summaryrefslogtreecommitdiff
path: root/app/src/main/java/foundation/e/advancedprivacy/domain/usecases/TrackersStatisticsUseCase.kt
blob: b0c9f39114c638101eef35a10ac2fd8646a36b9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
 * Copyright (C) 2021 E FOUNDATION, 2022 - 2023 MURENA SAS
 *
 * 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 <https://www.gnu.org/licenses/>.
 */

package foundation.e.advancedprivacy.domain.usecases

import android.content.res.Resources
import foundation.e.advancedprivacy.R
import foundation.e.advancedprivacy.common.throttleFirst
import foundation.e.advancedprivacy.data.repositories.AppListsRepository
import foundation.e.advancedprivacy.domain.entities.AppWithCounts
import foundation.e.advancedprivacy.domain.entities.ApplicationDescription
import foundation.e.advancedprivacy.domain.entities.TrackersPeriodicStatistics
import foundation.e.advancedprivacy.trackers.data.TrackersRepository
import foundation.e.advancedprivacy.trackers.data.WhitelistRepository
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
import foundation.e.advancedprivacy.trackers.domain.usecases.StatisticsUseCase
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds

class TrackersStatisticsUseCase(
    private val statisticsUseCase: StatisticsUseCase,
    private val whitelistRepository: WhitelistRepository,
    private val trackersRepository: TrackersRepository,
    private val appListsRepository: AppListsRepository,
    private val resources: Resources
) {
    fun initAppList() {
        appListsRepository.apps()
    }

    @OptIn(FlowPreview::class)
    fun listenUpdates(debounce: Duration = 1.seconds) =
        statisticsUseCase.newDataAvailable
            .throttleFirst(windowDuration = debounce)
            .onStart { emit(Unit) }

    fun getDayStatistics(): Pair<TrackersPeriodicStatistics, Int> {
        return TrackersPeriodicStatistics(
            callsBlockedNLeaked = statisticsUseCase.getTrackersCallsOnPeriod(24, ChronoUnit.HOURS),
            periods = buildDayLabels(),
            trackersCount = statisticsUseCase.getActiveTrackersByPeriod(24, ChronoUnit.HOURS),
            graduations = buildDayGraduations(),
        ) to statisticsUseCase.getContactedTrackersCount()
    }

    fun getNonBlockedTrackersCount(): Flow<Int> {
        return if (whitelistRepository.isBlockingEnabled)
            appListsRepository.allApps().map { apps ->
                val whiteListedTrackers = mutableSetOf<Tracker>()
                val whiteListedApps = whitelistRepository.getWhiteListedApp()
                apps.forEach { app ->
                    if (app in whiteListedApps) {
                        whiteListedTrackers.addAll(statisticsUseCase.getTrackers(listOf(app)))
                    } else {
                        whiteListedTrackers.addAll(getWhiteList(app))
                    }
                }
                whiteListedTrackers.size
            }
        else flowOf(statisticsUseCase.getContactedTrackersCount())
    }

    fun getMostLeakedApp(): ApplicationDescription? {
        return statisticsUseCase.getMostLeakedApp(24, ChronoUnit.HOURS)
    }

    fun getDayTrackersCalls() = statisticsUseCase.getTrackersCallsOnPeriod(24, ChronoUnit.HOURS)

    fun getDayTrackersCount() = statisticsUseCase.getActiveTrackersByPeriod(24, ChronoUnit.HOURS)

    private fun buildDayGraduations(): List<String?> {
        val formatter = DateTimeFormatter.ofPattern(
            resources.getString(R.string.trackers_graph_hours_period_format)
        )

        val periods = mutableListOf<String?>()
        var end = ZonedDateTime.now()
        for (i in 1..24) {
            val start = end.truncatedTo(ChronoUnit.HOURS)
            periods.add(if (start.hour % 6 == 0) formatter.format(start) else null)
            end = start.minus(1, ChronoUnit.MINUTES)
        }
        return periods.reversed()
    }

    private fun buildDayLabels(): List<String> {
        val formatter = DateTimeFormatter.ofPattern(
            resources.getString(R.string.trackers_graph_hours_period_format)
        )
        val periods = mutableListOf<String>()
        var end = ZonedDateTime.now()
        for (i in 1..24) {
            val start = end.truncatedTo(ChronoUnit.HOURS)
            periods.add("${formatter.format(start)} - ${formatter.format(end)}")
            end = start.minus(1, ChronoUnit.MINUTES)
        }
        return periods.reversed()
    }

    private fun buildMonthLabels(): List<String> {
        val formater = DateTimeFormatter.ofPattern(
            resources.getString(R.string.trackers_graph_days_period_format)
        )
        val periods = mutableListOf<String>()
        var day = ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS)
        for (i in 1..30) {
            periods.add(formater.format(day))
            day = day.minus(1, ChronoUnit.DAYS)
        }
        return periods.reversed()
    }

    private fun buildYearLabels(): List<String> {
        val formater = DateTimeFormatter.ofPattern(
            resources.getString(R.string.trackers_graph_months_period_format)
        )
        val periods = mutableListOf<String>()
        var month = ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1)
        for (i in 1..12) {
            periods.add(formater.format(month))
            month = month.minus(1, ChronoUnit.MONTHS)
        }
        return periods.reversed()
    }

    fun getDayMonthYearStatistics(): Triple<TrackersPeriodicStatistics, TrackersPeriodicStatistics, TrackersPeriodicStatistics> {
        return Triple(
            TrackersPeriodicStatistics(
                callsBlockedNLeaked = statisticsUseCase.getTrackersCallsOnPeriod(24, ChronoUnit.HOURS),
                periods = buildDayLabels(),
                trackersCount = statisticsUseCase.getActiveTrackersByPeriod(24, ChronoUnit.HOURS)
            ),
            TrackersPeriodicStatistics(
                callsBlockedNLeaked = statisticsUseCase.getTrackersCallsOnPeriod(30, ChronoUnit.DAYS),
                periods = buildMonthLabels(),
                trackersCount = statisticsUseCase.getActiveTrackersByPeriod(30, ChronoUnit.DAYS)
            ),
            TrackersPeriodicStatistics(
                callsBlockedNLeaked = statisticsUseCase.getTrackersCallsOnPeriod(12, ChronoUnit.MONTHS),
                periods = buildYearLabels(),
                trackersCount = statisticsUseCase.getActiveTrackersByPeriod(12, ChronoUnit.MONTHS)
            )
        )
    }

    fun getTrackersWithWhiteList(app: ApplicationDescription): List<Pair<Tracker, Boolean>> {
        return appListsRepository.mapReduceForHiddenApps(
            app = app,
            map = { appDesc: ApplicationDescription ->
                (
                    statisticsUseCase.getTrackers(listOf(appDesc)) to
                        getWhiteList(appDesc)
                    )
            },
            reduce = { lists ->
                lists.unzip().let { (trackerLists, whiteListedIdLists) ->
                    val whiteListedIds = whiteListedIdLists.flatten().map { it.id }.toSet()

                    trackerLists.flatten().distinctBy { it.id }.sortedBy { it.label.lowercase() }
                        .map { tracker -> tracker to (tracker.id in whiteListedIds) }
                }
            }
        )
    }

    fun isWhiteListEmpty(app: ApplicationDescription): Boolean {
        return appListsRepository.mapReduceForHiddenApps(
            app = app,
            map = { appDesc: ApplicationDescription ->
                getWhiteList(appDesc).isEmpty()
            },
            reduce = { areEmpty -> areEmpty.all { it } }
        )
    }

    fun getCalls(app: ApplicationDescription): Pair<Int, Int> {
        return appListsRepository.mapReduceForHiddenApps(
            app = app,
            map = {
                statisticsUseCase.getCalls(it, 24, ChronoUnit.HOURS)
            },
            reduce = { zip ->
                zip.unzip().let { (blocked, leaked) ->
                    blocked.sum() to leaked.sum()
                }
            }
        )
    }

    fun getAppsWithCounts(): Flow<List<AppWithCounts>> {
        val trackersCounts = statisticsUseCase.getContactedTrackersCountByApp()
        val hiddenAppsTrackersWithWhiteList =
            getTrackersWithWhiteList(appListsRepository.dummySystemApp)
        val acAppsTrackersWithWhiteList =
            getTrackersWithWhiteList(appListsRepository.dummyCompatibilityApp)

        return appListsRepository.apps()
            .map { apps ->
                val callsByApp = statisticsUseCase.getCallsByApps(24, ChronoUnit.HOURS)
                apps.map { app ->
                    val calls = appListsRepository.mapReduceForHiddenApps(
                        app = app,
                        map = { callsByApp.getOrDefault(app, 0 to 0) },
                        reduce = {
                            it.unzip().let { (blocked, leaked) ->
                                blocked.sum() to leaked.sum()
                            }
                        }
                    )

                    AppWithCounts(
                        app = app,
                        isWhitelisted = !whitelistRepository.isBlockingEnabled ||
                            isWhitelisted(app, appListsRepository, whitelistRepository),
                        trackersCount = when (app) {
                            appListsRepository.dummySystemApp ->
                                hiddenAppsTrackersWithWhiteList.size
                            appListsRepository.dummyCompatibilityApp ->
                                acAppsTrackersWithWhiteList.size
                            else -> trackersCounts.getOrDefault(app, 0)
                        },
                        whiteListedTrackersCount = when (app) {
                            appListsRepository.dummySystemApp ->
                                hiddenAppsTrackersWithWhiteList.count { it.second }
                            appListsRepository.dummyCompatibilityApp ->
                                acAppsTrackersWithWhiteList.count { it.second }
                            else ->
                                getWhiteList(app).size
                        },
                        blockedLeaks = calls.first,
                        leaks = calls.second
                    )
                }
                    .sortedWith(mostLeakedAppsComparator)
            }
    }

    private fun getWhiteList(app: ApplicationDescription): List<Tracker> {
        return whitelistRepository.getWhiteListForApp(app).mapNotNull {
            trackersRepository.getTracker(it)
        }
    }

    private val mostLeakedAppsComparator: Comparator<AppWithCounts> = Comparator { o1, o2 ->
        val leaks = o2.leaks - o1.leaks
        if (leaks != 0) leaks else {
            val whitelisted = o2.whiteListedTrackersCount - o1.whiteListedTrackersCount
            if (whitelisted != 0) whitelisted else {
                o2.trackersCount - o1.trackersCount
            }
        }
    }
}