1 /*
2  * Copyright (C) 2016 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.launcher3.provider;
18 
19 import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
20 
21 import android.app.backup.BackupManager;
22 import android.content.ContentValues;
23 import android.content.Context;
24 import android.content.SharedPreferences;
25 import android.database.Cursor;
26 import android.database.sqlite.SQLiteDatabase;
27 import android.os.UserHandle;
28 import android.util.LongSparseArray;
29 import android.util.SparseLongArray;
30 
31 import androidx.annotation.NonNull;
32 
33 import com.android.launcher3.AppWidgetsRestoredReceiver;
34 import com.android.launcher3.LauncherAppWidgetInfo;
35 import com.android.launcher3.LauncherProvider.DatabaseHelper;
36 import com.android.launcher3.LauncherSettings.Favorites;
37 import com.android.launcher3.WorkspaceItemInfo;
38 import com.android.launcher3.Utilities;
39 import com.android.launcher3.logging.FileLog;
40 import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
41 import com.android.launcher3.util.IntArray;
42 import com.android.launcher3.util.LogConfig;
43 
44 import java.io.InvalidObjectException;
45 
46 /**
47  * Utility class to update DB schema after it has been restored.
48  *
49  * This task is executed when Launcher starts for the first time and not immediately after restore.
50  * This helps keep the model consistent if the launcher updates between restore and first startup.
51  */
52 public class RestoreDbTask {
53 
54     private static final String TAG = "RestoreDbTask";
55     private static final String RESTORE_TASK_PENDING = "restore_task_pending";
56 
57     private static final String INFO_COLUMN_NAME = "name";
58     private static final String INFO_COLUMN_DEFAULT_VALUE = "dflt_value";
59 
60     private static final String APPWIDGET_OLD_IDS = "appwidget_old_ids";
61     private static final String APPWIDGET_IDS = "appwidget_ids";
62 
performRestore(Context context, DatabaseHelper helper, BackupManager backupManager)63     public static boolean performRestore(Context context, DatabaseHelper helper,
64             BackupManager backupManager) {
65         SQLiteDatabase db = helper.getWritableDatabase();
66         try (SQLiteTransaction t = new SQLiteTransaction(db)) {
67             RestoreDbTask task = new RestoreDbTask();
68             task.sanitizeDB(helper, db, backupManager);
69             task.restoreAppWidgetIdsIfExists(context);
70             t.commit();
71             return true;
72         } catch (Exception e) {
73             FileLog.e(TAG, "Failed to verify db", e);
74             return false;
75         }
76     }
77 
78     /**
79      * Makes the following changes in the provider DB.
80      *   1. Removes all entries belonging to any profiles that were not restored.
81      *   2. Marks all entries as restored. The flags are updated during first load or as
82      *      the restored apps get installed.
83      *   3. If the user serial for any restored profile is different than that of the previous
84      *      device, update the entries to the new profile id.
85      */
sanitizeDB(DatabaseHelper helper, SQLiteDatabase db, BackupManager backupManager)86     private void sanitizeDB(DatabaseHelper helper, SQLiteDatabase db, BackupManager backupManager)
87             throws Exception {
88         // Primary user ids
89         long myProfileId = helper.getDefaultUserSerial();
90         long oldProfileId = getDefaultProfileId(db);
91         LongSparseArray<Long> oldManagedProfileIds = getManagedProfileIds(db, oldProfileId);
92         LongSparseArray<Long> profileMapping = new LongSparseArray<>(oldManagedProfileIds.size()
93                 + 1);
94 
95         // Build mapping of restored profile ids to their new profile ids.
96         profileMapping.put(oldProfileId, myProfileId);
97         for (int i = oldManagedProfileIds.size() - 1; i >= 0; --i) {
98             long oldManagedProfileId = oldManagedProfileIds.keyAt(i);
99             UserHandle user = getUserForAncestralSerialNumber(backupManager, oldManagedProfileId);
100             if (user != null) {
101                 long newManagedProfileId = helper.getSerialNumberForUser(user);
102                 profileMapping.put(oldManagedProfileId, newManagedProfileId);
103             }
104         }
105 
106         // Delete all entries which do not belong to any restored profile(s).
107         int numProfiles = profileMapping.size();
108         String[] profileIds = new String[numProfiles];
109         profileIds[0] = Long.toString(oldProfileId);
110         StringBuilder whereClause = new StringBuilder("profileId != ?");
111         for (int i = profileMapping.size() - 1; i >= 1; --i) {
112             whereClause.append(" AND profileId != ?");
113             profileIds[i] = Long.toString(profileMapping.keyAt(i));
114         }
115         int itemsDeleted = db.delete(Favorites.TABLE_NAME, whereClause.toString(), profileIds);
116         if (itemsDeleted > 0) {
117             FileLog.d(TAG, itemsDeleted + " items from unrestored user(s) were deleted");
118         }
119 
120         // Mark all items as restored.
121         boolean keepAllIcons = Utilities.isPropertyEnabled(LogConfig.KEEP_ALL_ICONS);
122         ContentValues values = new ContentValues();
123         values.put(Favorites.RESTORED, WorkspaceItemInfo.FLAG_RESTORED_ICON
124                 | (keepAllIcons ? WorkspaceItemInfo.FLAG_RESTORE_STARTED : 0));
125         db.update(Favorites.TABLE_NAME, values, null, null);
126 
127         // Mark widgets with appropriate restore flag.
128         values.put(Favorites.RESTORED,  LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
129                 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
130                 LauncherAppWidgetInfo.FLAG_UI_NOT_READY |
131                 (keepAllIcons ? LauncherAppWidgetInfo.FLAG_RESTORE_STARTED : 0));
132         db.update(Favorites.TABLE_NAME, values, "itemType = ?",
133                 new String[]{Integer.toString(Favorites.ITEM_TYPE_APPWIDGET)});
134 
135         // Migrate ids. To avoid any overlap, we initially move conflicting ids to a temp location.
136         // Using Long.MIN_VALUE since profile ids can not be negative, so there will be no overlap.
137         final long tempLocationOffset = Long.MIN_VALUE;
138         SparseLongArray tempMigratedIds = new SparseLongArray(profileMapping.size());
139         int numTempMigrations = 0;
140         for (int i = profileMapping.size() - 1; i >= 0; --i) {
141             long oldId = profileMapping.keyAt(i);
142             long newId = profileMapping.valueAt(i);
143 
144             if (oldId != newId) {
145                 if (profileMapping.indexOfKey(newId) >= 0) {
146                     tempMigratedIds.put(numTempMigrations, newId);
147                     numTempMigrations++;
148                     newId = tempLocationOffset + newId;
149                 }
150                 migrateProfileId(db, oldId, newId);
151             }
152         }
153 
154         // Migrate ids from their temporary id to their actual final id.
155         for (int i = tempMigratedIds.size() - 1; i >= 0; --i) {
156             long newId = tempMigratedIds.valueAt(i);
157             migrateProfileId(db, tempLocationOffset + newId, newId);
158         }
159 
160         if (myProfileId != oldProfileId) {
161             changeDefaultColumn(db, myProfileId);
162         }
163     }
164 
165     /**
166      * Updates profile id of all entries from {@param oldProfileId} to {@param newProfileId}.
167      */
migrateProfileId(SQLiteDatabase db, long oldProfileId, long newProfileId)168     protected void migrateProfileId(SQLiteDatabase db, long oldProfileId, long newProfileId) {
169         FileLog.d(TAG, "Changing profile user id from " + oldProfileId + " to " + newProfileId);
170         // Update existing entries.
171         ContentValues values = new ContentValues();
172         values.put(Favorites.PROFILE_ID, newProfileId);
173         db.update(Favorites.TABLE_NAME, values, "profileId = ?",
174                 new String[]{Long.toString(oldProfileId)});
175     }
176 
177 
178     /**
179      * Changes the default value for the column.
180      */
changeDefaultColumn(SQLiteDatabase db, long newProfileId)181     protected void changeDefaultColumn(SQLiteDatabase db, long newProfileId) {
182         db.execSQL("ALTER TABLE favorites RENAME TO favorites_old;");
183         Favorites.addTableToDb(db, newProfileId, false);
184         db.execSQL("INSERT INTO favorites SELECT * FROM favorites_old;");
185         dropTable(db, "favorites_old");
186     }
187 
188     /**
189      * Returns a list of the managed profile id(s) used in the favorites table of the provided db.
190      */
getManagedProfileIds(SQLiteDatabase db, long defaultProfileId)191     private LongSparseArray<Long> getManagedProfileIds(SQLiteDatabase db, long defaultProfileId) {
192         LongSparseArray<Long> ids = new LongSparseArray<>();
193         try (Cursor c = db.rawQuery("SELECT profileId from favorites WHERE profileId != ? "
194                 + "GROUP BY profileId", new String[] {Long.toString(defaultProfileId)})){
195                 while (c.moveToNext()) {
196                     ids.put(c.getLong(c.getColumnIndex(Favorites.PROFILE_ID)), null);
197                 }
198         }
199         return ids;
200     }
201 
202     /**
203      * Returns a UserHandle of a restored managed profile with the given serial number, or null
204      * if none found.
205      */
getUserForAncestralSerialNumber(BackupManager backupManager, long ancestralSerialNumber)206     private UserHandle getUserForAncestralSerialNumber(BackupManager backupManager,
207             long ancestralSerialNumber) {
208         if (!Utilities.ATLEAST_Q) {
209             return null;
210         }
211         return backupManager.getUserForAncestralSerialNumber(ancestralSerialNumber);
212     }
213 
214     /**
215      * Returns the profile id used in the favorites table of the provided db.
216      */
getDefaultProfileId(SQLiteDatabase db)217     protected long getDefaultProfileId(SQLiteDatabase db) throws Exception {
218         try (Cursor c = db.rawQuery("PRAGMA table_info (favorites)", null)){
219             int nameIndex = c.getColumnIndex(INFO_COLUMN_NAME);
220             while (c.moveToNext()) {
221                 if (Favorites.PROFILE_ID.equals(c.getString(nameIndex))) {
222                     return c.getLong(c.getColumnIndex(INFO_COLUMN_DEFAULT_VALUE));
223                 }
224             }
225             throw new InvalidObjectException("Table does not have a profile id column");
226         }
227     }
228 
isPending(Context context)229     public static boolean isPending(Context context) {
230         return Utilities.getPrefs(context).getBoolean(RESTORE_TASK_PENDING, false);
231     }
232 
setPending(Context context, boolean isPending)233     public static void setPending(Context context, boolean isPending) {
234         FileLog.d(TAG, "Restore data received through full backup " + isPending);
235         Utilities.getPrefs(context).edit().putBoolean(RESTORE_TASK_PENDING, isPending).commit();
236     }
237 
restoreAppWidgetIdsIfExists(Context context)238     private void restoreAppWidgetIdsIfExists(Context context) {
239         SharedPreferences prefs = Utilities.getPrefs(context);
240         if (prefs.contains(APPWIDGET_OLD_IDS) && prefs.contains(APPWIDGET_IDS)) {
241             AppWidgetsRestoredReceiver.restoreAppWidgetIds(context,
242                     IntArray.fromConcatString(prefs.getString(APPWIDGET_OLD_IDS, "")).toArray(),
243                     IntArray.fromConcatString(prefs.getString(APPWIDGET_IDS, "")).toArray());
244         } else {
245             FileLog.d(TAG, "No app widget ids to restore.");
246         }
247 
248         prefs.edit().remove(APPWIDGET_OLD_IDS)
249                 .remove(APPWIDGET_IDS).apply();
250     }
251 
setRestoredAppWidgetIds(Context context, @NonNull int[] oldIds, @NonNull int[] newIds)252     public static void setRestoredAppWidgetIds(Context context, @NonNull int[] oldIds,
253             @NonNull int[] newIds) {
254         Utilities.getPrefs(context).edit()
255                 .putString(APPWIDGET_OLD_IDS, IntArray.wrap(oldIds).toConcatString())
256                 .putString(APPWIDGET_IDS, IntArray.wrap(newIds).toConcatString())
257                 .commit();
258     }
259 
260 }
261