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