DnsQueryRepository.kt 5.43 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
    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>> {
Daniel Wolf's avatar
Daniel Wolf committed
53
54
55
56
57
58
59
        return if(filterConfig.showForwarded == filterConfig.showBlockedByDns) {
            liveData
        } else {
             if(filterConfig.showForwarded && !filterConfig.showBlockedByDns) {
                Transformations.map(liveData) {
                    it.filterNot { query ->
                        query.isHostBlockedByDnsServer
Daniel Wolf's avatar
Daniel Wolf committed
60
61
                    }
                }
Daniel Wolf's avatar
Daniel Wolf committed
62
63
64
65
            } else {
                Transformations.map(liveData) {
                    it.filter { query ->
                        query.isHostBlockedByDnsServer
Daniel Wolf's avatar
Daniel Wolf committed
66
67
68
69
70
71
                    }
                }
            }
        }
    }

72
    fun insertAllAsync(dnsQueries:List<DnsQuery>): Job {
73
        return GlobalScope.launch(Dispatchers.IO) {
74
75
76
77
            dnsQueryDao.insertAll(dnsQueries)
        }
    }

78
79
80
    fun exportQueriesAsCsvAsync(context: Context,
                                fileReadyCallback:(createdFile: File) ->Unit,
                                countUpdateCallback:(count:Long, total:Int) -> Unit):Job {
81
82
83
        val exportDir = File(context.filesDir, "queryexport/")
        exportDir.mkdirs()
        val exportFile = File(exportDir, "queries.csv")
84
85
86
87
88
        val start = context.getPreferences().exportedQueryCount
        val existed = if(start == 0 && exportFile.exists()) {
            exportFile.delete()
            false
        } else exportFile.exists()
89
        return GlobalScope.launch(Dispatchers.IO) {
90
91
92
93
94
            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()
            }
95
96
            val builder = StringBuilder()
            val responseConverter = StringListConverter()
97
98

            val count = dnsQueryDao.getCount()
99
100
            var total = start.toLong()
            for(i in start..count step 5000) {
101
102
103
104
105
106
107
108
                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(",")
109
                    builder.append(query.responseSource.name).append(",")
110
111
112
113
114
115
116
                    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()
117
                    if(total % 250 == 0L) countUpdateCallback(total, count)
118
                }
119
120
            }
            outStream.close()
121
            context.getPreferences().exportedQueryCount = count
122
123
124
            fileReadyCallback(exportFile)
        }
    }
125
}