aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/foundation/e/advancedprivacy/features/dashboard/DashboardViewModel.kt
blob: 8259c89e2bf6d227a9b52fdb608bf99afb921d12 (plain) (blame)
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
/*
 * 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.features.dashboard

import androidx.annotation.StringRes
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavDirections
import foundation.e.advancedprivacy.R
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
import foundation.e.advancedprivacy.domain.usecases.TrackersStatisticsUseCase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class DashboardViewModel(
    private val getPrivacyStateUseCase: GetQuickPrivacyStateUseCase,
    private val trackersStatisticsUseCase: TrackersStatisticsUseCase,
) : ViewModel() {

    private val _state = MutableStateFlow(DashboardState())
    val state = _state.asStateFlow()

    private val _singleEvents = MutableSharedFlow<SingleEvent>()
    val singleEvents = _singleEvents.asSharedFlow()

    private val _navigate = MutableSharedFlow<NavDirections>()
    val navigate = _navigate.asSharedFlow()
    init {
        viewModelScope.launch(Dispatchers.IO) { trackersStatisticsUseCase.initAppList() }
    }

    suspend fun doOnStartedState() = withContext(Dispatchers.IO) {
        merge(
            getPrivacyStateUseCase.quickPrivacyState.map {
                _state.update { s -> s.copy(quickPrivacyState = it) }
            },
            getPrivacyStateUseCase.ipScramblingMode.map {
                _state.update { s -> s.copy(ipScramblingMode = it) }
            },
            trackersStatisticsUseCase.listenUpdates().flatMapLatest {
                fetchStatistics()
            },
            getPrivacyStateUseCase.trackerMode.map {
                _state.update { s -> s.copy(trackerMode = it) }
            },
            getPrivacyStateUseCase.isLocationHidden.map {
                _state.update { s -> s.copy(isLocationHidden = it) }
            },
            getPrivacyStateUseCase.locationMode.map {
                _state.update { s -> s.copy(locationMode = it) }
            },
            getPrivacyStateUseCase.otherVpnRunning.map {
                _singleEvents.emit(
                    SingleEvent.ToastMessageSingleEvent(
                        R.string.ipscrambling_error_always_on_vpn_already_running,
                        listOf(it.label ?: "")
                    )
                )
            }
        ).collect {}
    }

    fun submitAction(action: Action) = viewModelScope.launch {
        when (action) {
            is Action.ToggleTrackers -> {
                getPrivacyStateUseCase.toggleTrackers(action.enabled)
                // Add delay here to prevent race condition with trackers state.
                delay(200)
                fetchStatistics().first()
            }
            is Action.ToggleLocation -> getPrivacyStateUseCase.toggleLocation(action.enabled)
            is Action.ToggleIpScrambling ->
                getPrivacyStateUseCase.toggleIpScrambling(action.enabled)
            is Action.ShowFakeMyLocationAction ->
                _navigate.emit(DashboardFragmentDirections.gotoFakeLocationFragment())
            is Action.ShowAppsPermissions ->
                _navigate.emit(DashboardFragmentDirections.gotoSettingsPermissionsActivity())
            is Action.ShowInternetActivityPrivacyAction ->
                _navigate.emit(DashboardFragmentDirections.gotoInternetPrivacyFragment())
            is Action.ShowTrackers ->
                _navigate.emit(DashboardFragmentDirections.gotoTrackersFragment())
            is Action.ShowMostLeakedApp -> actionShowMostLeakedApp()
        }
    }

    private suspend fun fetchStatistics(): Flow<Unit> = withContext(Dispatchers.IO) {
        trackersStatisticsUseCase.getNonBlockedTrackersCount().map { nonBlockedTrackersCount ->
            trackersStatisticsUseCase.getDayStatistics().let { (dayStatistics, trackersCount) ->
                _state.update { s ->
                    s.copy(
                        dayStatistics = dayStatistics.callsBlockedNLeaked,
                        dayLabels = dayStatistics.periods,
                        dayGraduations = dayStatistics.graduations,
                        leakedTrackersCount = dayStatistics.trackersCount,
                        trackersCount = trackersCount,
                        allowedTrackersCount = nonBlockedTrackersCount
                    )
                }
            }
        }
    }

    private suspend fun actionShowMostLeakedApp() = withContext(Dispatchers.IO) {
        _navigate.emit(
            trackersStatisticsUseCase.getMostLeakedApp()?.let {
                DashboardFragmentDirections.gotoAppTrackersFragment(appUid = it.uid)
            } ?: DashboardFragmentDirections.gotoTrackersFragment()
        )
    }

    sealed class SingleEvent {
        data class ToastMessageSingleEvent(
            @StringRes val message: Int,
            val args: List<Any> = emptyList()
        ) : SingleEvent()
    }

    sealed class Action {
        data class ToggleTrackers(val enabled: Boolean) : Action()
        data class ToggleLocation(val enabled: Boolean) : Action()
        data class ToggleIpScrambling(val enabled: Boolean) : Action()
        object ShowFakeMyLocationAction : Action()
        object ShowInternetActivityPrivacyAction : Action()
        object ShowAppsPermissions : Action()
        object ShowTrackers : Action()
        object ShowMostLeakedApp : Action()
    }
}