1 /*
<lambda>null2  * Copyright (C) 2022 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.recentaccess
18 
19 import android.health.connect.HealthConnectManager
20 import android.health.connect.accesslog.AccessLog
21 import android.util.Log
22 import androidx.core.os.asOutcomeReceiver
23 import com.android.healthconnect.controller.service.IoDispatcher
24 import com.android.healthconnect.controller.utils.TimeSource
25 import java.time.Duration
26 import java.time.Instant
27 import javax.inject.Inject
28 import javax.inject.Singleton
29 import kotlinx.coroutines.CoroutineDispatcher
30 import kotlinx.coroutines.suspendCancellableCoroutine
31 import kotlinx.coroutines.withContext
32 
33 @Singleton
34 class LoadRecentAccessUseCase
35 @Inject
36 constructor(
37     private val manager: HealthConnectManager,
38     @IoDispatcher private val dispatcher: CoroutineDispatcher,
39     private val timeSource: TimeSource
40 ) : ILoadRecentAccessUseCase {
41 
42     companion object {
43         private const val TAG = "LoadRecentAccessUseCase"
44     }
45 
46     /** Returns a list of apps that have recently accessed Health Connect */
47     override suspend fun invoke(): List<AccessLog> =
48         withContext(dispatcher) {
49             val accessLogs =
50                 try {
51                     suspendCancellableCoroutine<List<AccessLog>> { continuation ->
52                         manager.queryAccessLogs(Runnable::run, continuation.asOutcomeReceiver())
53                     }
54                 } catch (e: Exception) {
55                     Log.e(TAG, "Load error ", e)
56                     listOf()
57                 }
58 
59             val instant24Hours =
60                 Instant.ofEpochMilli(timeSource.currentTimeMillis()).minus(Duration.ofDays(1))
61 
62             // only need the last 24 hours of access logs
63             accessLogs
64                 .filter { accessLog -> accessLog.accessTime.isAfter(instant24Hours) }
65                 .sortedByDescending { it.accessTime }
66         }
67 }
68 
69 interface ILoadRecentAccessUseCase {
invokenull70     suspend fun invoke(): List<AccessLog>
71 }
72