1 /*
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 */
16
17 package com.android.systemui.backup
18
19 import android.app.backup.BackupAgentHelper
20 import android.app.backup.BackupDataInputStream
21 import android.app.backup.BackupDataOutput
22 import android.app.backup.FileBackupHelper
23 import android.app.job.JobScheduler
24 import android.content.Context
25 import android.content.Intent
26 import android.os.Environment
27 import android.os.ParcelFileDescriptor
28 import android.os.UserHandle
29 import android.util.Log
30 import com.android.app.tracing.traceSection
31 import com.android.systemui.backup.BackupHelper.Companion.ACTION_RESTORE_FINISHED
32 import com.android.systemui.communal.data.backup.CommunalBackupHelper
33 import com.android.systemui.communal.data.backup.CommunalBackupUtils
34 import com.android.systemui.communal.domain.backup.CommunalPrefsBackupHelper
35 import com.android.systemui.controls.controller.AuxiliaryPersistenceWrapper
36 import com.android.systemui.controls.controller.ControlsFavoritePersistenceWrapper
37 import com.android.systemui.keyguard.domain.backup.KeyguardQuickAffordanceBackupHelper
38 import com.android.systemui.people.widget.PeopleBackupHelper
39 import com.android.systemui.res.R
40 import com.android.systemui.settings.UserFileManagerImpl
41
42 /**
43 * Helper for backing up elements in SystemUI
44 *
45 * This helper is invoked by BackupManager whenever a backup or restore is required in SystemUI. The
46 * helper can be used to back up any element that is stored in [Context.getFilesDir] or
47 * [Context.getSharedPreferences].
48 *
49 * After restoring is done, a [ACTION_RESTORE_FINISHED] intent will be send to SystemUI user 0,
50 * indicating that restoring is finished for a given user.
51 */
52 open class BackupHelper : BackupAgentHelper() {
53
54 companion object {
55 const val TAG = "BackupHelper"
56 internal const val CONTROLS = ControlsFavoritePersistenceWrapper.FILE_NAME
57 private const val NO_OVERWRITE_FILES_BACKUP_KEY = "systemui.files_no_overwrite"
58 private const val PEOPLE_TILES_BACKUP_KEY = "systemui.people.shared_preferences"
59 private const val KEYGUARD_QUICK_AFFORDANCES_BACKUP_KEY =
60 "systemui.keyguard.quickaffordance.shared_preferences"
61 private const val COMMUNAL_PREFS_BACKUP_KEY =
62 "systemui.communal.shared_preferences"
63 private const val COMMUNAL_STATE_BACKUP_KEY = "systemui.communal_state"
64 val controlsDataLock = Any()
65 const val ACTION_RESTORE_FINISHED = "com.android.systemui.backup.RESTORE_FINISHED"
66 const val PERMISSION_SELF = "com.android.systemui.permission.SELF"
67 }
68
onCreatenull69 override fun onCreate(userHandle: UserHandle) {
70 super.onCreate(userHandle)
71
72 addControlsHelper(userHandle.identifier)
73
74 val keys = PeopleBackupHelper.getFilesToBackup()
75 addHelper(
76 PEOPLE_TILES_BACKUP_KEY,
77 PeopleBackupHelper(this, userHandle, keys.toTypedArray())
78 )
79 addHelper(
80 KEYGUARD_QUICK_AFFORDANCES_BACKUP_KEY,
81 KeyguardQuickAffordanceBackupHelper(
82 context = this,
83 userId = userHandle.identifier,
84 ),
85 )
86 if (communalEnabled()) {
87 addHelper(
88 COMMUNAL_PREFS_BACKUP_KEY,
89 CommunalPrefsBackupHelper(
90 context = this,
91 userId = userHandle.identifier,
92 )
93 )
94 addHelper(
95 COMMUNAL_STATE_BACKUP_KEY,
96 CommunalBackupHelper(userHandle, CommunalBackupUtils(context = this)),
97 )
98 }
99 }
100
onRestoreFinishednull101 override fun onRestoreFinished() {
102 super.onRestoreFinished()
103 val intent =
104 Intent(ACTION_RESTORE_FINISHED).apply {
105 `package` = packageName
106 putExtra(Intent.EXTRA_USER_ID, userId)
107 flags = Intent.FLAG_RECEIVER_REGISTERED_ONLY
108 }
109 sendBroadcastAsUser(intent, UserHandle.SYSTEM, PERMISSION_SELF)
110 }
111
addControlsHelpernull112 private fun addControlsHelper(userId: Int) {
113 val file = UserFileManagerImpl.createFile(
114 userId = userId,
115 fileName = CONTROLS,
116 )
117 // The map in mapOf is guaranteed to be order preserving
118 val controlsMap = mapOf(file.getPath() to getPPControlsFile(this, userId))
119 NoOverwriteFileBackupHelper(controlsDataLock, this, controlsMap).also {
120 addHelper(NO_OVERWRITE_FILES_BACKUP_KEY, it)
121 }
122 }
123
communalEnablednull124 private fun communalEnabled(): Boolean {
125 return resources.getBoolean(R.bool.config_communalServiceEnabled)
126 }
127
128 /**
129 * Helper class for restoring files ONLY if they are not present.
130 *
131 * A [Map] between filenames and actions (functions) is passed to indicate post processing
132 * actions to be taken after each file is restored.
133 *
134 * @property lock a lock to hold while backing up and restoring the files.
135 * @property context the context of the [BackupAgent]
136 * @property fileNamesAndPostProcess a map from the filenames to back up and the post processing
137 * ```
138 * actions to take
139 * ```
140 */
141 private class NoOverwriteFileBackupHelper(
142 val lock: Any,
143 val context: Context,
144 val fileNamesAndPostProcess: Map<String, () -> Unit>
145 ) : FileBackupHelper(context, *fileNamesAndPostProcess.keys.toTypedArray()) {
146
restoreEntitynull147 override fun restoreEntity(data: BackupDataInputStream) {
148 Log.d(TAG, "Starting restore for ${data.key} for user ${context.userId}")
149 val file = Environment.buildPath(context.filesDir, data.key)
150 if (file.exists()) {
151 Log.w(TAG, "File " + data.key + " already exists. Skipping restore.")
152 return
153 }
154 synchronized(lock) {
155 traceSection("File restore: ${data.key}") {
156 super.restoreEntity(data)
157 }
158 Log.d(TAG, "Finishing restore for ${data.key} for user ${context.userId}. " +
159 "Starting postProcess.")
160 traceSection("Postprocess: ${data.key}") {
161 fileNamesAndPostProcess.get(data.key)?.invoke()
162 }
163 Log.d(TAG, "Finishing postprocess for ${data.key} for user ${context.userId}.")
164 }
165 }
166
performBackupnull167 override fun performBackup(
168 oldState: ParcelFileDescriptor?,
169 data: BackupDataOutput?,
170 newState: ParcelFileDescriptor?
171 ) {
172 synchronized(lock) { super.performBackup(oldState, data, newState) }
173 }
174 }
175 }
176
getPPControlsFilenull177 private fun getPPControlsFile(context: Context, userId: Int): () -> Unit {
178 return {
179 val file = UserFileManagerImpl.createFile(
180 userId = userId,
181 fileName = BackupHelper.CONTROLS,
182 )
183 if (file.exists()) {
184 val dest = UserFileManagerImpl.createFile(
185 userId = userId,
186 fileName = AuxiliaryPersistenceWrapper.AUXILIARY_FILE_NAME,
187 )
188 file.copyTo(dest)
189 val jobScheduler = context.getSystemService(JobScheduler::class.java)
190 jobScheduler?.schedule(
191 AuxiliaryPersistenceWrapper.DeletionJobService.getJobForContext(context, userId)
192 )
193 }
194 }
195 }
196