summaryrefslogtreecommitdiff
path: root/trackers/src/main/java/foundation/e/advancedprivacy/trackers/data/WhitelistRepository.kt
blob: 429c5e94380687c73af9d029e00a29596d5a285b (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
/*
 * Copyright (C) 2023 MURENA SAS
 * Copyright (C) 2022 E FOUNDATION
 *
 * 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.trackers.data

import android.content.Context
import android.content.SharedPreferences
import foundation.e.advancedprivacy.data.repositories.AppListsRepository
import foundation.e.advancedprivacy.domain.entities.ApplicationDescription
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
import java.io.File

class WhitelistRepository(
    context: Context,
    private val appListsRepository: AppListsRepository
) {
    private var appsWhitelist: Set<String> = HashSet()
    private var appUidsWhitelist: Set<Int> = HashSet()

    private var trackersWhitelistByApp: MutableMap<String, MutableSet<String>> = HashMap()
    private var trackersWhitelistByUid: Map<Int, MutableSet<String>> = HashMap()

    private val prefs: SharedPreferences

    companion object {
        private const val SHARED_PREFS_FILE = "trackers_whitelist_v2"
        private const val KEY_BLOCKING_ENABLED = "blocking_enabled"
        private const val KEY_APPS_WHITELIST = "apps_whitelist"
        private const val KEY_APP_TRACKERS_WHITELIST_PREFIX = "app_trackers_whitelist_"

        private const val SHARED_PREFS_FILE_V1 = "trackers_whitelist.prefs"
    }

    init {
        prefs = context.getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE)
        reloadCache()
        migrate(context)
    }

    private fun migrate(context: Context) {
        if (context.sharedPreferencesExists(SHARED_PREFS_FILE_V1)) {
            migrate1To2(context)
        }
    }

    private fun Context.sharedPreferencesExists(fileName: String): Boolean {
        return File(
            "${applicationInfo.dataDir}/shared_prefs/$fileName.xml"
        ).exists()
    }

    private fun migrate1To2(context: Context) {
        val prefsV1 = context.getSharedPreferences(SHARED_PREFS_FILE_V1, Context.MODE_PRIVATE)
        val editorV2 = prefs.edit()

        editorV2.putBoolean(KEY_BLOCKING_ENABLED, prefsV1.getBoolean(KEY_BLOCKING_ENABLED, false))

        val apIds = prefsV1.getStringSet(KEY_APPS_WHITELIST, HashSet())?.mapNotNull {
            try {
                val uid = it.toInt()
                appListsRepository.getApp(uid)?.apId
            } catch (e: Exception) { null }
        }?.toSet() ?: HashSet()

        editorV2.putStringSet(KEY_APPS_WHITELIST, apIds)

        prefsV1.all.keys.forEach { key ->
            if (key.startsWith(KEY_APP_TRACKERS_WHITELIST_PREFIX)) {
                try {
                    val uid = key.substring(KEY_APP_TRACKERS_WHITELIST_PREFIX.length).toInt()
                    val apId = appListsRepository.getApp(uid)?.apId
                    apId?.let {
                        val trackers = prefsV1.getStringSet(key, emptySet())
                        editorV2.putStringSet(buildAppTrackersKey(apId), trackers)
                    }
                } catch (e: Exception) { }
            }
        }
        editorV2.commit()

        context.deleteSharedPreferences(SHARED_PREFS_FILE_V1)

        reloadCache()
    }

    private fun reloadCache() {
        isBlockingEnabled = prefs.getBoolean(KEY_BLOCKING_ENABLED, false)
        reloadAppsWhiteList()
        reloadAllAppTrackersWhiteList()
    }

    private fun reloadAppsWhiteList() {
        appsWhitelist = prefs.getStringSet(KEY_APPS_WHITELIST, HashSet()) ?: HashSet()
        appUidsWhitelist = appsWhitelist
            .mapNotNull { apId -> appListsRepository.getApp(apId)?.uid }
            .toSet()
    }

    private fun refreshAppUidTrackersWhiteList() {
        trackersWhitelistByUid = trackersWhitelistByApp.mapNotNull { (apId, value) ->
            appListsRepository.getApp(apId)?.uid?.let { uid ->
                uid to value
            }
        }.toMap()
    }
    private fun reloadAllAppTrackersWhiteList() {
        val map: MutableMap<String, MutableSet<String>> = HashMap()
        prefs.all.keys.forEach { key ->
            if (key.startsWith(KEY_APP_TRACKERS_WHITELIST_PREFIX)) {
                map[key.substring(KEY_APP_TRACKERS_WHITELIST_PREFIX.length)] = (
                    prefs.getStringSet(key, HashSet()) ?: HashSet()
                    )
            }
        }
        trackersWhitelistByApp = map
    }

    var isBlockingEnabled: Boolean = false
        get() = field
        set(enabled) {
            prefs.edit().putBoolean(KEY_BLOCKING_ENABLED, enabled).apply()
            field = enabled
        }

    fun setWhiteListed(apId: String, isWhiteListed: Boolean) {
        val current = prefs.getStringSet(KEY_APPS_WHITELIST, HashSet())?.toHashSet() ?: HashSet()

        if (isWhiteListed) {
            current.add(apId)
        } else {
            current.remove(apId)
        }
        prefs.edit().putStringSet(KEY_APPS_WHITELIST, current).commit()
        reloadAppsWhiteList()
    }

    private fun buildAppTrackersKey(apId: String): String {
        return KEY_APP_TRACKERS_WHITELIST_PREFIX + apId
    }

    fun setWhiteListed(tracker: Tracker, apId: String, isWhiteListed: Boolean) {
        val trackers = trackersWhitelistByApp.getOrDefault(apId, HashSet())
        trackersWhitelistByApp[apId] = trackers

        if (isWhiteListed) {
            trackers.add(tracker.id)
        } else {
            trackers.remove(tracker.id)
        }
        refreshAppUidTrackersWhiteList()
        prefs.edit().putStringSet(buildAppTrackersKey(apId), trackers).commit()
    }

    fun isAppWhiteListed(app: ApplicationDescription): Boolean {
        return appsWhitelist.contains(app.apId)
    }

    fun isWhiteListed(appUid: Int, trackerId: String?): Boolean {
        return appUidsWhitelist.contains(appUid) ||
            trackersWhitelistByUid.getOrDefault(appUid, HashSet()).contains(trackerId)
    }

    fun areWhiteListEmpty(): Boolean {
        return appsWhitelist.isEmpty() && trackersWhitelistByApp.all { (_, trackers) -> trackers.isEmpty() }
    }

    fun getWhiteListedApp(): List<ApplicationDescription> {
        return appsWhitelist.mapNotNull(appListsRepository::getApp)
    }

    fun getWhiteListForApp(app: ApplicationDescription): List<String> {
        return trackersWhitelistByApp[app.apId]?.toList() ?: emptyList()
    }

    fun clearWhiteList(apId: String) {
        trackersWhitelistByApp.remove(apId)
        refreshAppUidTrackersWhiteList()
        prefs.edit().remove(buildAppTrackersKey(apId)).commit()
    }
}