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 35 @SysUISingleton 36 class CommunalMediaRepositoryImpl 37 @Inject 38 constructor( 39 private val mediaDataManager: MediaDataManager, 40 @CommunalTableLog tableLogBuffer: TableLogBuffer, 41 ) : CommunalMediaRepository { 42 43 private val mediaDataListener = 44 object : MediaDataManager.Listener { onMediaDataLoadednull45 override fun onMediaDataLoaded( 46 key: String, 47 oldKey: String?, 48 data: MediaData, 49 immediately: Boolean, 50 receivedSmartspaceCardLatency: Int, 51 isSsReactivated: Boolean 52 ) { 53 updateMediaModel(data) 54 } 55 onMediaDataRemovednull56 override fun onMediaDataRemoved(key: String, userInitiated: Boolean) { 57 updateMediaModel() 58 } 59 } 60 61 init { 62 mediaDataManager.addListener(mediaDataListener) 63 } 64 65 private val _mediaModel: MutableStateFlow<CommunalMediaModel> = 66 MutableStateFlow(CommunalMediaModel.INACTIVE) 67 68 override val mediaModel: Flow<CommunalMediaModel> = 69 _mediaModel.logDiffsForTable( 70 tableLogBuffer = tableLogBuffer, 71 columnPrefix = "", 72 initialValue = CommunalMediaModel.INACTIVE, 73 ) 74 updateMediaModelnull75 private fun updateMediaModel(data: MediaData? = null) { 76 if (mediaDataManager.hasActiveMediaOrRecommendation()) { 77 _mediaModel.value = 78 CommunalMediaModel( 79 hasActiveMediaOrRecommendation = true, 80 createdTimestampMillis = data?.createdTimestampMillis ?: 0L, 81 ) 82 } else { 83 _mediaModel.value = CommunalMediaModel.INACTIVE 84 } 85 } 86 } 87