/* * Copyright (C) 2025 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.privatespace.filetransfer import android.content.Context import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map /** Interface for managing the writes and reads of the state of file transfer. */ interface IFileTransferStateRepository { /** Saves the state of the file transfer. */ suspend fun saveState(context: Context, keepOriginal: Boolean, transferInProgress: Boolean) /** Returns the current state of the file transfer. */ suspend fun getTransferState(context: Context): TransferState } /** Manages the writes and reads of the state of file transfer */ object FileTransferStateRepository : IFileTransferStateRepository { private val Context.dataStore by preferencesDataStore(name = FILE_TRANSFER_PREFS_KEY) private const val FILE_TRANSFER_PREFS_KEY = "file_transfer_prefs" private val KEEP_ORIGINAL_KEY = booleanPreferencesKey("keep_original") private val TRANSFER_IN_PROGRESS_KEY = booleanPreferencesKey("transfer_in_progress") override suspend fun saveState( context: Context, keepOriginal: Boolean, transferInProgress: Boolean, ) { context.dataStore.edit { prefs -> prefs[KEEP_ORIGINAL_KEY] = keepOriginal prefs[TRANSFER_IN_PROGRESS_KEY] = transferInProgress } } /** * Returns the current {@link TransferState}. * * If there is no state saved, it means that no file transfer is in progress. The default value * for keepOriginal file is true, while the default for transferInProgress is false */ override suspend fun getTransferState(context: Context): TransferState { return context.dataStore.data .map { prefs -> val keepOriginal = prefs[KEEP_ORIGINAL_KEY] ?: true val transferInProgress = prefs[TRANSFER_IN_PROGRESS_KEY] ?: false TransferState(keepOriginal, transferInProgress) } .first() } }