1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 @file:Suppress("MissingPermission")
17 
18 package com.android.systemui.screenshot.data.repository
19 
20 import android.annotation.UserIdInt
21 import android.os.UserManager
22 import com.android.systemui.dagger.qualifiers.Background
23 import com.android.systemui.screenshot.data.model.ProfileType
24 import javax.inject.Inject
25 import kotlinx.coroutines.CoroutineDispatcher
26 import kotlinx.coroutines.sync.Mutex
27 import kotlinx.coroutines.sync.withLock
28 import kotlinx.coroutines.withContext
29 
30 /** Fetches profile types from [UserManager] as needed, caching results for a given user. */
31 class ProfileTypeRepositoryImpl
32 @Inject
33 constructor(
34     private val userManager: UserManager,
35     @Background private val background: CoroutineDispatcher
36 ) : ProfileTypeRepository {
37     /** Cache to avoid repeated requests to IActivityTaskManager for the same userId */
38     private val cache = mutableMapOf<Int, ProfileType>()
39     private val mutex = Mutex()
40 
getProfileTypenull41     override suspend fun getProfileType(@UserIdInt userId: Int): ProfileType {
42         return mutex.withLock {
43             cache[userId]
44                 ?: withContext(background) {
45                         val userType = userManager.getUserInfo(userId).userType
46                         when (userType) {
47                             UserManager.USER_TYPE_PROFILE_MANAGED -> ProfileType.WORK
48                             UserManager.USER_TYPE_PROFILE_PRIVATE -> ProfileType.PRIVATE
49                             UserManager.USER_TYPE_PROFILE_CLONE -> ProfileType.CLONE
50                             UserManager.USER_TYPE_PROFILE_COMMUNAL -> ProfileType.COMMUNAL
51                             else -> ProfileType.NONE
52                         }
53                     }
54                     .also { cache[userId] = it }
55         }
56     }
57 }
58