1 /* 2 * Copyright (C) 2023 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.systemui.communal.data.repository 18 19 import com.android.systemui.communal.data.model.CommunalMediaModel 20 import com.android.systemui.dagger.SysUISingleton 21 import com.android.systemui.log.dagger.CommunalTableLog 22 import com.android.systemui.log.table.TableLogBuffer 23 import com.android.systemui.log.table.logDiffsForTable 24 import com.android.systemui.media.controls.domain.pipeline.MediaDataManager 25 import com.android.systemui.media.controls.shared.model.MediaData 26 import javax.inject.Inject 27 import kotlinx.coroutines.flow.Flow 28 import kotlinx.coroutines.flow.MutableStateFlow 29 30 /** Encapsulates the state of smartspace in communal. */ 31 interface CommunalMediaRepository { 32 val mediaModel: Flow<CommunalMediaModel> 33 34 /** Start listening for media updates. */ startListeningnull35 fun startListening() 36 37 /** Stop listening for media updates. */ 38 fun stopListening() 39 } 40 41 @SysUISingleton 42 class CommunalMediaRepositoryImpl 43 @Inject 44 constructor( 45 private val mediaDataManager: MediaDataManager, 46 @CommunalTableLog tableLogBuffer: TableLogBuffer, 47 ) : CommunalMediaRepository, MediaDataManager.Listener { 48 49 private val _mediaModel: MutableStateFlow<CommunalMediaModel> = 50 MutableStateFlow(CommunalMediaModel.INACTIVE) 51 52 override val mediaModel: Flow<CommunalMediaModel> = 53 _mediaModel.logDiffsForTable( 54 tableLogBuffer = tableLogBuffer, 55 initialValue = CommunalMediaModel.INACTIVE, 56 ) 57 58 override fun startListening() { 59 mediaDataManager.addListener(this) 60 } 61 62 override fun stopListening() { 63 mediaDataManager.removeListener(this) 64 } 65 66 override fun onMediaDataLoaded( 67 key: String, 68 oldKey: String?, 69 data: MediaData, 70 immediately: Boolean, 71 receivedSmartspaceCardLatency: Int, 72 isSsReactivated: Boolean 73 ) { 74 updateMediaModel(data) 75 } 76 77 override fun onMediaDataRemoved(key: String, userInitiated: Boolean) { 78 updateMediaModel() 79 } 80 81 private fun updateMediaModel(data: MediaData? = null) { 82 if (mediaDataManager.hasAnyMediaOrRecommendation()) { 83 _mediaModel.value = 84 CommunalMediaModel( 85 hasAnyMediaOrRecommendation = true, 86 createdTimestampMillis = data?.createdTimestampMillis ?: 0L, 87 ) 88 } else { 89 _mediaModel.value = CommunalMediaModel.INACTIVE 90 } 91 } 92 } 93