summaryrefslogtreecommitdiff
path: root/app/src/main/java/foundation/e/advancedprivacy/domain/usecases/IpScramblingStateUseCase.kt
blob: 9c893290d24e1f7a41e00874c06af8130a7d4b08 (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
/*
 * Copyright (C) 2023 MURENA SAS
 * Copyright (C) 2021 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.domain.usecases

import android.content.Intent
import foundation.e.advancedprivacy.common.isStandaloneBuild
import foundation.e.advancedprivacy.data.repositories.AppListsRepository
import foundation.e.advancedprivacy.data.repositories.LocalStateRepository
import foundation.e.advancedprivacy.domain.entities.ApplicationDescription
import foundation.e.advancedprivacy.domain.entities.InternetPrivacyMode
import foundation.e.advancedprivacy.domain.entities.InternetPrivacyMode.HIDE_IP
import foundation.e.advancedprivacy.domain.entities.InternetPrivacyMode.HIDE_IP_LOADING
import foundation.e.advancedprivacy.domain.entities.InternetPrivacyMode.REAL_IP
import foundation.e.advancedprivacy.domain.entities.InternetPrivacyMode.REAL_IP_LOADING
import foundation.e.advancedprivacy.externalinterfaces.permissions.IPermissionsPrivacyModule
import foundation.e.advancedprivacy.ipscrambler.IpScramblerModule
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

class IpScramblingStateUseCase(
    private val ipScramblerModule: IpScramblerModule,
    private val permissionsPrivacyModule: IPermissionsPrivacyModule,
    private val appDesc: ApplicationDescription,
    private val localStateRepository: LocalStateRepository,
    private val appListsRepository: AppListsRepository,
    private val coroutineScope: CoroutineScope
) {
    val internetPrivacyMode: StateFlow<InternetPrivacyMode> = callbackFlow {
        val listener = object : IpScramblerModule.Listener {
            override fun onStatusChanged(newStatus: IpScramblerModule.Status) {
                trySend(map(newStatus))
            }

            override fun log(message: String) {}
            override fun onTrafficUpdate(
                upload: Long,
                download: Long,
                read: Long,
                write: Long
            ) {
            }
        }
        ipScramblerModule.addListener(listener)
        ipScramblerModule.requestStatus()
        awaitClose { ipScramblerModule.removeListener(listener) }
    }.stateIn(
        scope = coroutineScope,
        started = SharingStarted.Eagerly,
        initialValue = REAL_IP
    )

    init {
        coroutineScope.launch(Dispatchers.Default) {
            localStateRepository.ipScramblingSetting.collect {
                applySettings(it)
            }
        }

        coroutineScope.launch(Dispatchers.IO) {
            internetPrivacyMode.collect {
                if (
                    it == REAL_IP &&
                    localStateRepository.internetPrivacyMode.value == REAL_IP_LOADING
                ) {
                    // Wait for orbot to relax before allowing user to reactivate it.
                    delay(1000)
                }
                localStateRepository.internetPrivacyMode.value = it
            }
        }
    }

    fun toggle(hideIp: Boolean) {
        localStateRepository.setIpScramblingSetting(enabled = hideIp)
    }

    private fun getHiddenPackageNames(): List<String> {
        return appListsRepository.getMainProfileHiddenSystemApps().map { it.packageName }
    }

    val bypassTorApps: Set<String> get() {
        var whitelist = ipScramblerModule.appList
        if (getHiddenPackageNames().any { it in whitelist }) {
            val mutable = whitelist.toMutableSet()
            mutable.removeAll(getHiddenPackageNames())
            mutable.add(appListsRepository.dummySystemApp.packageName)
            whitelist = mutable
        }
        if (AppListsRepository.compatibiltyPNames.any { it in whitelist }) {
            val mutable = whitelist.toMutableSet()
            mutable.removeAll(AppListsRepository.compatibiltyPNames)
            mutable.add(appListsRepository.dummyCompatibilityApp.packageName)
            whitelist = mutable
        }
        return whitelist
    }

    fun toggleBypassTor(packageName: String) {
        val visibleList = bypassTorApps.toMutableSet()
        val rawList = ipScramblerModule.appList.toMutableSet()

        if (visibleList.contains(packageName)) {
            if (packageName == appListsRepository.dummySystemApp.packageName) {
                rawList.removeAll(getHiddenPackageNames())
            } else if (packageName == appListsRepository.dummyCompatibilityApp.packageName) {
                rawList.removeAll(AppListsRepository.compatibiltyPNames)
            } else {
                rawList.remove(packageName)
            }
        } else {
            if (packageName == appListsRepository.dummySystemApp.packageName) {
                rawList.addAll(getHiddenPackageNames())
            } else if (packageName == appListsRepository.dummyCompatibilityApp.packageName) {
                rawList.addAll(AppListsRepository.compatibiltyPNames)
            } else {
                rawList.add(packageName)
            }
        }
        ipScramblerModule.appList = rawList
    }

    private suspend fun applySettings(isIpScramblingEnabled: Boolean) {
        val currentMode = localStateRepository.internetPrivacyMode.value
        when {
            isIpScramblingEnabled && currentMode in setOf(REAL_IP, REAL_IP_LOADING) ->
                applyStartIpScrambling()

            !isIpScramblingEnabled && currentMode in setOf(HIDE_IP, HIDE_IP_LOADING) ->
                ipScramblerModule.stop()

            else -> {}
        }
    }

    private suspend fun applyStartIpScrambling() {
        val authorizeVpnIntent = ipScramblerModule.prepareAndroidVpn()
        if (authorizeVpnIntent == null) {
            localStateRepository.emitStartVpnDisclaimer(null)

            startIpScrambling()
            return
        }

        acquireVpnAuthorization(authorizeVpnIntent)
    }

    private suspend fun acquireVpnAuthorization(authorizeVpnIntent: Intent) {
        val authorized = permissionsPrivacyModule.setVpnPackageAuthorization(appDesc.packageName)
        val alwaysOnVpnPackage = permissionsPrivacyModule.getAlwaysOnVpnPackage()

        when {
            authorized && alwaysOnVpnPackage == null -> {
                localStateRepository.emitStartVpnDisclaimer(null)
                startIpScrambling()
            }
            authorized && alwaysOnVpnPackage != null -> {
                localStateRepository.emitOtherVpnRunning(
                    permissionsPrivacyModule.getApplicationDescription(
                        packageName = alwaysOnVpnPackage,
                        withIcon = false
                    )
                )
                localStateRepository.setIpScramblingSetting(enabled = false)
            }
            else -> localStateRepository.emitStartVpnDisclaimer(authorizeVpnIntent)
        }
    }

    fun startIpScrambling() {
        localStateRepository.internetPrivacyMode.value = HIDE_IP_LOADING
        ipScramblerModule.start(enableNotification = isStandaloneBuild)
    }

    private fun map(status: IpScramblerModule.Status): InternetPrivacyMode {
        return when (status) {
            IpScramblerModule.Status.OFF -> REAL_IP
            IpScramblerModule.Status.ON -> HIDE_IP
            IpScramblerModule.Status.STARTING -> HIDE_IP_LOADING
            IpScramblerModule.Status.STOPPING,
            IpScramblerModule.Status.START_DISABLED -> REAL_IP_LOADING
        }
    }
}