summaryrefslogtreecommitdiff
path: root/PermissionController/src/com/android/permissioncontroller/permission/ui/model/PermissionAppsViewModel.kt
blob: 1b17041b620d4e267d98517433b89dd7b485f714 (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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
@file:Suppress("DEPRECATION")

package com.android.permissioncontroller.permission.ui.model

import android.Manifest
import android.Manifest.permission_group.LOCATION
import android.app.Application
import android.content.Intent
import android.content.res.Resources
import android.hardware.SensorPrivacyManager
import android.os.Build
import android.os.Bundle
import android.os.UserHandle
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.lifecycle.AbstractSavedStateViewModelFactory
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.navigation.fragment.findNavController
import androidx.preference.Preference
import androidx.savedstate.SavedStateRegistryOwner
import com.android.modules.utils.build.SdkLevel
import com.android.permissioncontroller.PermissionControllerStatsLog
import com.android.permissioncontroller.PermissionControllerStatsLog.PERMISSION_APPS_FRAGMENT_VIEWED__CATEGORY__ALLOWED
import com.android.permissioncontroller.PermissionControllerStatsLog.PERMISSION_APPS_FRAGMENT_VIEWED__CATEGORY__ALLOWED_FOREGROUND
import com.android.permissioncontroller.PermissionControllerStatsLog.PERMISSION_APPS_FRAGMENT_VIEWED__CATEGORY__DENIED
import com.android.permissioncontroller.PermissionControllerStatsLog.PERMISSION_APPS_FRAGMENT_VIEWED__CATEGORY__UNDEFINED
import com.android.permissioncontroller.R
import com.android.permissioncontroller.permission.data.AllPackageInfosLiveData
import com.android.permissioncontroller.permission.data.FullStoragePermissionAppsLiveData
import com.android.permissioncontroller.permission.data.FullStoragePermissionAppsLiveData.FullStoragePackageState
import com.android.permissioncontroller.permission.data.SinglePermGroupPackagesUiInfoLiveData
import com.android.permissioncontroller.permission.data.SmartUpdateMediatorLiveData
import com.android.permissioncontroller.permission.model.livedatatypes.AppPermGroupUiInfo.PermGrantState
import com.android.permissioncontroller.permission.model.v31.AppPermissionUsage
import com.android.permissioncontroller.permission.ui.Category
import com.android.permissioncontroller.permission.ui.LocationProviderInterceptDialog
import com.android.permissioncontroller.permission.ui.model.PermissionAppsViewModel.Companion.CREATION_LOGGED_KEY
import com.android.permissioncontroller.permission.ui.model.PermissionAppsViewModel.Companion.HAS_SYSTEM_APPS_KEY
import com.android.permissioncontroller.permission.ui.model.PermissionAppsViewModel.Companion.SHOULD_SHOW_SYSTEM_KEY
import com.android.permissioncontroller.permission.ui.model.PermissionAppsViewModel.Companion.SHOW_ALWAYS_ALLOWED
import com.android.permissioncontroller.permission.utils.KotlinUtils.getPackageUid
import com.android.permissioncontroller.permission.utils.KotlinUtils.is7DayToggleEnabled
import com.android.permissioncontroller.permission.utils.LocationUtils
import com.android.permissioncontroller.permission.utils.Utils
import com.android.permissioncontroller.permission.utils.navigateSafe
import java.text.Collator
import java.time.Instant
import java.util.concurrent.TimeUnit
import kotlin.math.max

/**
 * ViewModel for the PermissionAppsFragment. Has a liveData with all of the UI info for each
 * package which requests permissions in this permission group, a liveData which tracks whether or
 * not to show system apps, and a liveData tracking whether there are any system apps which request
 * permissions in this group.
 *
 * @param app The current application
 * @param groupName The name of the permission group this viewModel is representing
 */
class PermissionAppsViewModel(
    private val state: SavedStateHandle,
    private val app: Application,
    private val groupName: String
) : ViewModel() {

    companion object {
        const val AGGREGATE_DATA_FILTER_BEGIN_DAYS_1 = 1
        const val AGGREGATE_DATA_FILTER_BEGIN_DAYS_7 = 7
        internal const val SHOULD_SHOW_SYSTEM_KEY = "showSystem"
        internal const val HAS_SYSTEM_APPS_KEY = "hasSystem"
        internal const val SHOW_ALWAYS_ALLOWED = "showAlways"
        internal const val CREATION_LOGGED_KEY = "creationLogged"
    }

    val shouldShowSystemLiveData = state.getLiveData(SHOULD_SHOW_SYSTEM_KEY, false)
    val hasSystemAppsLiveData = state.getLiveData(HAS_SYSTEM_APPS_KEY, true)
    val showAllowAlwaysStringLiveData = state.getLiveData(SHOW_ALWAYS_ALLOWED, false)
    val categorizedAppsLiveData = CategorizedAppsLiveData(groupName)

    @get:RequiresApi(Build.VERSION_CODES.S)
    val sensorStatusLiveData: SensorStatusLiveData by lazy(LazyThreadSafetyMode.NONE)
    @RequiresApi(Build.VERSION_CODES.S) {
        SensorStatusLiveData()
    }

    fun updateShowSystem(showSystem: Boolean) {
        if (showSystem != state.get(SHOULD_SHOW_SYSTEM_KEY)) {
            state.set(SHOULD_SHOW_SYSTEM_KEY, showSystem)
        }
    }

    var creationLogged
        get() = state.get(CREATION_LOGGED_KEY) ?: false
        set(value) = state.set(CREATION_LOGGED_KEY, value)

    /**
     * A LiveData that tracks the status (blocked or available) of a sensor
     */
    @RequiresApi(Build.VERSION_CODES.S)
    inner class SensorStatusLiveData() : SmartUpdateMediatorLiveData<Boolean>() {
        val sensorPrivacyManager = app.getSystemService(SensorPrivacyManager::class.java)!!
        val sensor = Utils.getSensorCode(groupName)
        val isLocation = LOCATION.equals(groupName)

        init {
            checkAndUpdateStatus()
        }

        fun checkAndUpdateStatus() {
            var blocked: Boolean

            if (isLocation) {
                blocked = !LocationUtils.isLocationEnabled(app.getApplicationContext())
            } else {
                blocked = sensorPrivacyManager.isSensorPrivacyEnabled(sensor)
            }

            if (blocked) {
                value = blocked
            }
        }

        override fun onActive() {
            super.onActive()
            checkAndUpdateStatus()
            if (isLocation) {
                LocationUtils.addLocationListener(locListener)
            } else {
                sensorPrivacyManager.addSensorPrivacyListener(sensor, listener)
            }
        }

        override fun onInactive() {
            super.onInactive()
            if (isLocation) {
                LocationUtils.removeLocationListener(locListener)
            } else {
                sensorPrivacyManager.removeSensorPrivacyListener(sensor, listener)
            }
        }

        private val listener = { _: Int, status: Boolean ->
            value = status
        }

        private val locListener = { status: Boolean ->
            value = !status
        }

        override fun onUpdate() {
            // Do nothing
        }
    }

    inner class CategorizedAppsLiveData(groupName: String) :
        MediatorLiveData<@kotlin.jvm.JvmSuppressWildcards
    Map<Category, List<Pair<String, UserHandle>>>>() {
        private val packagesUiInfoLiveData = SinglePermGroupPackagesUiInfoLiveData[groupName]

        init {
            var fullStorageLiveData: FullStoragePermissionAppsLiveData? = null

            // If this is the Storage group, observe a FullStoragePermissionAppsLiveData, update
            // the packagesWithFullFileAccess list, and call update to populate the subtitles.
            if (groupName == Manifest.permission_group.STORAGE) {
                fullStorageLiveData = FullStoragePermissionAppsLiveData
                addSource(FullStoragePermissionAppsLiveData) { fullAccessPackages ->
                    if (fullAccessPackages != packagesWithFullFileAccess) {
                        packagesWithFullFileAccess = fullAccessPackages.filter { it.isGranted }
                        if (packagesUiInfoLiveData.isInitialized) {
                            update()
                        }
                    }
                }
            }

            addSource(packagesUiInfoLiveData) {
                if (fullStorageLiveData == null || fullStorageLiveData.isInitialized)
                    update()
            }
            addSource(shouldShowSystemLiveData) {
                if (fullStorageLiveData == null || fullStorageLiveData.isInitialized)
                    update()
            }

            if ((fullStorageLiveData == null || fullStorageLiveData.isInitialized) &&
                packagesUiInfoLiveData.isInitialized) {
                packagesWithFullFileAccess = fullStorageLiveData?.value?.filter { it.isGranted }
                    ?: emptyList()
                update()
            }
        }

        fun update() {
            val categoryMap = mutableMapOf<Category, MutableList<Pair<String, UserHandle>>>()
            val showSystem: Boolean = state.get(SHOULD_SHOW_SYSTEM_KEY) ?: false

            categoryMap[Category.ALLOWED] = mutableListOf()
            categoryMap[Category.ALLOWED_FOREGROUND] = mutableListOf()
            categoryMap[Category.ASK] = mutableListOf()
            categoryMap[Category.DENIED] = mutableListOf()

            val packageMap = packagesUiInfoLiveData.value ?: run {
                if (packagesUiInfoLiveData.isInitialized) {
                    value = categoryMap
                }
                return
            }

            val hasSystem = packageMap.any { it.value.isSystem && it.value.shouldShow }
            if (hasSystem != state.get(HAS_SYSTEM_APPS_KEY)) {
                state.set(HAS_SYSTEM_APPS_KEY, hasSystem)
            }

            var showAlwaysAllowedString = false

            for ((packageUserPair, uiInfo) in packageMap) {
                if (!uiInfo.shouldShow) {
                    continue
                }

                if (uiInfo.isSystem && !showSystem) {
                    continue
                }

                if (uiInfo.permGrantState == PermGrantState.PERMS_ALLOWED_ALWAYS ||
                    uiInfo.permGrantState == PermGrantState.PERMS_ALLOWED_FOREGROUND_ONLY) {
                    showAlwaysAllowedString = true
                }

                var category = when (uiInfo.permGrantState) {
                    PermGrantState.PERMS_ALLOWED -> Category.ALLOWED
                    PermGrantState.PERMS_ALLOWED_FOREGROUND_ONLY -> Category.ALLOWED_FOREGROUND
                    PermGrantState.PERMS_ALLOWED_ALWAYS -> Category.ALLOWED
                    PermGrantState.PERMS_DENIED -> Category.DENIED
                    PermGrantState.PERMS_ASK -> Category.ASK
                }

                if (!SdkLevel.isAtLeastT() && groupName == Manifest.permission_group.STORAGE &&
                    packagesWithFullFileAccess.any { !it.isLegacy && it.isGranted &&
                        it.packageName to it.user == packageUserPair }) {
                    category = Category.ALLOWED
                }
                categoryMap[category]!!.add(packageUserPair)
            }
            showAllowAlwaysStringLiveData.value = showAlwaysAllowedString
            value = categoryMap
        }
    }

    /**
     * If this is the storage permission group, some apps have full access to storage, while
     * others just have access to media files. This list contains the packages with full access.
     * To listen for changes, create and observe a FullStoragePermissionAppsLiveData
     */
    private var packagesWithFullFileAccess = listOf<FullStoragePackageState>()

    /**
     * Whether or not to show the "Files and Media" subtitle label for a package, vs. the normal
     * "Media". Requires packagesWithFullFileAccess to be updated in order to work. To do this,
     * create and observe a FullStoragePermissionAppsLiveData.
     *
     * @param packageName The name of the package we want to check
     * @param user The name of the user whose package we want to check
     *
     * @return true if the package and user has full file access
     */
    fun packageHasFullStorage(packageName: String, user: UserHandle): Boolean {
        return packagesWithFullFileAccess.any {
            it.packageName == packageName && it.user == user }
    }

    /**
     * Whether or not packages have been loaded from the system.
     * To update, need to observe the allPackageInfosLiveData.
     *
     * @return Whether or not all packages have been loaded
     */
    fun arePackagesLoaded(): Boolean {
        return AllPackageInfosLiveData.isInitialized
    }

    /**
     * Navigate to an AppPermissionFragment, unless this is a special location package
     *
     * @param fragment The fragment attached to this ViewModel
     * @param packageName The package name we want to navigate to
     * @param user The user we want to navigate to the package of
     * @param args The arguments to pass onto the fragment
     */
    fun navigateToAppPermission(
        fragment: Fragment,
        packageName: String,
        user: UserHandle,
        args: Bundle
    ) {
        val activity = fragment.activity!!
        if (LocationUtils.isLocationGroupAndProvider(
                activity, groupName, packageName)) {
            val intent = Intent(activity, LocationProviderInterceptDialog::class.java)
            intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName)
            activity.startActivityAsUser(intent, user)
            return
        }

        if (LocationUtils.isLocationGroupAndControllerExtraPackage(
                activity, groupName, packageName)) {
            // Redirect to location controller extra package settings.
            LocationUtils.startLocationControllerExtraPackageSettings(activity, user)
            return
        }

        fragment.findNavController().navigateSafe(R.id.perm_apps_to_app, args)
    }

    fun getFilterTimeBeginMillis(): Long {
        val aggregateDataFilterBeginDays = if (is7DayToggleEnabled())
            AGGREGATE_DATA_FILTER_BEGIN_DAYS_7 else AGGREGATE_DATA_FILTER_BEGIN_DAYS_1

        return max(System.currentTimeMillis() -
                TimeUnit.DAYS.toMillis(aggregateDataFilterBeginDays.toLong()),
                Instant.EPOCH.toEpochMilli())
    }

    /**
     * Return a mapping of user + packageName to their last access timestamps for the permission
     * group.
     */
    fun extractGroupUsageLastAccessTime(appPermissionUsages: List<AppPermissionUsage>):
            MutableMap<String, Long> {
        val accessTime: MutableMap<String, Long> = HashMap()
        if (!SdkLevel.isAtLeastS()) {
            return accessTime
        }

        val aggregateDataFilterBeginDays = if (is7DayToggleEnabled())
            AGGREGATE_DATA_FILTER_BEGIN_DAYS_7 else AGGREGATE_DATA_FILTER_BEGIN_DAYS_1
        val now = System.currentTimeMillis()
        val filterTimeBeginMillis = max(
                now - TimeUnit.DAYS.toMillis(aggregateDataFilterBeginDays.toLong()),
                Instant.EPOCH.toEpochMilli())
        val numApps: Int = appPermissionUsages.size
        for (appIndex in 0 until numApps) {
            val appUsage: AppPermissionUsage = appPermissionUsages.get(appIndex)
            val packageName = appUsage.packageName
            val appGroups = appUsage.groupUsages
            val numGroups = appGroups.size
            for (groupIndex in 0 until numGroups) {
                val groupUsage = appGroups[groupIndex]
                val groupUsageGroupName = groupUsage.group.name
                if (groupName != groupUsageGroupName) {
                    continue
                }
                val lastAccessTime = groupUsage.lastAccessTime
                if (lastAccessTime == 0L || lastAccessTime < filterTimeBeginMillis) {
                    continue
                }
                val key = groupUsage.group.user.toString() + packageName
                accessTime[key] = lastAccessTime
            }
        }
        return accessTime
    }

    /**
     * Return the String preference summary based on the last access time.
     */
    fun getPreferenceSummary(res: Resources, summaryTimestamp: Triple<String, Int, String>):
            String {
        return when (summaryTimestamp.second) {
            Utils.LAST_24H_CONTENT_PROVIDER -> res.getString(
                    R.string.app_perms_content_provider_24h)
            Utils.LAST_7D_CONTENT_PROVIDER -> res.getString(
                    R.string.app_perms_content_provider_7d)
            Utils.LAST_24H_SENSOR_TODAY -> res.getString(R.string.app_perms_24h_access,
                    summaryTimestamp.first)
            Utils.LAST_24H_SENSOR_YESTERDAY -> res.getString(R.string.app_perms_24h_access_yest,
                    summaryTimestamp.first)
            Utils.LAST_7D_SENSOR -> res.getString(R.string.app_perms_7d_access,
                    summaryTimestamp.third, summaryTimestamp.first)
            else -> ""
        }
    }

    /**
     * Return two preferences to determine their ordering.
     */
    fun comparePreference(collator: Collator, lhs: Preference, rhs: Preference): Int {
        var result: Int = collator.compare(lhs.title.toString(),
                rhs.title.toString())
        if (result == 0) {
            result = lhs.key.compareTo(rhs.key)
        }
        return result
    }

    /**
     * Log that the fragment was created.
     */
    fun logPermissionAppsFragmentCreated(
        packageName: String,
        user: UserHandle,
        viewId: Long,
        isAllowed: Boolean,
        isAllowedForeground: Boolean,
        isDenied: Boolean,
        sessionId: Long,
        application: Application,
        permGroupName: String,
        tag: String
    ) {
        var category = PERMISSION_APPS_FRAGMENT_VIEWED__CATEGORY__UNDEFINED
        when {
            isAllowed -> {
                category = PERMISSION_APPS_FRAGMENT_VIEWED__CATEGORY__ALLOWED
            }
            isAllowedForeground -> {
                category = PERMISSION_APPS_FRAGMENT_VIEWED__CATEGORY__ALLOWED_FOREGROUND
            }
            isDenied -> {
                category = PERMISSION_APPS_FRAGMENT_VIEWED__CATEGORY__DENIED
            }
        }
        val uid = getPackageUid(application,
                packageName, user) ?: return
        PermissionControllerStatsLog.write(
                PermissionControllerStatsLog.PERMISSION_APPS_FRAGMENT_VIEWED, sessionId, viewId,
                permGroupName, uid, packageName, category)
        Log.v(tag, tag + " created with sessionId=" + sessionId +
                " permissionGroupName=" + permGroupName + " appUid=" + uid +
                " packageName=" + packageName + " category=" + category)
    }
}

/**
 * Factory for a PermissionAppsViewModel
 *
 * @param app The current application of the fragment
 * @param groupName The name of the permission group this viewModel is representing
 * @param owner The owner of this saved state
 * @param defaultArgs The default args to pass
 */
class PermissionAppsViewModelFactory(
    private val app: Application,
    private val groupName: String,
    owner: SavedStateRegistryOwner,
    defaultArgs: Bundle
) : AbstractSavedStateViewModelFactory(owner, defaultArgs) {

    override fun <T : ViewModel> create(p0: String, p1: Class<T>, state: SavedStateHandle): T {
        state.set(SHOULD_SHOW_SYSTEM_KEY, state.get<Boolean>(SHOULD_SHOW_SYSTEM_KEY) ?: false)
        state.set(HAS_SYSTEM_APPS_KEY, state.get<Boolean>(HAS_SYSTEM_APPS_KEY) ?: true)
        state.set(SHOW_ALWAYS_ALLOWED, state.get<Boolean>(SHOW_ALWAYS_ALLOWED) ?: false)
        state.set(CREATION_LOGGED_KEY, state.get<Boolean>(CREATION_LOGGED_KEY) ?: false)
        @Suppress("UNCHECKED_CAST")
        return PermissionAppsViewModel(state, app, groupName) as T
    }
}