DnsQueryRepository.kt 5.73 KB
Newer Older
1
2
package com.frostnerd.smokescreen.database.repository

3
import android.content.Context
Daniel Wolf's avatar
Daniel Wolf committed
4
5
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
6
import com.frostnerd.smokescreen.database.converters.StringListConverter
7
8
import com.frostnerd.smokescreen.database.dao.DnsQueryDao
import com.frostnerd.smokescreen.database.entities.DnsQuery
Daniel Wolf's avatar
Daniel Wolf committed
9
import com.frostnerd.smokescreen.dialog.QueryLogFilterDialog
10
import com.frostnerd.smokescreen.getPreferences
Daniel Wolf's avatar
Daniel Wolf committed
11
12
13
14
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
15
16
17
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
18

Daniel Wolf's avatar
Daniel Wolf committed
19
20
/*
 * Copyright (C) 2019 Daniel Wolf (Ch4t4r)
21
 *
Daniel Wolf's avatar
Daniel Wolf committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * You can contact the developer at daniel.wolf@frostnerd.com.
36
37
 */

Daniel Wolf's avatar
Daniel Wolf committed
38
class DnsQueryRepository(private val dnsQueryDao: DnsQueryDao) {
39

Daniel Wolf's avatar
Daniel Wolf committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    fun getAllWithFilterLive(filterConfig: QueryLogFilterDialog.FilterConfig): LiveData<List<DnsQuery>> {
        return dnsQueryDao.getAllWithFilterLive(filterConfig.showForwarded, filterConfig.showCache, filterConfig.showDnsrules, filterConfig.showBlockedByDns).let {
            filterDnsQuery(filterConfig, it)
        }
    }

    fun getAllWithHostAndFilterLive(hostPart:String, filterConfig: QueryLogFilterDialog.FilterConfig): LiveData<List<DnsQuery>> {
        return dnsQueryDao.getAllWithHostAndFilterLive(hostPart, filterConfig.showForwarded, filterConfig.showCache, filterConfig.showDnsrules, filterConfig.showBlockedByDns).let {
            filterDnsQuery(filterConfig, it)
        }
    }

    private fun filterDnsQuery(filterConfig: QueryLogFilterDialog.FilterConfig, liveData: LiveData<List<DnsQuery>>):LiveData<List<DnsQuery>> {
        if(filterConfig.showForwarded && filterConfig.showBlockedByDns) {
            return liveData
        } else{
            val holdsAllData = liveData.value?.let {
                dnsQueryDao.getCount() == it.size
            } ?: false

            return when {
                holdsAllData -> {
                    liveData
                }
                filterConfig.showForwarded -> {
                    Transformations.map(liveData) {
                        it.filter {
                            !it.isHostBlockedByDnsServer
                        }
                    }
                }
                else -> { // showForwarded = false, showBlockedByDns = true
                    Transformations.map(liveData) {
                        it.filter {
                            it.isHostBlockedByDnsServer
                        }
                    }
                }
            }
        }
    }

82
    fun insertAllAsync(dnsQueries:List<DnsQuery>): Job {
83
        return GlobalScope.launch(Dispatchers.IO) {
84
85
86
87
            dnsQueryDao.insertAll(dnsQueries)
        }
    }

88
89
90
    fun exportQueriesAsCsvAsync(context: Context,
                                fileReadyCallback:(createdFile: File) ->Unit,
                                countUpdateCallback:(count:Long, total:Int) -> Unit):Job {
91
92
93
        val exportDir = File(context.filesDir, "queryexport/")
        exportDir.mkdirs()
        val exportFile = File(exportDir, "queries.csv")
94
95
96
97
98
        val start = context.getPreferences().exportedQueryCount
        val existed = if(start == 0 && exportFile.exists()) {
            exportFile.delete()
            false
        } else exportFile.exists()
99
        return GlobalScope.launch(Dispatchers.IO) {
100
101
102
103
104
            val outStream = BufferedWriter(FileWriter(exportFile, true))
            if(!existed) {
                outStream.write("Name,Short Name,Type Name,Type ID,Asked Server,Answered from Cache,Question time,Response Time,Responses(JSON-Array of Base64)")
                outStream.newLine()
            }
105
106
            val builder = StringBuilder()
            val responseConverter = StringListConverter()
107
108

            val count = dnsQueryDao.getCount()
109
110
            var total = start.toLong()
            for(i in start..count step 5000) {
111
112
113
114
115
116
117
118
                val all = dnsQueryDao.getAll(5000, i.toLong())
                for (query in all) {
                    total++
                    builder.append(query.name).append(",")
                    builder.append(query.shortName).append(",")
                    builder.append(query.type.name).append(",")
                    builder.append(query.type.value).append(",")
                    builder.append(query.askedServer).append(",")
119
                    builder.append(query.responseSource.name).append(",")
120
121
122
123
124
125
126
                    builder.append(query.questionTime).append(",")
                    builder.append(query.responseTime).append(",")
                    builder.append("\"").append(responseConverter.someObjectListToString(query.responses).replace(",", ";").replace("\"", "'")).append("\"")
                    outStream.write(builder.toString())
                    outStream.newLine()
                    outStream.flush()
                    builder.clear()
127
                    if(total % 250 == 0L) countUpdateCallback(total, count)
128
                }
129
130
            }
            outStream.close()
131
            context.getPreferences().exportedQueryCount = count
132
133
134
            fileReadyCallback(exportFile)
        }
    }
135
}