1 /** <lambda>null2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * ``` 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * ``` 10 * 11 * Unless required by applicable law or agreed to in writing, software distributed under the License 12 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 * or implied. See the License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 package com.android.healthconnect.controller.permissiontypes.api 17 18 import android.health.connect.HealthConnectManager 19 import android.health.connect.HealthDataCategory 20 import android.health.connect.RecordTypeInfoResponse 21 import android.health.connect.datatypes.Record 22 import android.util.Log 23 import androidx.core.os.asOutcomeReceiver 24 import com.android.healthconnect.controller.permissions.data.HealthPermissionType 25 import com.android.healthconnect.controller.permissions.data.fromHealthPermissionCategory 26 import com.android.healthconnect.controller.service.IoDispatcher 27 import com.android.healthconnect.controller.shared.HealthDataCategoryExtensions.healthPermissionTypes 28 import com.android.healthconnect.controller.shared.HealthDataCategoryInt 29 import javax.inject.Inject 30 import javax.inject.Singleton 31 import kotlinx.coroutines.CoroutineDispatcher 32 import kotlinx.coroutines.suspendCancellableCoroutine 33 import kotlinx.coroutines.withContext 34 35 @Singleton 36 class LoadPermissionTypesUseCase 37 @Inject 38 constructor( 39 private val healthConnectManager: HealthConnectManager, 40 @IoDispatcher private val dispatcher: CoroutineDispatcher 41 ) { 42 43 companion object { 44 private const val TAG = "GetPermissionTypesWithData" 45 } 46 47 /** Returns list of available [HealthPermissionType]s within given [HealthDataCategory]. */ 48 suspend fun invoke(category: @HealthDataCategoryInt Int): List<HealthPermissionType> = 49 withContext(dispatcher) { 50 try { 51 val recordTypeInfoMap: Map<Class<out Record>, RecordTypeInfoResponse> = 52 suspendCancellableCoroutine { continuation -> 53 healthConnectManager.queryAllRecordTypesInfo( 54 Runnable::run, continuation.asOutcomeReceiver()) 55 } 56 category.healthPermissionTypes().filter { hasData(it, recordTypeInfoMap) } 57 } catch (e: Exception) { 58 Log.e(TAG, "GetPermissionTypesWithDataUseCase", e) 59 emptyList() 60 } 61 } 62 63 private fun hasData( 64 permissionType: HealthPermissionType, 65 recordTypeInfoMap: Map<Class<out Record>, RecordTypeInfoResponse> 66 ): Boolean = 67 recordTypeInfoMap.values.firstOrNull { 68 fromHealthPermissionCategory(it.permissionCategory) == permissionType && 69 it.contributingPackages.isNotEmpty() 70 } != null 71 } 72