1 /* 2 * Copyright (C) 2017 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.settings.intelligence.search.indexing; 18 19 import static com.android.settings.intelligence.search.indexing.DevicePolicyResourcesUtils.DEVICE_POLICY_RESOURCES_VERSION_KEY; 20 21 import android.app.admin.DevicePolicyManager; 22 import android.content.Context; 23 import android.content.SharedPreferences; 24 import android.content.pm.PackageInfo; 25 import android.content.pm.PackageManager; 26 import android.content.pm.ResolveInfo; 27 import android.database.Cursor; 28 import android.database.sqlite.SQLiteDatabase; 29 import android.database.sqlite.SQLiteOpenHelper; 30 import android.os.Build; 31 import androidx.annotation.VisibleForTesting; 32 import android.text.TextUtils; 33 import android.util.Log; 34 35 import java.util.List; 36 import java.util.Locale; 37 38 public class IndexDatabaseHelper extends SQLiteOpenHelper { 39 40 private static final String TAG = "IndexDatabaseHelper"; 41 42 private static final String DATABASE_NAME = "search_index.db"; 43 private static final int DATABASE_VERSION = 120; 44 45 @VisibleForTesting 46 static final String SHARED_PREFS_TAG = "indexing_manager"; 47 48 private static final String PREF_KEY_INDEXED_PROVIDERS = "indexed_providers"; 49 50 public interface Tables { 51 String TABLE_PREFS_INDEX = "prefs_index"; 52 String TABLE_SITE_MAP = "site_map"; 53 String TABLE_META_INDEX = "meta_index"; 54 String TABLE_SAVED_QUERIES = "saved_queries"; 55 } 56 57 public interface IndexColumns { 58 String DATA_TITLE = "data_title"; 59 String DATA_TITLE_NORMALIZED = "data_title_normalized"; 60 String DATA_SUMMARY_ON = "data_summary_on"; 61 String DATA_SUMMARY_ON_NORMALIZED = "data_summary_on_normalized"; 62 String DATA_SUMMARY_OFF = "data_summary_off"; 63 String DATA_SUMMARY_OFF_NORMALIZED = "data_summary_off_normalized"; 64 String DATA_ENTRIES = "data_entries"; 65 String DATA_KEYWORDS = "data_keywords"; 66 String DATA_PACKAGE = "package"; 67 String DATA_AUTHORITY = "authority"; 68 String CLASS_NAME = "class_name"; 69 String SCREEN_TITLE = "screen_title"; 70 String INTENT_ACTION = "intent_action"; 71 String INTENT_TARGET_PACKAGE = "intent_target_package"; 72 String INTENT_TARGET_CLASS = "intent_target_class"; 73 String ICON = "icon"; 74 String ENABLED = "enabled"; 75 String DATA_KEY_REF = "data_key_reference"; 76 String PAYLOAD_TYPE = "payload_type"; 77 String PAYLOAD = "payload"; 78 } 79 80 public interface MetaColumns { 81 String BUILD = "build"; 82 } 83 84 public interface SavedQueriesColumns { 85 String QUERY = "query"; 86 String TIME_STAMP = "timestamp"; 87 } 88 89 public interface SiteMapColumns { 90 String DOCID = "docid"; 91 String PARENT_CLASS = "parent_class"; 92 String CHILD_CLASS = "child_class"; 93 String PARENT_TITLE = "parent_title"; 94 String CHILD_TITLE = "child_title"; 95 } 96 97 private static final String CREATE_INDEX_TABLE = 98 "CREATE VIRTUAL TABLE " + Tables.TABLE_PREFS_INDEX + " USING fts4" + 99 "(" + 100 IndexColumns.DATA_TITLE + 101 ", " + 102 IndexColumns.DATA_TITLE_NORMALIZED + 103 ", " + 104 IndexColumns.DATA_SUMMARY_ON + 105 ", " + 106 IndexColumns.DATA_SUMMARY_ON_NORMALIZED + 107 ", " + 108 IndexColumns.DATA_SUMMARY_OFF + 109 ", " + 110 IndexColumns.DATA_SUMMARY_OFF_NORMALIZED + 111 ", " + 112 IndexColumns.DATA_ENTRIES + 113 ", " + 114 IndexColumns.DATA_KEYWORDS + 115 ", " + 116 IndexColumns.DATA_PACKAGE + 117 ", " + 118 IndexColumns.DATA_AUTHORITY + 119 ", " + 120 IndexColumns.SCREEN_TITLE + 121 ", " + 122 IndexColumns.CLASS_NAME + 123 ", " + 124 IndexColumns.ICON + 125 ", " + 126 IndexColumns.INTENT_ACTION + 127 ", " + 128 IndexColumns.INTENT_TARGET_PACKAGE + 129 ", " + 130 IndexColumns.INTENT_TARGET_CLASS + 131 ", " + 132 IndexColumns.ENABLED + 133 ", " + 134 IndexColumns.DATA_KEY_REF + 135 ", " + 136 IndexColumns.PAYLOAD_TYPE + 137 ", " + 138 IndexColumns.PAYLOAD + 139 ");"; 140 141 private static final String CREATE_META_TABLE = 142 "CREATE TABLE " + Tables.TABLE_META_INDEX + 143 "(" + 144 MetaColumns.BUILD + " VARCHAR(32) NOT NULL" + 145 ")"; 146 147 private static final String CREATE_SAVED_QUERIES_TABLE = 148 "CREATE TABLE " + Tables.TABLE_SAVED_QUERIES + 149 "(" + 150 SavedQueriesColumns.QUERY + " VARCHAR(64) NOT NULL" + 151 ", " + 152 SavedQueriesColumns.TIME_STAMP + " INTEGER" + 153 ")"; 154 155 private static final String CREATE_SITE_MAP_TABLE = 156 "CREATE VIRTUAL TABLE " + Tables.TABLE_SITE_MAP + " USING fts4" + 157 "(" + 158 SiteMapColumns.PARENT_CLASS + 159 ", " + 160 SiteMapColumns.CHILD_CLASS + 161 ", " + 162 SiteMapColumns.PARENT_TITLE + 163 ", " + 164 SiteMapColumns.CHILD_TITLE + 165 ")"; 166 private static final String INSERT_BUILD_VERSION = 167 "INSERT INTO " + Tables.TABLE_META_INDEX + 168 " VALUES ('" + Build.VERSION.INCREMENTAL + "');"; 169 170 private static final String SELECT_BUILD_VERSION = 171 "SELECT " + MetaColumns.BUILD + " FROM " + Tables.TABLE_META_INDEX + " LIMIT 1;"; 172 173 private static IndexDatabaseHelper sSingleton; 174 175 private final Context mContext; 176 getInstance(Context context)177 public static synchronized IndexDatabaseHelper getInstance(Context context) { 178 if (sSingleton == null) { 179 sSingleton = new IndexDatabaseHelper(context); 180 } 181 return sSingleton; 182 } 183 IndexDatabaseHelper(Context context)184 public IndexDatabaseHelper(Context context) { 185 super(context, DATABASE_NAME, null, DATABASE_VERSION); 186 mContext = context.getApplicationContext(); 187 } 188 189 @Override onCreate(SQLiteDatabase db)190 public void onCreate(SQLiteDatabase db) { 191 bootstrapDB(db); 192 } 193 bootstrapDB(SQLiteDatabase db)194 private void bootstrapDB(SQLiteDatabase db) { 195 db.execSQL(CREATE_INDEX_TABLE); 196 db.execSQL(CREATE_META_TABLE); 197 db.execSQL(CREATE_SAVED_QUERIES_TABLE); 198 db.execSQL(CREATE_SITE_MAP_TABLE); 199 db.execSQL(INSERT_BUILD_VERSION); 200 Log.i(TAG, "Bootstrapped database"); 201 } 202 203 @Override onOpen(SQLiteDatabase db)204 public void onOpen(SQLiteDatabase db) { 205 super.onOpen(db); 206 207 Log.i(TAG, "Using schema version: " + db.getVersion()); 208 209 if (!Build.VERSION.INCREMENTAL.equals(getBuildVersion(db))) { 210 Log.w(TAG, "Index needs to be rebuilt as build-version is not the same"); 211 // We need to drop the tables and recreate them 212 reconstruct(db); 213 } else { 214 Log.i(TAG, "Index is fine"); 215 } 216 } 217 218 @Override onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)219 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 220 if (oldVersion < DATABASE_VERSION) { 221 Log.w(TAG, "Detected schema version '" + oldVersion + "'. " + 222 "Index needs to be rebuilt for schema version '" + newVersion + "'."); 223 // We need to drop the tables and recreate them 224 reconstruct(db); 225 } 226 } 227 228 @Override onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion)229 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { 230 Log.w(TAG, "Detected schema version '" + oldVersion + "'. " + 231 "Index needs to be rebuilt for schema version '" + newVersion + "'."); 232 // We need to drop the tables and recreate them 233 reconstruct(db); 234 } 235 reconstruct(SQLiteDatabase db)236 public void reconstruct(SQLiteDatabase db) { 237 mContext.getSharedPreferences(SHARED_PREFS_TAG, Context.MODE_PRIVATE) 238 .edit() 239 .clear() 240 .commit(); 241 dropTables(db); 242 bootstrapDB(db); 243 } 244 getBuildVersion(SQLiteDatabase db)245 private String getBuildVersion(SQLiteDatabase db) { 246 String version = null; 247 Cursor cursor = null; 248 try { 249 cursor = db.rawQuery(SELECT_BUILD_VERSION, null); 250 if (cursor.moveToFirst()) { 251 version = cursor.getString(0); 252 } 253 } catch (Exception e) { 254 Log.e(TAG, "Cannot get build version from Index metadata"); 255 } finally { 256 if (cursor != null) { 257 cursor.close(); 258 } 259 } 260 return version; 261 } 262 263 @VisibleForTesting buildProviderVersionedNames(Context context, List<ResolveInfo> providers)264 static String buildProviderVersionedNames(Context context, List<ResolveInfo> providers) { 265 // TODO Refactor update test to reflect version code change. 266 try { 267 StringBuilder sb = new StringBuilder(); 268 for (ResolveInfo info : providers) { 269 String packageName = info.providerInfo.packageName; 270 PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 271 0 /* flags */); 272 sb.append(packageName) 273 .append(':') 274 .append(packageInfo.versionCode) 275 .append(','); 276 } 277 // add SettingsIntelligence version as well. 278 sb.append(context.getPackageName()) 279 .append(':') 280 .append(context.getPackageManager() 281 .getPackageInfo(context.getPackageName(), 0 /* flags */).versionCode); 282 return sb.toString(); 283 } catch (PackageManager.NameNotFoundException e) { 284 Log.d(TAG, "Could not find package name in provider", e); 285 } 286 return ""; 287 } 288 289 /** 290 * Set a flag that indicates the search database is fully indexed. 291 */ setIndexed(Context context, List<ResolveInfo> providers)292 static void setIndexed(Context context, List<ResolveInfo> providers) { 293 final String localeStr = Locale.getDefault().toString(); 294 final String fingerprint = Build.FINGERPRINT; 295 final String providerVersionedNames = 296 IndexDatabaseHelper.buildProviderVersionedNames(context, providers); 297 final String devicePolicyResourcesVersion = context.getSystemService( 298 DevicePolicyManager.class).getResources().getString( 299 DEVICE_POLICY_RESOURCES_VERSION_KEY, () -> null); 300 context.getSharedPreferences(SHARED_PREFS_TAG, Context.MODE_PRIVATE) 301 .edit() 302 .putBoolean(localeStr, true) 303 .putBoolean(fingerprint, true) 304 .putString(PREF_KEY_INDEXED_PROVIDERS, providerVersionedNames) 305 .putString(DEVICE_POLICY_RESOURCES_VERSION_KEY, devicePolicyResourcesVersion) 306 .apply(); 307 } 308 309 /** 310 * Checks if the indexed data requires full index. The index data is out of date when: 311 * - Device language has changed 312 * - Device has taken an OTA. 313 * In both cases, the device requires a full index. 314 * 315 * @return true if a full index should be preformed. 316 */ isFullIndex(Context context, List<ResolveInfo> providers)317 static boolean isFullIndex(Context context, List<ResolveInfo> providers) { 318 final String localeStr = Locale.getDefault().toString(); 319 final String fingerprint = Build.FINGERPRINT; 320 final String providerVersionedNames = 321 IndexDatabaseHelper.buildProviderVersionedNames(context, providers); 322 final SharedPreferences prefs = context 323 .getSharedPreferences(SHARED_PREFS_TAG, Context.MODE_PRIVATE); 324 325 final boolean isIndexed = prefs.getBoolean(fingerprint, false) 326 && prefs.getBoolean(localeStr, false) 327 && TextUtils.equals( 328 prefs.getString(PREF_KEY_INDEXED_PROVIDERS, null), providerVersionedNames) 329 && !enterpriseResourcesUpdated(context, prefs); 330 return !isIndexed; 331 } 332 333 /** 334 * returns true if device policy resources have been updated and need reindexing. 335 */ enterpriseResourcesUpdated(Context context, SharedPreferences prefs)336 private static boolean enterpriseResourcesUpdated(Context context, SharedPreferences prefs) { 337 final String currentVersion = context.getSystemService(DevicePolicyManager.class) 338 .getResources().getString(DEVICE_POLICY_RESOURCES_VERSION_KEY, () -> null); 339 return !TextUtils.equals( 340 prefs.getString(DEVICE_POLICY_RESOURCES_VERSION_KEY, null), currentVersion); 341 } 342 dropTables(SQLiteDatabase db)343 private void dropTables(SQLiteDatabase db) { 344 db.execSQL("DROP TABLE IF EXISTS " + Tables.TABLE_META_INDEX); 345 db.execSQL("DROP TABLE IF EXISTS " + Tables.TABLE_PREFS_INDEX); 346 db.execSQL("DROP TABLE IF EXISTS " + Tables.TABLE_SAVED_QUERIES); 347 db.execSQL("DROP TABLE IF EXISTS " + Tables.TABLE_SITE_MAP); 348 } 349 } 350