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 
17 package com.android.intentresolver.ui.viewmodel
18 
19 import android.os.Bundle
20 import android.os.UserHandle
21 import com.android.intentresolver.ResolverActivity.PROFILE_PERSONAL
22 import com.android.intentresolver.ResolverActivity.PROFILE_WORK
23 import com.android.intentresolver.shared.model.Profile
24 import com.android.intentresolver.ui.model.ActivityModel
25 import com.android.intentresolver.ui.model.ResolverRequest
26 import com.android.intentresolver.validation.Validation
27 import com.android.intentresolver.validation.ValidationResult
28 import com.android.intentresolver.validation.types.value
29 import com.android.intentresolver.validation.validateFrom
30 
31 const val EXTRA_CALLING_USER = "com.android.internal.app.ResolverActivity.EXTRA_CALLING_USER"
32 const val EXTRA_SELECTED_PROFILE =
33     "com.android.internal.app.ResolverActivity.EXTRA_SELECTED_PROFILE"
34 const val EXTRA_IS_AUDIO_CAPTURE_DEVICE = "is_audio_capture_device"
35 
readResolverRequestnull36 fun readResolverRequest(launch: ActivityModel): ValidationResult<ResolverRequest> {
37     @Suppress("DEPRECATION")
38     return validateFrom((launch.intent.extras ?: Bundle())::get) {
39         val callingUser = optional(value<UserHandle>(EXTRA_CALLING_USER))
40         val selectedProfile = checkSelectedProfile()
41         val audioDevice = optional(value<Boolean>(EXTRA_IS_AUDIO_CAPTURE_DEVICE)) ?: false
42         ResolverRequest(launch.intent, selectedProfile, callingUser, audioDevice)
43     }
44 }
45 
Validationnull46 private fun Validation.checkSelectedProfile(): Profile.Type? {
47     return when (val selected = optional(value<Int>(EXTRA_SELECTED_PROFILE))) {
48         null -> null
49         PROFILE_PERSONAL -> Profile.Type.PERSONAL
50         PROFILE_WORK -> Profile.Type.WORK
51         else ->
52             error(
53                 EXTRA_SELECTED_PROFILE +
54                     " has invalid value ($selected)." +
55                     " Must be either ResolverActivity.PROFILE_PERSONAL ($PROFILE_PERSONAL)" +
56                     " or ResolverActivity.PROFILE_WORK ($PROFILE_WORK)."
57             )
58     }
59 }
60