blob: 149e2c4c40229cd5fe09857bd5c562f632bc81ba [file] [log] [blame]
Pinyao Tingee191b12020-04-29 18:35:39 -07001/*
2 * Copyright (C) 2020 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 */
16package com.android.systemui.bubbles.storage
17
18import android.content.Context
19import android.util.AtomicFile
20import android.util.Log
21import java.io.File
22import java.io.FileOutputStream
23import java.io.IOException
24import javax.inject.Inject
25import javax.inject.Singleton
26
27@Singleton
28class BubblePersistentRepository @Inject constructor(
29 context: Context
30) {
31
32 private val bubbleFile: AtomicFile = AtomicFile(File(context.filesDir,
33 "overflow_bubbles.xml"), "overflow-bubbles")
34
35 fun persistsToDisk(bubbles: List<BubbleXmlEntity>): Boolean {
Pinyao Ting76ed7ba2020-04-29 18:35:39 -070036 if (DEBUG) Log.d(TAG, "persisting ${bubbles.size} bubbles")
Pinyao Tingee191b12020-04-29 18:35:39 -070037 synchronized(bubbleFile) {
38 val stream: FileOutputStream = try { bubbleFile.startWrite() } catch (e: IOException) {
39 Log.e(TAG, "Failed to save bubble file", e)
40 return false
41 }
42 try {
43 writeXml(stream, bubbles)
44 bubbleFile.finishWrite(stream)
Pinyao Ting76ed7ba2020-04-29 18:35:39 -070045 if (DEBUG) Log.d(TAG, "persisted ${bubbles.size} bubbles")
Pinyao Tingee191b12020-04-29 18:35:39 -070046 return true
47 } catch (e: Exception) {
48 Log.e(TAG, "Failed to save bubble file, restoring backup", e)
49 bubbleFile.failWrite(stream)
50 }
51 }
52 return false
53 }
Pinyao Ting76ed7ba2020-04-29 18:35:39 -070054
55 fun readFromDisk(): List<BubbleXmlEntity> {
56 synchronized(bubbleFile) {
57 try { return bubbleFile.openRead().use(::readXml) } catch (e: Throwable) {
58 Log.e(TAG, "Failed to open bubble file", e)
59 }
60 return emptyList()
61 }
62 }
Pinyao Tingee191b12020-04-29 18:35:39 -070063}
64
65private const val TAG = "BubblePersistentRepository"
Pinyao Ting76ed7ba2020-04-29 18:35:39 -070066private const val DEBUG = false