1 /* <lambda>null2 * 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.healthconnect.controller.exportimport.api 18 19 import android.health.connect.HealthConnectException 20 import android.util.Log 21 import androidx.core.os.asOutcomeReceiver 22 import javax.inject.Inject 23 import javax.inject.Singleton 24 import kotlinx.coroutines.Dispatchers 25 import kotlinx.coroutines.suspendCancellableCoroutine 26 import kotlinx.coroutines.withContext 27 28 @Singleton 29 class QueryDocumentProvidersUseCase 30 @Inject 31 constructor( 32 private val healthDataExportManager: HealthDataExportManager, 33 ) : IQueryDocumentProvidersUseCase { 34 companion object { 35 private const val TAG = "QueryDocumentProvidersUseCase" 36 } 37 38 /** Returns the available document providers. */ 39 override suspend operator fun invoke(): ExportImportUseCaseResult<List<DocumentProvider>> = 40 withContext(Dispatchers.IO) { 41 try { 42 val documentProviders: List<DocumentProvider> = 43 suspendCancellableCoroutine { continuation -> 44 healthDataExportManager.queryDocumentProviders( 45 Runnable::run, continuation.asOutcomeReceiver()) 46 } 47 .groupBy({ 48 DocumentProviderInfo(it.title, it.authority, it.iconResource) 49 }) { 50 DocumentProviderRoot(it.summary, it.rootUri) 51 } 52 .map { DocumentProvider(it.key, sortDocumentProviderRoots(it.value)) } 53 .stream() 54 .sorted { provider1, provider2 -> 55 provider1.info.title.compareTo(provider2.info.title) 56 } 57 .toList() 58 ExportImportUseCaseResult.Success(documentProviders) 59 } catch (ex: HealthConnectException) { 60 Log.e(TAG, "Query document providers error: ", ex) 61 ExportImportUseCaseResult.Failed(ex) 62 } 63 } 64 65 private fun sortDocumentProviderRoots( 66 roots: List<DocumentProviderRoot> 67 ): List<DocumentProviderRoot> { 68 return roots 69 .stream() 70 .sorted { root1, root2 -> root1.summary.compareTo(root2.summary) } 71 .toList() 72 } 73 } 74 75 interface IQueryDocumentProvidersUseCase { 76 /** Returns the available document providers. */ invokenull77 suspend fun invoke(): ExportImportUseCaseResult<List<DocumentProvider>> 78 } 79