BrowserProvider2.java revision 749542ee3500a9060b0961de968f2634269f2845
1/* 2 * Copyright (C) 2010 he 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 17package com.android.browser.provider; 18 19import com.google.common.annotations.VisibleForTesting; 20 21import com.android.browser.BookmarkUtils; 22import com.android.browser.BrowserBookmarksPage; 23import com.android.browser.R; 24import com.android.browser.UrlUtils; 25import com.android.browser.widget.BookmarkThumbnailWidgetProvider; 26import com.android.common.content.SyncStateContentProviderHelper; 27 28import android.accounts.Account; 29import android.app.SearchManager; 30import android.content.ContentResolver; 31import android.content.ContentUris; 32import android.content.ContentValues; 33import android.content.Context; 34import android.content.Intent; 35import android.content.SharedPreferences; 36import android.content.UriMatcher; 37import android.content.res.Resources; 38import android.content.res.TypedArray; 39import android.database.AbstractCursor; 40import android.database.ContentObserver; 41import android.database.Cursor; 42import android.database.DatabaseUtils; 43import android.database.MatrixCursor; 44import android.database.sqlite.SQLiteDatabase; 45import android.database.sqlite.SQLiteOpenHelper; 46import android.database.sqlite.SQLiteQueryBuilder; 47import android.net.Uri; 48import android.preference.PreferenceManager; 49import android.provider.BaseColumns; 50import android.provider.Browser; 51import android.provider.Browser.BookmarkColumns; 52import android.provider.BrowserContract; 53import android.provider.BrowserContract.Accounts; 54import android.provider.BrowserContract.Bookmarks; 55import android.provider.BrowserContract.ChromeSyncColumns; 56import android.provider.BrowserContract.Combined; 57import android.provider.BrowserContract.History; 58import android.provider.BrowserContract.Images; 59import android.provider.BrowserContract.Searches; 60import android.provider.BrowserContract.Settings; 61import android.provider.BrowserContract.SyncState; 62import android.provider.ContactsContract.RawContacts; 63import android.provider.SyncStateContract; 64import android.text.TextUtils; 65 66import java.io.ByteArrayOutputStream; 67import java.io.File; 68import java.io.IOException; 69import java.io.InputStream; 70import java.util.Arrays; 71import java.util.HashMap; 72 73public class BrowserProvider2 extends SQLiteContentProvider { 74 75 public static final String LEGACY_AUTHORITY = "browser"; 76 static final Uri LEGACY_AUTHORITY_URI = new Uri.Builder() 77 .authority(LEGACY_AUTHORITY).scheme("content").build(); 78 79 static final String TABLE_BOOKMARKS = "bookmarks"; 80 static final String TABLE_HISTORY = "history"; 81 static final String TABLE_IMAGES = "images"; 82 static final String TABLE_SEARCHES = "searches"; 83 static final String TABLE_SYNC_STATE = "syncstate"; 84 static final String TABLE_SETTINGS = "settings"; 85 86 static final String TABLE_BOOKMARKS_JOIN_IMAGES = "bookmarks LEFT OUTER JOIN images " + 87 "ON bookmarks.url = images." + Images.URL; 88 static final String TABLE_HISTORY_JOIN_IMAGES = "history LEFT OUTER JOIN images " + 89 "ON history.url = images." + Images.URL; 90 91 static final String VIEW_ACCOUNTS = "v_accounts"; 92 93 static final String FORMAT_COMBINED_JOIN_SUBQUERY_JOIN_IMAGES = 94 "history LEFT OUTER JOIN (%s) bookmarks " + 95 "ON history.url = bookmarks.url LEFT OUTER JOIN images " + 96 "ON history.url = images.url_key"; 97 98 static final String DEFAULT_SORT_HISTORY = History.DATE_LAST_VISITED + " DESC"; 99 100 private static final String[] SUGGEST_PROJECTION = new String[] { 101 Bookmarks._ID, 102 Bookmarks.URL, 103 Bookmarks.TITLE}; 104 105 private static final String SUGGEST_SELECTION = 106 "url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?" 107 + " OR title LIKE ?"; 108 109 private static final String IMAGE_PRUNE = 110 "url_key NOT IN (SELECT url FROM bookmarks " + 111 "WHERE url IS NOT NULL AND deleted == 0) AND url_key NOT IN " + 112 "(SELECT url FROM history WHERE url IS NOT NULL)"; 113 114 static final int BOOKMARKS = 1000; 115 static final int BOOKMARKS_ID = 1001; 116 static final int BOOKMARKS_FOLDER = 1002; 117 static final int BOOKMARKS_FOLDER_ID = 1003; 118 static final int BOOKMARKS_SUGGESTIONS = 1004; 119 static final int BOOKMARKS_DEFAULT_FOLDER_ID = 1005; 120 121 static final int HISTORY = 2000; 122 static final int HISTORY_ID = 2001; 123 124 static final int SEARCHES = 3000; 125 static final int SEARCHES_ID = 3001; 126 127 static final int SYNCSTATE = 4000; 128 static final int SYNCSTATE_ID = 4001; 129 130 static final int IMAGES = 5000; 131 132 static final int COMBINED = 6000; 133 static final int COMBINED_ID = 6001; 134 135 static final int ACCOUNTS = 7000; 136 137 static final int SETTINGS = 8000; 138 139 static final int LEGACY = 9000; 140 static final int LEGACY_ID = 9001; 141 142 public static final long FIXED_ID_ROOT = 1; 143 144 // Default sort order for unsync'd bookmarks 145 static final String DEFAULT_BOOKMARKS_SORT_ORDER = 146 Bookmarks.IS_FOLDER + " DESC, position ASC, _id ASC"; 147 148 // Default sort order for sync'd bookmarks 149 static final String DEFAULT_BOOKMARKS_SORT_ORDER_SYNC = "position ASC, _id ASC"; 150 151 static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); 152 153 static final HashMap<String, String> ACCOUNTS_PROJECTION_MAP = new HashMap<String, String>(); 154 static final HashMap<String, String> BOOKMARKS_PROJECTION_MAP = new HashMap<String, String>(); 155 static final HashMap<String, String> OTHER_BOOKMARKS_PROJECTION_MAP = 156 new HashMap<String, String>(); 157 static final HashMap<String, String> HISTORY_PROJECTION_MAP = new HashMap<String, String>(); 158 static final HashMap<String, String> SYNC_STATE_PROJECTION_MAP = new HashMap<String, String>(); 159 static final HashMap<String, String> IMAGES_PROJECTION_MAP = new HashMap<String, String>(); 160 static final HashMap<String, String> COMBINED_HISTORY_PROJECTION_MAP = new HashMap<String, String>(); 161 static final HashMap<String, String> COMBINED_BOOKMARK_PROJECTION_MAP = new HashMap<String, String>(); 162 static final HashMap<String, String> SEARCHES_PROJECTION_MAP = new HashMap<String, String>(); 163 static final HashMap<String, String> SETTINGS_PROJECTION_MAP = new HashMap<String, String>(); 164 165 static { 166 final UriMatcher matcher = URI_MATCHER; 167 final String authority = BrowserContract.AUTHORITY; 168 matcher.addURI(authority, "accounts", ACCOUNTS); 169 matcher.addURI(authority, "bookmarks", BOOKMARKS); 170 matcher.addURI(authority, "bookmarks/#", BOOKMARKS_ID); 171 matcher.addURI(authority, "bookmarks/folder", BOOKMARKS_FOLDER); 172 matcher.addURI(authority, "bookmarks/folder/#", BOOKMARKS_FOLDER_ID); 173 matcher.addURI(authority, "bookmarks/folder/id", BOOKMARKS_DEFAULT_FOLDER_ID); 174 matcher.addURI(authority, 175 SearchManager.SUGGEST_URI_PATH_QUERY, 176 BOOKMARKS_SUGGESTIONS); 177 matcher.addURI(authority, 178 "bookmarks/" + SearchManager.SUGGEST_URI_PATH_QUERY, 179 BOOKMARKS_SUGGESTIONS); 180 matcher.addURI(authority, "history", HISTORY); 181 matcher.addURI(authority, "history/#", HISTORY_ID); 182 matcher.addURI(authority, "searches", SEARCHES); 183 matcher.addURI(authority, "searches/#", SEARCHES_ID); 184 matcher.addURI(authority, "syncstate", SYNCSTATE); 185 matcher.addURI(authority, "syncstate/#", SYNCSTATE_ID); 186 matcher.addURI(authority, "images", IMAGES); 187 matcher.addURI(authority, "combined", COMBINED); 188 matcher.addURI(authority, "combined/#", COMBINED_ID); 189 matcher.addURI(authority, "settings", SETTINGS); 190 191 // Legacy 192 matcher.addURI(LEGACY_AUTHORITY, "searches", SEARCHES); 193 matcher.addURI(LEGACY_AUTHORITY, "searches/#", SEARCHES_ID); 194 matcher.addURI(LEGACY_AUTHORITY, "bookmarks", LEGACY); 195 matcher.addURI(LEGACY_AUTHORITY, "bookmarks/#", LEGACY_ID); 196 matcher.addURI(LEGACY_AUTHORITY, 197 SearchManager.SUGGEST_URI_PATH_QUERY, 198 BOOKMARKS_SUGGESTIONS); 199 matcher.addURI(LEGACY_AUTHORITY, 200 "bookmarks/" + SearchManager.SUGGEST_URI_PATH_QUERY, 201 BOOKMARKS_SUGGESTIONS); 202 203 // Projection maps 204 HashMap<String, String> map; 205 206 // Accounts 207 map = ACCOUNTS_PROJECTION_MAP; 208 map.put(Accounts.ACCOUNT_TYPE, Accounts.ACCOUNT_TYPE); 209 map.put(Accounts.ACCOUNT_NAME, Accounts.ACCOUNT_NAME); 210 map.put(Accounts.ROOT_ID, Accounts.ROOT_ID); 211 212 // Bookmarks 213 map = BOOKMARKS_PROJECTION_MAP; 214 map.put(Bookmarks._ID, qualifyColumn(TABLE_BOOKMARKS, Bookmarks._ID)); 215 map.put(Bookmarks.TITLE, Bookmarks.TITLE); 216 map.put(Bookmarks.URL, Bookmarks.URL); 217 map.put(Bookmarks.FAVICON, Bookmarks.FAVICON); 218 map.put(Bookmarks.THUMBNAIL, Bookmarks.THUMBNAIL); 219 map.put(Bookmarks.TOUCH_ICON, Bookmarks.TOUCH_ICON); 220 map.put(Bookmarks.IS_FOLDER, Bookmarks.IS_FOLDER); 221 map.put(Bookmarks.PARENT, Bookmarks.PARENT); 222 map.put(Bookmarks.POSITION, Bookmarks.POSITION); 223 map.put(Bookmarks.INSERT_AFTER, Bookmarks.INSERT_AFTER); 224 map.put(Bookmarks.IS_DELETED, Bookmarks.IS_DELETED); 225 map.put(Bookmarks.ACCOUNT_NAME, Bookmarks.ACCOUNT_NAME); 226 map.put(Bookmarks.ACCOUNT_TYPE, Bookmarks.ACCOUNT_TYPE); 227 map.put(Bookmarks.SOURCE_ID, Bookmarks.SOURCE_ID); 228 map.put(Bookmarks.VERSION, Bookmarks.VERSION); 229 map.put(Bookmarks.DATE_CREATED, Bookmarks.DATE_CREATED); 230 map.put(Bookmarks.DATE_MODIFIED, Bookmarks.DATE_MODIFIED); 231 map.put(Bookmarks.DIRTY, Bookmarks.DIRTY); 232 map.put(Bookmarks.SYNC1, Bookmarks.SYNC1); 233 map.put(Bookmarks.SYNC2, Bookmarks.SYNC2); 234 map.put(Bookmarks.SYNC3, Bookmarks.SYNC3); 235 map.put(Bookmarks.SYNC4, Bookmarks.SYNC4); 236 map.put(Bookmarks.SYNC5, Bookmarks.SYNC5); 237 map.put(Bookmarks.PARENT_SOURCE_ID, "(SELECT " + Bookmarks.SOURCE_ID + 238 " FROM " + TABLE_BOOKMARKS + " A WHERE " + 239 "A." + Bookmarks._ID + "=" + TABLE_BOOKMARKS + "." + Bookmarks.PARENT + 240 ") AS " + Bookmarks.PARENT_SOURCE_ID); 241 map.put(Bookmarks.INSERT_AFTER_SOURCE_ID, "(SELECT " + Bookmarks.SOURCE_ID + 242 " FROM " + TABLE_BOOKMARKS + " A WHERE " + 243 "A." + Bookmarks._ID + "=" + TABLE_BOOKMARKS + "." + Bookmarks.INSERT_AFTER + 244 ") AS " + Bookmarks.INSERT_AFTER_SOURCE_ID); 245 246 // Other bookmarks 247 OTHER_BOOKMARKS_PROJECTION_MAP.putAll(BOOKMARKS_PROJECTION_MAP); 248 OTHER_BOOKMARKS_PROJECTION_MAP.put(Bookmarks.POSITION, 249 Long.toString(Long.MAX_VALUE) + " AS " + Bookmarks.POSITION); 250 251 // History 252 map = HISTORY_PROJECTION_MAP; 253 map.put(History._ID, qualifyColumn(TABLE_HISTORY, History._ID)); 254 map.put(History.TITLE, History.TITLE); 255 map.put(History.URL, History.URL); 256 map.put(History.FAVICON, History.FAVICON); 257 map.put(History.THUMBNAIL, History.THUMBNAIL); 258 map.put(History.TOUCH_ICON, History.TOUCH_ICON); 259 map.put(History.DATE_CREATED, History.DATE_CREATED); 260 map.put(History.DATE_LAST_VISITED, History.DATE_LAST_VISITED); 261 map.put(History.VISITS, History.VISITS); 262 map.put(History.USER_ENTERED, History.USER_ENTERED); 263 264 // Sync state 265 map = SYNC_STATE_PROJECTION_MAP; 266 map.put(SyncState._ID, SyncState._ID); 267 map.put(SyncState.ACCOUNT_NAME, SyncState.ACCOUNT_NAME); 268 map.put(SyncState.ACCOUNT_TYPE, SyncState.ACCOUNT_TYPE); 269 map.put(SyncState.DATA, SyncState.DATA); 270 271 // Images 272 map = IMAGES_PROJECTION_MAP; 273 map.put(Images.URL, Images.URL); 274 map.put(Images.FAVICON, Images.FAVICON); 275 map.put(Images.THUMBNAIL, Images.THUMBNAIL); 276 map.put(Images.TOUCH_ICON, Images.TOUCH_ICON); 277 278 // Combined history half 279 map = COMBINED_HISTORY_PROJECTION_MAP; 280 map.put(Combined._ID, bookmarkOrHistoryColumn(Combined._ID)); 281 map.put(Combined.TITLE, bookmarkOrHistoryColumn(Combined.TITLE)); 282 map.put(Combined.URL, qualifyColumn(TABLE_HISTORY, Combined.URL)); 283 map.put(Combined.DATE_CREATED, qualifyColumn(TABLE_HISTORY, Combined.DATE_CREATED)); 284 map.put(Combined.DATE_LAST_VISITED, Combined.DATE_LAST_VISITED); 285 map.put(Combined.IS_BOOKMARK, "CASE WHEN " + 286 TABLE_BOOKMARKS + "." + Bookmarks._ID + 287 " IS NOT NULL THEN 1 ELSE 0 END AS " + Combined.IS_BOOKMARK); 288 map.put(Combined.VISITS, Combined.VISITS); 289 map.put(Combined.FAVICON, Combined.FAVICON); 290 map.put(Combined.THUMBNAIL, Combined.THUMBNAIL); 291 map.put(Combined.TOUCH_ICON, Combined.TOUCH_ICON); 292 map.put(Combined.USER_ENTERED, "NULL AS " + Combined.USER_ENTERED); 293 294 // Combined bookmark half 295 map = COMBINED_BOOKMARK_PROJECTION_MAP; 296 map.put(Combined._ID, Combined._ID); 297 map.put(Combined.TITLE, Combined.TITLE); 298 map.put(Combined.URL, Combined.URL); 299 map.put(Combined.DATE_CREATED, Combined.DATE_CREATED); 300 map.put(Combined.DATE_LAST_VISITED, "NULL AS " + Combined.DATE_LAST_VISITED); 301 map.put(Combined.IS_BOOKMARK, "1 AS " + Combined.IS_BOOKMARK); 302 map.put(Combined.VISITS, "0 AS " + Combined.VISITS); 303 map.put(Combined.FAVICON, Combined.FAVICON); 304 map.put(Combined.THUMBNAIL, Combined.THUMBNAIL); 305 map.put(Combined.TOUCH_ICON, Combined.TOUCH_ICON); 306 map.put(Combined.USER_ENTERED, "NULL AS " + Combined.USER_ENTERED); 307 308 // Searches 309 map = SEARCHES_PROJECTION_MAP; 310 map.put(Searches._ID, Searches._ID); 311 map.put(Searches.SEARCH, Searches.SEARCH); 312 map.put(Searches.DATE, Searches.DATE); 313 314 // Settings 315 map = SETTINGS_PROJECTION_MAP; 316 map.put(Settings.KEY, Settings.KEY); 317 map.put(Settings.VALUE, Settings.VALUE); 318 } 319 320 static final String bookmarkOrHistoryColumn(String column) { 321 return "CASE WHEN bookmarks." + column + " IS NOT NULL THEN " + 322 "bookmarks." + column + " ELSE history." + column + " END AS " + column; 323 } 324 325 static final String qualifyColumn(String table, String column) { 326 return table + "." + column + " AS " + column; 327 } 328 329 DatabaseHelper mOpenHelper; 330 SyncStateContentProviderHelper mSyncHelper = new SyncStateContentProviderHelper(); 331 // This is so provider tests can intercept widget updating 332 ContentObserver mWidgetObserver = null; 333 334 final class DatabaseHelper extends SQLiteOpenHelper { 335 static final String DATABASE_NAME = "browser2.db"; 336 static final int DATABASE_VERSION = 27; 337 public DatabaseHelper(Context context) { 338 super(context, DATABASE_NAME, null, DATABASE_VERSION); 339 } 340 341 @Override 342 public void onCreate(SQLiteDatabase db) { 343 db.execSQL("CREATE TABLE " + TABLE_BOOKMARKS + "(" + 344 Bookmarks._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 345 Bookmarks.TITLE + " TEXT," + 346 Bookmarks.URL + " TEXT," + 347 Bookmarks.IS_FOLDER + " INTEGER NOT NULL DEFAULT 0," + 348 Bookmarks.PARENT + " INTEGER," + 349 Bookmarks.POSITION + " INTEGER NOT NULL," + 350 Bookmarks.INSERT_AFTER + " INTEGER," + 351 Bookmarks.IS_DELETED + " INTEGER NOT NULL DEFAULT 0," + 352 Bookmarks.ACCOUNT_NAME + " TEXT," + 353 Bookmarks.ACCOUNT_TYPE + " TEXT," + 354 Bookmarks.SOURCE_ID + " TEXT," + 355 Bookmarks.VERSION + " INTEGER NOT NULL DEFAULT 1," + 356 Bookmarks.DATE_CREATED + " INTEGER," + 357 Bookmarks.DATE_MODIFIED + " INTEGER," + 358 Bookmarks.DIRTY + " INTEGER NOT NULL DEFAULT 0," + 359 Bookmarks.SYNC1 + " TEXT," + 360 Bookmarks.SYNC2 + " TEXT," + 361 Bookmarks.SYNC3 + " TEXT," + 362 Bookmarks.SYNC4 + " TEXT," + 363 Bookmarks.SYNC5 + " TEXT" + 364 ");"); 365 366 // TODO indices 367 368 db.execSQL("CREATE TABLE " + TABLE_HISTORY + "(" + 369 History._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 370 History.TITLE + " TEXT," + 371 History.URL + " TEXT NOT NULL," + 372 History.DATE_CREATED + " INTEGER," + 373 History.DATE_LAST_VISITED + " INTEGER," + 374 History.VISITS + " INTEGER NOT NULL DEFAULT 0," + 375 History.USER_ENTERED + " INTEGER" + 376 ");"); 377 378 db.execSQL("CREATE TABLE " + TABLE_IMAGES + " (" + 379 Images.URL + " TEXT UNIQUE NOT NULL," + 380 Images.FAVICON + " BLOB," + 381 Images.THUMBNAIL + " BLOB," + 382 Images.TOUCH_ICON + " BLOB" + 383 ");"); 384 db.execSQL("CREATE INDEX imagesUrlIndex ON " + TABLE_IMAGES + 385 "(" + Images.URL + ")"); 386 387 db.execSQL("CREATE TABLE " + TABLE_SEARCHES + " (" + 388 Searches._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 389 Searches.SEARCH + " TEXT," + 390 Searches.DATE + " LONG" + 391 ");"); 392 393 db.execSQL("CREATE TABLE " + TABLE_SETTINGS + " (" + 394 Settings.KEY + " TEXT PRIMARY KEY," + 395 Settings.VALUE + " TEXT NOT NULL" + 396 ");"); 397 398 createAccountsView(db); 399 400 mSyncHelper.createDatabase(db); 401 402 if (!importFromBrowserProvider(db)) { 403 createDefaultBookmarks(db); 404 } 405 } 406 407 boolean importFromBrowserProvider(SQLiteDatabase db) { 408 Context context = getContext(); 409 File oldDbFile = context.getDatabasePath(BrowserProvider.sDatabaseName); 410 if (oldDbFile.exists()) { 411 BrowserProvider.DatabaseHelper helper = 412 new BrowserProvider.DatabaseHelper(context); 413 SQLiteDatabase oldDb = helper.getWritableDatabase(); 414 Cursor c = null; 415 try { 416 String table = BrowserProvider.TABLE_NAMES[BrowserProvider.URI_MATCH_BOOKMARKS]; 417 // Import bookmarks 418 c = oldDb.query(table, 419 new String[] { 420 BookmarkColumns.URL, // 0 421 BookmarkColumns.TITLE, // 1 422 BookmarkColumns.FAVICON, // 2 423 BookmarkColumns.TOUCH_ICON, // 3 424 }, BookmarkColumns.BOOKMARK + "!=0", null, 425 null, null, null); 426 if (c != null) { 427 while (c.moveToNext()) { 428 ContentValues values = new ContentValues(); 429 values.put(Bookmarks.URL, c.getString(0)); 430 values.put(Bookmarks.TITLE, c.getString(1)); 431 values.put(Bookmarks.POSITION, 0); 432 values.put(Bookmarks.PARENT, FIXED_ID_ROOT); 433 ContentValues imageValues = new ContentValues(); 434 imageValues.put(Images.URL, c.getString(0)); 435 imageValues.put(Images.FAVICON, c.getBlob(2)); 436 imageValues.put(Images.TOUCH_ICON, c.getBlob(3)); 437 db.insertOrThrow(TABLE_IMAGES, Images.THUMBNAIL, imageValues); 438 db.insertOrThrow(TABLE_BOOKMARKS, Bookmarks.DIRTY, values); 439 } 440 c.close(); 441 } 442 // Import history 443 c = oldDb.query(table, 444 new String[] { 445 BookmarkColumns.URL, // 0 446 BookmarkColumns.TITLE, // 1 447 BookmarkColumns.VISITS, // 2 448 BookmarkColumns.DATE, // 3 449 BookmarkColumns.CREATED, // 4 450 }, null, null, null, null, null); 451 if (c != null) { 452 while (c.moveToNext()) { 453 ContentValues values = new ContentValues(); 454 values.put(History.URL, c.getString(0)); 455 values.put(History.TITLE, c.getString(1)); 456 values.put(History.VISITS, c.getInt(2)); 457 values.put(History.DATE_LAST_VISITED, c.getLong(3)); 458 values.put(History.DATE_CREATED, c.getLong(4)); 459 db.insertOrThrow(TABLE_HISTORY, History.FAVICON, values); 460 } 461 c.close(); 462 } 463 // Wipe the old DB, in case the delete fails. 464 oldDb.delete(table, null, null); 465 } finally { 466 if (c != null) c.close(); 467 oldDb.close(); 468 helper.close(); 469 } 470 if (!oldDbFile.delete()) { 471 oldDbFile.deleteOnExit(); 472 } 473 return true; 474 } 475 return false; 476 } 477 478 void createAccountsView(SQLiteDatabase db) { 479 db.execSQL("CREATE VIEW IF NOT EXISTS v_accounts AS " 480 + "SELECT NULL AS " + Accounts.ACCOUNT_NAME 481 + ", NULL AS " + Accounts.ACCOUNT_TYPE 482 + ", " + FIXED_ID_ROOT + " AS " + Accounts.ROOT_ID 483 + " UNION ALL SELECT " + Accounts.ACCOUNT_NAME 484 + ", " + Accounts.ACCOUNT_TYPE + ", " 485 + Bookmarks._ID + " AS " + Accounts.ROOT_ID 486 + " FROM " + TABLE_BOOKMARKS + " WHERE " 487 + ChromeSyncColumns.SERVER_UNIQUE + " = \"" 488 + ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR + "\" AND " 489 + Bookmarks.IS_DELETED + " = 0"); 490 } 491 492 @Override 493 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 494 // TODO write upgrade logic 495 if (oldVersion < 27) { 496 createAccountsView(db); 497 } 498 if (oldVersion < 26) { 499 db.execSQL("DROP VIEW IF EXISTS combined"); 500 } 501 if (oldVersion < 25) { 502 db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKMARKS); 503 db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY); 504 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SEARCHES); 505 db.execSQL("DROP TABLE IF EXISTS " + TABLE_IMAGES); 506 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTINGS); 507 mSyncHelper.onAccountsChanged(db, new Account[] {}); // remove all sync info 508 onCreate(db); 509 } 510 } 511 512 @Override 513 public void onOpen(SQLiteDatabase db) { 514 db.enableWriteAheadLogging(); 515 mSyncHelper.onDatabaseOpened(db); 516 } 517 518 private void createDefaultBookmarks(SQLiteDatabase db) { 519 ContentValues values = new ContentValues(); 520 // TODO figure out how to deal with localization for the defaults 521 522 // Bookmarks folder 523 values.put(Bookmarks._ID, FIXED_ID_ROOT); 524 values.put(ChromeSyncColumns.SERVER_UNIQUE, ChromeSyncColumns.FOLDER_NAME_BOOKMARKS); 525 values.put(Bookmarks.TITLE, "Bookmarks"); 526 values.putNull(Bookmarks.PARENT); 527 values.put(Bookmarks.POSITION, 0); 528 values.put(Bookmarks.IS_FOLDER, true); 529 values.put(Bookmarks.DIRTY, true); 530 db.insertOrThrow(TABLE_BOOKMARKS, null, values); 531 532 addDefaultBookmarks(db, FIXED_ID_ROOT); 533 } 534 535 private void addDefaultBookmarks(SQLiteDatabase db, long parentId) { 536 Resources res = getContext().getResources(); 537 final CharSequence[] bookmarks = res.getTextArray( 538 R.array.bookmarks); 539 int size = bookmarks.length; 540 TypedArray preloads = res.obtainTypedArray(R.array.bookmark_preloads); 541 try { 542 String parent = Long.toString(parentId); 543 String now = Long.toString(System.currentTimeMillis()); 544 for (int i = 0; i < size; i = i + 2) { 545 CharSequence bookmarkDestination = replaceSystemPropertyInString(getContext(), 546 bookmarks[i + 1]); 547 db.execSQL("INSERT INTO bookmarks (" + 548 Bookmarks.TITLE + ", " + 549 Bookmarks.URL + ", " + 550 Bookmarks.IS_FOLDER + "," + 551 Bookmarks.PARENT + "," + 552 Bookmarks.POSITION + "," + 553 Bookmarks.DATE_CREATED + 554 ") VALUES (" + 555 "'" + bookmarks[i] + "', " + 556 "'" + bookmarkDestination + "', " + 557 "0," + 558 parent + "," + 559 Integer.toString(i) + "," + 560 now + 561 ");"); 562 563 int faviconId = preloads.getResourceId(i, 0); 564 int thumbId = preloads.getResourceId(i + 1, 0); 565 byte[] thumb = null, favicon = null; 566 try { 567 thumb = readRaw(res, thumbId); 568 } catch (IOException e) { 569 } 570 try { 571 favicon = readRaw(res, faviconId); 572 } catch (IOException e) { 573 } 574 if (thumb != null || favicon != null) { 575 ContentValues imageValues = new ContentValues(); 576 imageValues.put(Images.URL, bookmarkDestination.toString()); 577 if (favicon != null) { 578 imageValues.put(Images.FAVICON, favicon); 579 } 580 if (thumb != null) { 581 imageValues.put(Images.THUMBNAIL, thumb); 582 } 583 db.insert(TABLE_IMAGES, Images.FAVICON, imageValues); 584 } 585 } 586 } catch (ArrayIndexOutOfBoundsException e) { 587 } 588 } 589 590 private byte[] readRaw(Resources res, int id) throws IOException { 591 if (id == 0) { 592 return null; 593 } 594 InputStream is = res.openRawResource(id); 595 try { 596 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 597 byte[] buf = new byte[4096]; 598 int read; 599 while ((read = is.read(buf)) > 0) { 600 bos.write(buf, 0, read); 601 } 602 bos.flush(); 603 return bos.toByteArray(); 604 } finally { 605 is.close(); 606 } 607 } 608 609 // XXX: This is a major hack to remove our dependency on gsf constants and 610 // its content provider. http://b/issue?id=2425179 611 private String getClientId(ContentResolver cr) { 612 String ret = "android-google"; 613 Cursor c = null; 614 try { 615 c = cr.query(Uri.parse("content://com.google.settings/partner"), 616 new String[] { "value" }, "name='client_id'", null, null); 617 if (c != null && c.moveToNext()) { 618 ret = c.getString(0); 619 } 620 } catch (RuntimeException ex) { 621 // fall through to return the default 622 } finally { 623 if (c != null) { 624 c.close(); 625 } 626 } 627 return ret; 628 } 629 630 private CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) { 631 StringBuffer sb = new StringBuffer(); 632 int lastCharLoc = 0; 633 634 final String client_id = getClientId(context.getContentResolver()); 635 636 for (int i = 0; i < srcString.length(); ++i) { 637 char c = srcString.charAt(i); 638 if (c == '{') { 639 sb.append(srcString.subSequence(lastCharLoc, i)); 640 lastCharLoc = i; 641 inner: 642 for (int j = i; j < srcString.length(); ++j) { 643 char k = srcString.charAt(j); 644 if (k == '}') { 645 String propertyKeyValue = srcString.subSequence(i + 1, j).toString(); 646 if (propertyKeyValue.equals("CLIENT_ID")) { 647 sb.append(client_id); 648 } else { 649 sb.append("unknown"); 650 } 651 lastCharLoc = j + 1; 652 i = j; 653 break inner; 654 } 655 } 656 } 657 } 658 if (srcString.length() - lastCharLoc > 0) { 659 // Put on the tail, if there is one 660 sb.append(srcString.subSequence(lastCharLoc, srcString.length())); 661 } 662 return sb; 663 } 664 } 665 666 @Override 667 public SQLiteOpenHelper getDatabaseHelper(Context context) { 668 synchronized (this) { 669 if (mOpenHelper == null) { 670 mOpenHelper = new DatabaseHelper(context); 671 } 672 return mOpenHelper; 673 } 674 } 675 676 @Override 677 public boolean isCallerSyncAdapter(Uri uri) { 678 return uri.getBooleanQueryParameter(BrowserContract.CALLER_IS_SYNCADAPTER, false); 679 } 680 681 @VisibleForTesting 682 public void setWidgetObserver(ContentObserver obs) { 683 mWidgetObserver = obs; 684 } 685 686 void refreshWidgets() { 687 if (mWidgetObserver == null) { 688 BookmarkThumbnailWidgetProvider.refreshWidgets(getContext()); 689 } else { 690 mWidgetObserver.dispatchChange(false); 691 } 692 } 693 694 @Override 695 public String getType(Uri uri) { 696 final int match = URI_MATCHER.match(uri); 697 switch (match) { 698 case LEGACY: 699 case BOOKMARKS: 700 return Bookmarks.CONTENT_TYPE; 701 case LEGACY_ID: 702 case BOOKMARKS_ID: 703 return Bookmarks.CONTENT_ITEM_TYPE; 704 case HISTORY: 705 return History.CONTENT_TYPE; 706 case HISTORY_ID: 707 return History.CONTENT_ITEM_TYPE; 708 case SEARCHES: 709 return Searches.CONTENT_TYPE; 710 case SEARCHES_ID: 711 return Searches.CONTENT_ITEM_TYPE; 712 } 713 return null; 714 } 715 716 boolean isNullAccount(String account) { 717 if (account == null) return true; 718 account = account.trim(); 719 return account.length() == 0 || account.equals("null"); 720 } 721 722 Object[] getSelectionWithAccounts(Uri uri, String selection, String[] selectionArgs) { 723 // Look for account info 724 String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE); 725 String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME); 726 boolean hasAccounts = false; 727 if (accountType != null && accountName != null) { 728 if (!isNullAccount(accountType) && !isNullAccount(accountName)) { 729 selection = DatabaseUtils.concatenateWhere(selection, 730 Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=? "); 731 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 732 new String[] { accountType, accountName }); 733 hasAccounts = true; 734 } else { 735 selection = DatabaseUtils.concatenateWhere(selection, 736 Bookmarks.ACCOUNT_NAME + " IS NULL AND " + 737 Bookmarks.ACCOUNT_TYPE + " IS NULL"); 738 } 739 } 740 return new Object[] { selection, selectionArgs, hasAccounts }; 741 } 742 743 @Override 744 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, 745 String sortOrder) { 746 SQLiteDatabase db = mOpenHelper.getReadableDatabase(); 747 final int match = URI_MATCHER.match(uri); 748 SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); 749 String limit = uri.getQueryParameter(BrowserContract.PARAM_LIMIT); 750 switch (match) { 751 case ACCOUNTS: { 752 qb.setTables(VIEW_ACCOUNTS); 753 qb.setProjectionMap(ACCOUNTS_PROJECTION_MAP); 754 break; 755 } 756 757 case BOOKMARKS_FOLDER_ID: 758 case BOOKMARKS_ID: 759 case BOOKMARKS: { 760 // Only show deleted bookmarks if requested to do so 761 if (!uri.getBooleanQueryParameter(Bookmarks.QUERY_PARAMETER_SHOW_DELETED, false)) { 762 selection = DatabaseUtils.concatenateWhere( 763 Bookmarks.IS_DELETED + "=0", selection); 764 } 765 766 if (match == BOOKMARKS_ID) { 767 // Tack on the ID of the specific bookmark requested 768 selection = DatabaseUtils.concatenateWhere(selection, 769 TABLE_BOOKMARKS + "." + Bookmarks._ID + "=?"); 770 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 771 new String[] { Long.toString(ContentUris.parseId(uri)) }); 772 } else if (match == BOOKMARKS_FOLDER_ID) { 773 // Tack on the ID of the specific folder requested 774 selection = DatabaseUtils.concatenateWhere(selection, 775 TABLE_BOOKMARKS + "." + Bookmarks.PARENT + "=?"); 776 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 777 new String[] { Long.toString(ContentUris.parseId(uri)) }); 778 } 779 780 Object[] withAccount = getSelectionWithAccounts(uri, selection, selectionArgs); 781 selection = (String) withAccount[0]; 782 selectionArgs = (String[]) withAccount[1]; 783 boolean hasAccounts = (Boolean) withAccount[2]; 784 785 // Set a default sort order if one isn't specified 786 if (TextUtils.isEmpty(sortOrder)) { 787 if (hasAccounts) { 788 sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC; 789 } else { 790 sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER; 791 } 792 } 793 794 qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP); 795 qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES); 796 break; 797 } 798 799 case BOOKMARKS_FOLDER: { 800 // Look for an account 801 boolean useAccount = false; 802 String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE); 803 String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME); 804 if (!isNullAccount(accountType) && !isNullAccount(accountName)) { 805 useAccount = true; 806 } 807 808 qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES); 809 String[] args; 810 String query; 811 // Set a default sort order if one isn't specified 812 if (TextUtils.isEmpty(sortOrder)) { 813 if (useAccount) { 814 sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC; 815 } else { 816 sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER; 817 } 818 } 819 if (!useAccount) { 820 qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP); 821 String where = Bookmarks.PARENT + "=? AND " + Bookmarks.IS_DELETED + "=0"; 822 where = DatabaseUtils.concatenateWhere(where, selection); 823 args = new String[] { Long.toString(FIXED_ID_ROOT) }; 824 if (selectionArgs != null) { 825 args = DatabaseUtils.appendSelectionArgs(args, selectionArgs); 826 } 827 query = qb.buildQuery(projection, where, null, null, sortOrder, null); 828 } else { 829 qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP); 830 String where = Bookmarks.ACCOUNT_TYPE + "=? AND " + 831 Bookmarks.ACCOUNT_NAME + "=? " + 832 "AND parent = " + 833 "(SELECT _id FROM " + TABLE_BOOKMARKS + " WHERE " + 834 ChromeSyncColumns.SERVER_UNIQUE + "=" + 835 "'" + ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR + "' " + 836 "AND account_type = ? AND account_name = ?) " + 837 "AND " + Bookmarks.IS_DELETED + "=0"; 838 where = DatabaseUtils.concatenateWhere(where, selection); 839 String bookmarksBarQuery = qb.buildQuery(projection, 840 where, null, null, null, null); 841 args = new String[] {accountType, accountName, 842 accountType, accountName}; 843 if (selectionArgs != null) { 844 args = DatabaseUtils.appendSelectionArgs(args, selectionArgs); 845 } 846 847 where = Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=?" + 848 " AND " + ChromeSyncColumns.SERVER_UNIQUE + "=?"; 849 where = DatabaseUtils.concatenateWhere(where, selection); 850 qb.setProjectionMap(OTHER_BOOKMARKS_PROJECTION_MAP); 851 String otherBookmarksQuery = qb.buildQuery(projection, 852 where, null, null, null, null); 853 854 query = qb.buildUnionQuery( 855 new String[] { bookmarksBarQuery, otherBookmarksQuery }, 856 sortOrder, limit); 857 858 args = DatabaseUtils.appendSelectionArgs(args, new String[] { 859 accountType, accountName, ChromeSyncColumns.FOLDER_NAME_OTHER_BOOKMARKS, 860 }); 861 if (selectionArgs != null) { 862 args = DatabaseUtils.appendSelectionArgs(args, selectionArgs); 863 } 864 } 865 866 Cursor cursor = db.rawQuery(query, args); 867 if (cursor != null) { 868 cursor.setNotificationUri(getContext().getContentResolver(), 869 BrowserContract.AUTHORITY_URI); 870 } 871 return cursor; 872 } 873 874 case BOOKMARKS_DEFAULT_FOLDER_ID: { 875 String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME); 876 String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE); 877 long id = queryDefaultFolderId(accountName, accountType); 878 MatrixCursor c = new MatrixCursor(new String[] {Bookmarks._ID}); 879 c.newRow().add(id); 880 return c; 881 } 882 883 case BOOKMARKS_SUGGESTIONS: { 884 return doSuggestQuery(selection, selectionArgs, limit); 885 } 886 887 case HISTORY_ID: { 888 selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?"); 889 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 890 new String[] { Long.toString(ContentUris.parseId(uri)) }); 891 // fall through 892 } 893 case HISTORY: { 894 filterSearchClient(selectionArgs); 895 if (sortOrder == null) { 896 sortOrder = DEFAULT_SORT_HISTORY; 897 } 898 qb.setProjectionMap(HISTORY_PROJECTION_MAP); 899 qb.setTables(TABLE_HISTORY_JOIN_IMAGES); 900 break; 901 } 902 903 case SEARCHES_ID: { 904 selection = DatabaseUtils.concatenateWhere(selection, TABLE_SEARCHES + "._id=?"); 905 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 906 new String[] { Long.toString(ContentUris.parseId(uri)) }); 907 // fall through 908 } 909 case SEARCHES: { 910 qb.setTables(TABLE_SEARCHES); 911 qb.setProjectionMap(SEARCHES_PROJECTION_MAP); 912 break; 913 } 914 915 case SYNCSTATE: { 916 return mSyncHelper.query(db, projection, selection, selectionArgs, sortOrder); 917 } 918 919 case SYNCSTATE_ID: { 920 selection = appendAccountToSelection(uri, selection); 921 String selectionWithId = 922 (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ") 923 + (selection == null ? "" : " AND (" + selection + ")"); 924 return mSyncHelper.query(db, projection, selectionWithId, selectionArgs, sortOrder); 925 } 926 927 case IMAGES: { 928 qb.setTables(TABLE_IMAGES); 929 qb.setProjectionMap(IMAGES_PROJECTION_MAP); 930 break; 931 } 932 933 case LEGACY_ID: 934 case COMBINED_ID: { 935 selection = DatabaseUtils.concatenateWhere( 936 selection, Combined._ID + " = CAST(? AS INTEGER)"); 937 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 938 new String[] { Long.toString(ContentUris.parseId(uri)) }); 939 // fall through 940 } 941 case LEGACY: 942 case COMBINED: { 943 if ((match == LEGACY || match == LEGACY_ID) 944 && projection == null) { 945 projection = Browser.HISTORY_PROJECTION; 946 } 947 String[] args = createCombinedQuery(uri, projection, qb); 948 if (selectionArgs == null) { 949 selectionArgs = args; 950 } else { 951 selectionArgs = DatabaseUtils.appendSelectionArgs(args, selectionArgs); 952 } 953 break; 954 } 955 956 case SETTINGS: { 957 qb.setTables(TABLE_SETTINGS); 958 qb.setProjectionMap(SETTINGS_PROJECTION_MAP); 959 break; 960 } 961 962 default: { 963 throw new UnsupportedOperationException("Unknown URL " + uri.toString()); 964 } 965 } 966 967 Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder, 968 limit); 969 cursor.setNotificationUri(getContext().getContentResolver(), BrowserContract.AUTHORITY_URI); 970 return cursor; 971 } 972 973 private Cursor doSuggestQuery(String selection, String[] selectionArgs, String limit) { 974 if (selectionArgs[0] == null) { 975 return null; 976 } else { 977 String like = selectionArgs[0] + "%"; 978 if (selectionArgs[0].startsWith("http") 979 || selectionArgs[0].startsWith("file")) { 980 selectionArgs[0] = like; 981 } else { 982 selectionArgs = new String[5]; 983 selectionArgs[0] = "http://" + like; 984 selectionArgs[1] = "http://www." + like; 985 selectionArgs[2] = "https://" + like; 986 selectionArgs[3] = "https://www." + like; 987 // To match against titles. 988 selectionArgs[4] = like; 989 selection = SUGGEST_SELECTION; 990 } 991 } 992 selection = DatabaseUtils.concatenateWhere(selection, 993 Bookmarks.IS_DELETED + "=0 AND " + Bookmarks.IS_FOLDER + "=0"); 994 995 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_BOOKMARKS, 996 SUGGEST_PROJECTION, selection, selectionArgs, null, null, 997 DEFAULT_BOOKMARKS_SORT_ORDER, null); 998 999 return new SuggestionsCursor(c); 1000 } 1001 1002 private String[] createCombinedQuery( 1003 Uri uri, String[] projection, SQLiteQueryBuilder qb) { 1004 String[] args = null; 1005 StringBuilder whereBuilder = new StringBuilder(128); 1006 whereBuilder.append(Bookmarks.IS_DELETED); 1007 whereBuilder.append(" = 0"); 1008 // Look for account info 1009 Object[] withAccount = getSelectionWithAccounts(uri, null, null); 1010 String selection = (String) withAccount[0]; 1011 String[] selectionArgs = (String[]) withAccount[1]; 1012 if (selection != null) { 1013 whereBuilder.append(" AND " + selection); 1014 if (selectionArgs != null) { 1015 // We use the selection twice, hence we need to duplicate the args 1016 args = new String[selectionArgs.length * 2]; 1017 System.arraycopy(selectionArgs, 0, args, 0, selectionArgs.length); 1018 System.arraycopy(selectionArgs, 0, args, selectionArgs.length, 1019 selectionArgs.length); 1020 } 1021 } 1022 String where = whereBuilder.toString(); 1023 // Build the bookmark subquery for history union subquery 1024 qb.setTables(TABLE_BOOKMARKS); 1025 String subQuery = qb.buildQuery(null, where, null, null, null, null); 1026 // Build the history union subquery 1027 qb.setTables(String.format(FORMAT_COMBINED_JOIN_SUBQUERY_JOIN_IMAGES, subQuery)); 1028 qb.setProjectionMap(COMBINED_HISTORY_PROJECTION_MAP); 1029 String historySubQuery = qb.buildQuery(null, 1030 null, null, null, null, null); 1031 // Build the bookmark union subquery 1032 qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES); 1033 qb.setProjectionMap(COMBINED_BOOKMARK_PROJECTION_MAP); 1034 where += String.format(" AND %s NOT IN (SELECT %s FROM %s)", 1035 Combined.URL, History.URL, TABLE_HISTORY); 1036 String bookmarksSubQuery = qb.buildQuery(null, where, 1037 null, null, null, null); 1038 // Put it all together 1039 String query = qb.buildUnionQuery( 1040 new String[] {historySubQuery, bookmarksSubQuery}, 1041 null, null); 1042 qb.setTables("(" + query + ")"); 1043 qb.setProjectionMap(null); 1044 return args; 1045 } 1046 1047 int deleteBookmarks(String selection, String[] selectionArgs, 1048 boolean callerIsSyncAdapter) { 1049 //TODO cascade deletes down from folders 1050 final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 1051 if (callerIsSyncAdapter) { 1052 return db.delete(TABLE_BOOKMARKS, selection, selectionArgs); 1053 } 1054 ContentValues values = new ContentValues(); 1055 values.put(Bookmarks.DATE_MODIFIED, System.currentTimeMillis()); 1056 values.put(Bookmarks.IS_DELETED, 1); 1057 return updateBookmarksInTransaction(values, selection, selectionArgs, 1058 callerIsSyncAdapter); 1059 } 1060 1061 @Override 1062 public int deleteInTransaction(Uri uri, String selection, String[] selectionArgs, 1063 boolean callerIsSyncAdapter) { 1064 final int match = URI_MATCHER.match(uri); 1065 final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 1066 int deleted = 0; 1067 switch (match) { 1068 case BOOKMARKS_ID: { 1069 selection = DatabaseUtils.concatenateWhere(selection, 1070 TABLE_BOOKMARKS + "._id=?"); 1071 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 1072 new String[] { Long.toString(ContentUris.parseId(uri)) }); 1073 // fall through 1074 } 1075 case BOOKMARKS: { 1076 // Look for account info 1077 Object[] withAccount = getSelectionWithAccounts(uri, selection, selectionArgs); 1078 selection = (String) withAccount[0]; 1079 selectionArgs = (String[]) withAccount[1]; 1080 deleted = deleteBookmarks(selection, selectionArgs, callerIsSyncAdapter); 1081 pruneImages(); 1082 if (deleted > 0) { 1083 refreshWidgets(); 1084 } 1085 break; 1086 } 1087 1088 case HISTORY_ID: { 1089 selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?"); 1090 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 1091 new String[] { Long.toString(ContentUris.parseId(uri)) }); 1092 // fall through 1093 } 1094 case HISTORY: { 1095 filterSearchClient(selectionArgs); 1096 deleted = db.delete(TABLE_HISTORY, selection, selectionArgs); 1097 pruneImages(); 1098 break; 1099 } 1100 1101 case SEARCHES_ID: { 1102 selection = DatabaseUtils.concatenateWhere(selection, TABLE_SEARCHES + "._id=?"); 1103 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 1104 new String[] { Long.toString(ContentUris.parseId(uri)) }); 1105 // fall through 1106 } 1107 case SEARCHES: { 1108 deleted = db.delete(TABLE_SEARCHES, selection, selectionArgs); 1109 break; 1110 } 1111 1112 case SYNCSTATE: { 1113 deleted = mSyncHelper.delete(db, selection, selectionArgs); 1114 break; 1115 } 1116 case SYNCSTATE_ID: { 1117 String selectionWithId = 1118 (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ") 1119 + (selection == null ? "" : " AND (" + selection + ")"); 1120 deleted = mSyncHelper.delete(db, selectionWithId, selectionArgs); 1121 break; 1122 } 1123 case LEGACY_ID: { 1124 selection = DatabaseUtils.concatenateWhere( 1125 selection, Combined._ID + " = CAST(? AS INTEGER)"); 1126 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 1127 new String[] { Long.toString(ContentUris.parseId(uri)) }); 1128 // fall through 1129 } 1130 case LEGACY: { 1131 String[] projection = new String[] { Combined._ID, 1132 Combined.IS_BOOKMARK, Combined.URL }; 1133 SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); 1134 String[] args = createCombinedQuery(uri, projection, qb); 1135 if (selectionArgs == null) { 1136 selectionArgs = args; 1137 } else { 1138 selectionArgs = DatabaseUtils.appendSelectionArgs( 1139 args, selectionArgs); 1140 } 1141 Cursor c = qb.query(db, projection, selection, selectionArgs, 1142 null, null, null); 1143 while (c.moveToNext()) { 1144 long id = c.getLong(0); 1145 boolean isBookmark = c.getInt(1) != 0; 1146 String url = c.getString(2); 1147 if (isBookmark) { 1148 deleted += deleteBookmarks(Bookmarks._ID + "=?", 1149 new String[] { Long.toString(id) }, 1150 callerIsSyncAdapter); 1151 db.delete(TABLE_HISTORY, History.URL + "=?", 1152 new String[] { url }); 1153 } else { 1154 deleted += db.delete(TABLE_HISTORY, 1155 Bookmarks._ID + "=?", 1156 new String[] { Long.toString(id) }); 1157 } 1158 } 1159 break; 1160 } 1161 default: { 1162 throw new UnsupportedOperationException("Unknown delete URI " + uri); 1163 } 1164 } 1165 if (deleted > 0) { 1166 postNotifyUri(uri); 1167 postNotifyUri(LEGACY_AUTHORITY_URI); 1168 } 1169 return deleted; 1170 } 1171 1172 long queryDefaultFolderId(String accountName, String accountType) { 1173 if (!isNullAccount(accountName) && !isNullAccount(accountType)) { 1174 final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); 1175 Cursor c = db.query(TABLE_BOOKMARKS, new String[] { Bookmarks._ID }, 1176 ChromeSyncColumns.SERVER_UNIQUE + " = ?" + 1177 " AND account_type = ? AND account_name = ?", 1178 new String[] { ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR, 1179 accountType, accountName }, null, null, null); 1180 if (c.moveToFirst()) { 1181 return c.getLong(0); 1182 } 1183 } 1184 return FIXED_ID_ROOT; 1185 } 1186 1187 @Override 1188 public Uri insertInTransaction(Uri uri, ContentValues values, boolean callerIsSyncAdapter) { 1189 int match = URI_MATCHER.match(uri); 1190 final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 1191 long id = -1; 1192 if (match == LEGACY) { 1193 // Intercept and route to the correct table 1194 Integer bookmark = values.getAsInteger(BookmarkColumns.BOOKMARK); 1195 values.remove(BookmarkColumns.BOOKMARK); 1196 if (bookmark == null || bookmark == 0) { 1197 match = HISTORY; 1198 } else { 1199 match = BOOKMARKS; 1200 values.remove(BookmarkColumns.DATE); 1201 values.remove(BookmarkColumns.VISITS); 1202 values.remove(BookmarkColumns.USER_ENTERED); 1203 values.put(Bookmarks.IS_FOLDER, 0); 1204 } 1205 } 1206 switch (match) { 1207 case BOOKMARKS: { 1208 // Mark rows dirty if they're not coming from a sync adapter 1209 if (!callerIsSyncAdapter) { 1210 long now = System.currentTimeMillis(); 1211 values.put(Bookmarks.DATE_CREATED, now); 1212 values.put(Bookmarks.DATE_MODIFIED, now); 1213 values.put(Bookmarks.DIRTY, 1); 1214 1215 String accountType = values 1216 .getAsString(Bookmarks.ACCOUNT_TYPE); 1217 String accountName = values 1218 .getAsString(Bookmarks.ACCOUNT_NAME); 1219 boolean hasParent = values.containsKey(Bookmarks.PARENT); 1220 if (hasParent) { 1221 // Let's make sure it's valid 1222 long parentId = values.getAsLong(Bookmarks.PARENT); 1223 hasParent = isValidParent( 1224 accountType, accountName, parentId); 1225 } 1226 1227 // If no parent is set default to the "Bookmarks Bar" folder 1228 if (!hasParent) { 1229 values.put(Bookmarks.PARENT, 1230 queryDefaultFolderId(accountName, accountType)); 1231 } 1232 } 1233 1234 // If no position is requested put the bookmark at the beginning of the list 1235 if (!values.containsKey(Bookmarks.POSITION)) { 1236 values.put(Bookmarks.POSITION, Long.toString(Long.MIN_VALUE)); 1237 } 1238 1239 // Extract out the image values so they can be inserted into the images table 1240 String url = values.getAsString(Bookmarks.URL); 1241 ContentValues imageValues = extractImageValues(values, url); 1242 Boolean isFolder = values.getAsBoolean(Bookmarks.IS_FOLDER); 1243 if ((isFolder == null || !isFolder) 1244 && imageValues != null && !TextUtils.isEmpty(url)) { 1245 int count = db.update(TABLE_IMAGES, imageValues, Images.URL + "=?", 1246 new String[] { url }); 1247 if (count == 0) { 1248 db.insertOrThrow(TABLE_IMAGES, Images.FAVICON, imageValues); 1249 } 1250 } 1251 1252 id = db.insertOrThrow(TABLE_BOOKMARKS, Bookmarks.DIRTY, values); 1253 refreshWidgets(); 1254 break; 1255 } 1256 1257 case HISTORY: { 1258 // If no created time is specified set it to now 1259 if (!values.containsKey(History.DATE_CREATED)) { 1260 values.put(History.DATE_CREATED, System.currentTimeMillis()); 1261 } 1262 String url = values.getAsString(History.URL); 1263 url = filterSearchClient(url); 1264 values.put(History.URL, url); 1265 1266 // Extract out the image values so they can be inserted into the images table 1267 ContentValues imageValues = extractImageValues(values, 1268 values.getAsString(History.URL)); 1269 if (imageValues != null) { 1270 db.insertOrThrow(TABLE_IMAGES, Images.FAVICON, imageValues); 1271 } 1272 1273 id = db.insertOrThrow(TABLE_HISTORY, History.VISITS, values); 1274 break; 1275 } 1276 1277 case SEARCHES: { 1278 id = insertSearchesInTransaction(db, values); 1279 break; 1280 } 1281 1282 case SYNCSTATE: { 1283 id = mSyncHelper.insert(db, values); 1284 break; 1285 } 1286 1287 case SETTINGS: { 1288 id = 0; 1289 insertSettingsInTransaction(db, values); 1290 break; 1291 } 1292 1293 default: { 1294 throw new UnsupportedOperationException("Unknown insert URI " + uri); 1295 } 1296 } 1297 1298 if (id >= 0) { 1299 postNotifyUri(uri); 1300 postNotifyUri(LEGACY_AUTHORITY_URI); 1301 return ContentUris.withAppendedId(uri, id); 1302 } else { 1303 return null; 1304 } 1305 } 1306 1307 private boolean isValidParent(String accountType, String accountName, 1308 long parentId) { 1309 if (parentId <= 0) { 1310 return false; 1311 } 1312 Uri uri = ContentUris.withAppendedId(Bookmarks.CONTENT_URI, parentId); 1313 Cursor c = query(uri, 1314 new String[] { Bookmarks.ACCOUNT_NAME, Bookmarks.ACCOUNT_TYPE }, 1315 null, null, null); 1316 try { 1317 if (c.moveToFirst()) { 1318 String parentName = c.getString(0); 1319 String parentType = c.getString(1); 1320 if (TextUtils.equals(accountName, parentName) 1321 && TextUtils.equals(accountType, parentType)) { 1322 return true; 1323 } 1324 } 1325 return false; 1326 } finally { 1327 c.close(); 1328 } 1329 } 1330 1331 private void filterSearchClient(String[] selectionArgs) { 1332 if (selectionArgs != null) { 1333 for (int i = 0; i < selectionArgs.length; i++) { 1334 selectionArgs[i] = filterSearchClient(selectionArgs[i]); 1335 } 1336 } 1337 } 1338 1339 // Filters out the client= param for search urls 1340 private String filterSearchClient(String url) { 1341 // remove "client" before updating it to the history so that it wont 1342 // show up in the auto-complete list. 1343 int index = url.indexOf("client="); 1344 if (index > 0 && url.contains(".google.")) { 1345 int end = url.indexOf('&', index); 1346 if (end > 0) { 1347 url = url.substring(0, index) 1348 .concat(url.substring(end + 1)); 1349 } else { 1350 // the url.charAt(index-1) should be either '?' or '&' 1351 url = url.substring(0, index-1); 1352 } 1353 } 1354 return url; 1355 } 1356 1357 /** 1358 * Searches are unique, so perform an UPSERT manually since SQLite doesn't support them. 1359 */ 1360 private long insertSearchesInTransaction(SQLiteDatabase db, ContentValues values) { 1361 String search = values.getAsString(Searches.SEARCH); 1362 if (TextUtils.isEmpty(search)) { 1363 throw new IllegalArgumentException("Must include the SEARCH field"); 1364 } 1365 Cursor cursor = null; 1366 try { 1367 cursor = db.query(TABLE_SEARCHES, new String[] { Searches._ID }, 1368 Searches.SEARCH + "=?", new String[] { search }, null, null, null); 1369 if (cursor.moveToNext()) { 1370 long id = cursor.getLong(0); 1371 db.update(TABLE_SEARCHES, values, Searches._ID + "=?", 1372 new String[] { Long.toString(id) }); 1373 return id; 1374 } else { 1375 return db.insertOrThrow(TABLE_SEARCHES, Searches.SEARCH, values); 1376 } 1377 } finally { 1378 if (cursor != null) cursor.close(); 1379 } 1380 } 1381 1382 /** 1383 * Settings are unique, so perform an UPSERT manually since SQLite doesn't support them. 1384 */ 1385 private long insertSettingsInTransaction(SQLiteDatabase db, ContentValues values) { 1386 String key = values.getAsString(Settings.KEY); 1387 if (TextUtils.isEmpty(key)) { 1388 throw new IllegalArgumentException("Must include the KEY field"); 1389 } 1390 String[] keyArray = new String[] { key }; 1391 Cursor cursor = null; 1392 try { 1393 cursor = db.query(TABLE_SETTINGS, new String[] { Settings.KEY }, 1394 Settings.KEY + "=?", keyArray, null, null, null); 1395 if (cursor.moveToNext()) { 1396 long id = cursor.getLong(0); 1397 db.update(TABLE_SETTINGS, values, Settings.KEY + "=?", keyArray); 1398 return id; 1399 } else { 1400 return db.insertOrThrow(TABLE_SETTINGS, Settings.VALUE, values); 1401 } 1402 } finally { 1403 if (cursor != null) cursor.close(); 1404 } 1405 } 1406 1407 @Override 1408 public int updateInTransaction(Uri uri, ContentValues values, String selection, 1409 String[] selectionArgs, boolean callerIsSyncAdapter) { 1410 int match = URI_MATCHER.match(uri); 1411 final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 1412 if (match == LEGACY || match == LEGACY_ID) { 1413 // Intercept and route to the correct table 1414 Integer bookmark = values.getAsInteger(BookmarkColumns.BOOKMARK); 1415 values.remove(BookmarkColumns.BOOKMARK); 1416 if (bookmark == null || bookmark == 0) { 1417 if (match == LEGACY) { 1418 match = HISTORY; 1419 } else { 1420 match = HISTORY_ID; 1421 } 1422 } else { 1423 if (match == LEGACY) { 1424 match = BOOKMARKS; 1425 } else { 1426 match = BOOKMARKS_ID; 1427 } 1428 values.remove(BookmarkColumns.DATE); 1429 values.remove(BookmarkColumns.VISITS); 1430 values.remove(BookmarkColumns.USER_ENTERED); 1431 } 1432 } 1433 int modified = 0; 1434 switch (match) { 1435 case BOOKMARKS_ID: { 1436 selection = DatabaseUtils.concatenateWhere(selection, 1437 TABLE_BOOKMARKS + "._id=?"); 1438 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 1439 new String[] { Long.toString(ContentUris.parseId(uri)) }); 1440 // fall through 1441 } 1442 case BOOKMARKS: { 1443 Object[] withAccount = getSelectionWithAccounts(uri, selection, selectionArgs); 1444 selection = (String) withAccount[0]; 1445 selectionArgs = (String[]) withAccount[1]; 1446 modified = updateBookmarksInTransaction(values, selection, selectionArgs, 1447 callerIsSyncAdapter); 1448 if (modified > 0) { 1449 refreshWidgets(); 1450 } 1451 break; 1452 } 1453 1454 case HISTORY_ID: { 1455 selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?"); 1456 selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, 1457 new String[] { Long.toString(ContentUris.parseId(uri)) }); 1458 // fall through 1459 } 1460 case HISTORY: { 1461 modified = updateHistoryInTransaction(values, selection, selectionArgs); 1462 break; 1463 } 1464 1465 case SYNCSTATE: { 1466 modified = mSyncHelper.update(mDb, values, 1467 appendAccountToSelection(uri, selection), selectionArgs); 1468 break; 1469 } 1470 1471 case SYNCSTATE_ID: { 1472 selection = appendAccountToSelection(uri, selection); 1473 String selectionWithId = 1474 (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ") 1475 + (selection == null ? "" : " AND (" + selection + ")"); 1476 modified = mSyncHelper.update(mDb, values, 1477 selectionWithId, selectionArgs); 1478 break; 1479 } 1480 1481 case IMAGES: { 1482 String url = values.getAsString(Images.URL); 1483 if (TextUtils.isEmpty(url)) { 1484 throw new IllegalArgumentException("Images.URL is required"); 1485 } 1486 if (!shouldUpdateImages(db, url, values)) { 1487 return 0; 1488 } 1489 int count = db.update(TABLE_IMAGES, values, Images.URL + "=?", 1490 new String[] { url }); 1491 if (count == 0) { 1492 db.insertOrThrow(TABLE_IMAGES, Images.FAVICON, values); 1493 count = 1; 1494 } 1495 if (getUrlCount(db, TABLE_BOOKMARKS, url) > 0) { 1496 postNotifyUri(Bookmarks.CONTENT_URI); 1497 refreshWidgets(); 1498 } 1499 if (getUrlCount(db, TABLE_HISTORY, url) > 0) { 1500 postNotifyUri(History.CONTENT_URI); 1501 } 1502 postNotifyUri(LEGACY_AUTHORITY_URI); 1503 pruneImages(); 1504 return count; 1505 } 1506 1507 case SEARCHES: { 1508 modified = db.update(TABLE_SEARCHES, values, selection, selectionArgs); 1509 break; 1510 } 1511 1512 default: { 1513 throw new UnsupportedOperationException("Unknown update URI " + uri); 1514 } 1515 } 1516 pruneImages(); 1517 if (modified > 0) { 1518 postNotifyUri(uri); 1519 postNotifyUri(LEGACY_AUTHORITY_URI); 1520 } 1521 return modified; 1522 } 1523 1524 // We want to avoid sending out more URI notifications than we have to 1525 // Thus, we check to see if the images we are about to store are already there 1526 // This is used because things like a site's favion or touch icon is rarely 1527 // changed, but the browser tries to update it every time the page loads. 1528 // Without this, we will always send out 3 URI notifications per page load. 1529 // With this, that drops to 0 or 1, depending on if the thumbnail changed. 1530 private boolean shouldUpdateImages( 1531 SQLiteDatabase db, String url, ContentValues values) { 1532 final String[] projection = new String[] { 1533 Images.FAVICON, 1534 Images.THUMBNAIL, 1535 Images.TOUCH_ICON, 1536 }; 1537 Cursor cursor = db.query(TABLE_IMAGES, projection, Images.URL + "=?", 1538 new String[] { url }, null, null, null); 1539 byte[] nfavicon = values.getAsByteArray(Images.FAVICON); 1540 byte[] nthumb = values.getAsByteArray(Images.THUMBNAIL); 1541 byte[] ntouch = values.getAsByteArray(Images.TOUCH_ICON); 1542 byte[] cfavicon = null; 1543 byte[] cthumb = null; 1544 byte[] ctouch = null; 1545 try { 1546 if (cursor.getCount() <= 0) { 1547 return nfavicon != null || nthumb != null || ntouch != null; 1548 } 1549 while (cursor.moveToNext()) { 1550 if (nfavicon != null) { 1551 cfavicon = cursor.getBlob(0); 1552 if (!Arrays.equals(nfavicon, cfavicon)) { 1553 return true; 1554 } 1555 } 1556 if (nthumb != null) { 1557 cthumb = cursor.getBlob(1); 1558 if (!Arrays.equals(nthumb, cthumb)) { 1559 return true; 1560 } 1561 } 1562 if (ntouch != null) { 1563 ctouch = cursor.getBlob(2); 1564 if (!Arrays.equals(ntouch, ctouch)) { 1565 return true; 1566 } 1567 } 1568 } 1569 } finally { 1570 cursor.close(); 1571 } 1572 return false; 1573 } 1574 1575 int getUrlCount(SQLiteDatabase db, String table, String url) { 1576 Cursor c = db.query(table, new String[] { "COUNT(*)" }, 1577 "url = ?", new String[] { url }, null, null, null); 1578 try { 1579 int count = 0; 1580 if (c.moveToFirst()) { 1581 count = c.getInt(0); 1582 } 1583 return count; 1584 } finally { 1585 c.close(); 1586 } 1587 } 1588 1589 /** 1590 * Does a query to find the matching bookmarks and updates each one with the provided values. 1591 */ 1592 int updateBookmarksInTransaction(ContentValues values, String selection, 1593 String[] selectionArgs, boolean callerIsSyncAdapter) { 1594 int count = 0; 1595 final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 1596 final String[] bookmarksProjection = new String[] { 1597 Bookmarks._ID, // 0 1598 Bookmarks.VERSION, // 1 1599 Bookmarks.URL, // 2 1600 Bookmarks.TITLE, // 3 1601 Bookmarks.IS_FOLDER, // 4 1602 Bookmarks.ACCOUNT_NAME, // 5 1603 Bookmarks.ACCOUNT_TYPE, // 6 1604 }; 1605 Cursor cursor = db.query(TABLE_BOOKMARKS, bookmarksProjection, 1606 selection, selectionArgs, null, null, null); 1607 boolean updatingParent = values.containsKey(Bookmarks.PARENT); 1608 String parentAccountName = null; 1609 String parentAccountType = null; 1610 if (updatingParent) { 1611 long parent = values.getAsLong(Bookmarks.PARENT); 1612 Cursor c = db.query(TABLE_BOOKMARKS, new String[] { 1613 Bookmarks.ACCOUNT_NAME, Bookmarks.ACCOUNT_TYPE}, 1614 "_id = ?", new String[] { Long.toString(parent) }, 1615 null, null, null); 1616 if (c.moveToFirst()) { 1617 parentAccountName = c.getString(0); 1618 parentAccountType = c.getString(1); 1619 c.close(); 1620 } 1621 } else if (values.containsKey(Bookmarks.ACCOUNT_NAME) 1622 || values.containsKey(Bookmarks.ACCOUNT_TYPE)) { 1623 // TODO: Implement if needed (no one needs this yet) 1624 } 1625 try { 1626 String[] args = new String[1]; 1627 // Mark the bookmark dirty if the caller isn't a sync adapter 1628 if (!callerIsSyncAdapter) { 1629 values.put(Bookmarks.DATE_MODIFIED, System.currentTimeMillis()); 1630 values.put(Bookmarks.DIRTY, 1); 1631 } 1632 1633 boolean updatingUrl = values.containsKey(Bookmarks.URL); 1634 String url = null; 1635 if (updatingUrl) { 1636 url = values.getAsString(Bookmarks.URL); 1637 } 1638 ContentValues imageValues = extractImageValues(values, url); 1639 1640 while (cursor.moveToNext()) { 1641 long id = cursor.getLong(0); 1642 args[0] = Long.toString(id); 1643 String accountName = cursor.getString(5); 1644 String accountType = cursor.getString(6); 1645 // If we are updating the parent and either the account name or 1646 // type do not match that of the new parent 1647 if (updatingParent 1648 && (!TextUtils.equals(accountName, parentAccountName) 1649 || !TextUtils.equals(accountType, parentAccountType))) { 1650 // Parent is a different account 1651 // First, insert a new bookmark/folder with the new account 1652 // Then, if this is a folder, reparent all it's children 1653 // Finally, delete the old bookmark/folder 1654 ContentValues newValues = valuesFromCursor(cursor); 1655 newValues.putAll(values); 1656 newValues.remove(Bookmarks._ID); 1657 newValues.remove(Bookmarks.VERSION); 1658 newValues.put(Bookmarks.ACCOUNT_NAME, parentAccountName); 1659 newValues.put(Bookmarks.ACCOUNT_TYPE, parentAccountType); 1660 Uri insertUri = insertInTransaction(Bookmarks.CONTENT_URI, 1661 newValues, callerIsSyncAdapter); 1662 long newId = ContentUris.parseId(insertUri); 1663 if (cursor.getInt(4) != 0) { 1664 // This is a folder, reparent 1665 ContentValues updateChildren = new ContentValues(1); 1666 updateChildren.put(Bookmarks.PARENT, newId); 1667 count += updateBookmarksInTransaction(updateChildren, 1668 Bookmarks.PARENT + "=?", new String[] { 1669 Long.toString(id)}, callerIsSyncAdapter); 1670 } 1671 // Now, delete the old one 1672 Uri uri = ContentUris.withAppendedId(Bookmarks.CONTENT_URI, id); 1673 deleteInTransaction(uri, null, null, callerIsSyncAdapter); 1674 count += 1; 1675 } else { 1676 if (!callerIsSyncAdapter) { 1677 // increase the local version for non-sync changes 1678 values.put(Bookmarks.VERSION, cursor.getLong(1) + 1); 1679 } 1680 count += db.update(TABLE_BOOKMARKS, values, "_id=?", args); 1681 } 1682 1683 // Update the images over in their table 1684 if (imageValues != null) { 1685 if (!updatingUrl) { 1686 url = cursor.getString(2); 1687 imageValues.put(Images.URL, url); 1688 } 1689 1690 if (!TextUtils.isEmpty(url)) { 1691 args[0] = url; 1692 if (db.update(TABLE_IMAGES, imageValues, Images.URL + "=?", args) == 0) { 1693 db.insert(TABLE_IMAGES, Images.FAVICON, imageValues); 1694 } 1695 } 1696 } 1697 } 1698 } finally { 1699 if (cursor != null) cursor.close(); 1700 } 1701 return count; 1702 } 1703 1704 ContentValues valuesFromCursor(Cursor c) { 1705 int count = c.getColumnCount(); 1706 ContentValues values = new ContentValues(count); 1707 String[] colNames = c.getColumnNames(); 1708 for (int i = 0; i < count; i++) { 1709 switch (c.getType(i)) { 1710 case Cursor.FIELD_TYPE_BLOB: 1711 values.put(colNames[i], c.getBlob(i)); 1712 break; 1713 case Cursor.FIELD_TYPE_FLOAT: 1714 values.put(colNames[i], c.getFloat(i)); 1715 break; 1716 case Cursor.FIELD_TYPE_INTEGER: 1717 values.put(colNames[i], c.getLong(i)); 1718 break; 1719 case Cursor.FIELD_TYPE_STRING: 1720 values.put(colNames[i], c.getString(i)); 1721 break; 1722 } 1723 } 1724 return values; 1725 } 1726 1727 /** 1728 * Does a query to find the matching bookmarks and updates each one with the provided values. 1729 */ 1730 int updateHistoryInTransaction(ContentValues values, String selection, String[] selectionArgs) { 1731 int count = 0; 1732 final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 1733 filterSearchClient(selectionArgs); 1734 Cursor cursor = query(History.CONTENT_URI, 1735 new String[] { History._ID, History.URL }, 1736 selection, selectionArgs, null); 1737 try { 1738 String[] args = new String[1]; 1739 1740 boolean updatingUrl = values.containsKey(History.URL); 1741 String url = null; 1742 if (updatingUrl) { 1743 url = filterSearchClient(values.getAsString(History.URL)); 1744 values.put(History.URL, url); 1745 } 1746 ContentValues imageValues = extractImageValues(values, url); 1747 1748 while (cursor.moveToNext()) { 1749 args[0] = cursor.getString(0); 1750 count += db.update(TABLE_HISTORY, values, "_id=?", args); 1751 1752 // Update the images over in their table 1753 if (imageValues != null) { 1754 if (!updatingUrl) { 1755 url = cursor.getString(1); 1756 imageValues.put(Images.URL, url); 1757 } 1758 args[0] = url; 1759 if (db.update(TABLE_IMAGES, imageValues, Images.URL + "=?", args) == 0) { 1760 db.insert(TABLE_IMAGES, Images.FAVICON, imageValues); 1761 } 1762 } 1763 } 1764 } finally { 1765 if (cursor != null) cursor.close(); 1766 } 1767 return count; 1768 } 1769 1770 String appendAccountToSelection(Uri uri, String selection) { 1771 final String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME); 1772 final String accountType = uri.getQueryParameter(RawContacts.ACCOUNT_TYPE); 1773 1774 final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType); 1775 if (partialUri) { 1776 // Throw when either account is incomplete 1777 throw new IllegalArgumentException( 1778 "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE for " + uri); 1779 } 1780 1781 // Accounts are valid by only checking one parameter, since we've 1782 // already ruled out partial accounts. 1783 final boolean validAccount = !TextUtils.isEmpty(accountName); 1784 if (validAccount) { 1785 StringBuilder selectionSb = new StringBuilder(RawContacts.ACCOUNT_NAME + "=" 1786 + DatabaseUtils.sqlEscapeString(accountName) + " AND " 1787 + RawContacts.ACCOUNT_TYPE + "=" 1788 + DatabaseUtils.sqlEscapeString(accountType)); 1789 if (!TextUtils.isEmpty(selection)) { 1790 selectionSb.append(" AND ("); 1791 selectionSb.append(selection); 1792 selectionSb.append(')'); 1793 } 1794 return selectionSb.toString(); 1795 } else { 1796 return selection; 1797 } 1798 } 1799 1800 ContentValues extractImageValues(ContentValues values, String url) { 1801 ContentValues imageValues = null; 1802 // favicon 1803 if (values.containsKey(Bookmarks.FAVICON)) { 1804 imageValues = new ContentValues(); 1805 imageValues.put(Images.FAVICON, values.getAsByteArray(Bookmarks.FAVICON)); 1806 values.remove(Bookmarks.FAVICON); 1807 } 1808 1809 // thumbnail 1810 if (values.containsKey(Bookmarks.THUMBNAIL)) { 1811 if (imageValues == null) { 1812 imageValues = new ContentValues(); 1813 } 1814 imageValues.put(Images.THUMBNAIL, values.getAsByteArray(Bookmarks.THUMBNAIL)); 1815 values.remove(Bookmarks.THUMBNAIL); 1816 } 1817 1818 // touch icon 1819 if (values.containsKey(Bookmarks.TOUCH_ICON)) { 1820 if (imageValues == null) { 1821 imageValues = new ContentValues(); 1822 } 1823 imageValues.put(Images.TOUCH_ICON, values.getAsByteArray(Bookmarks.TOUCH_ICON)); 1824 values.remove(Bookmarks.TOUCH_ICON); 1825 } 1826 1827 if (imageValues != null) { 1828 imageValues.put(Images.URL, url); 1829 } 1830 return imageValues; 1831 } 1832 1833 void pruneImages() { 1834 final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 1835 db.delete(TABLE_IMAGES, IMAGE_PRUNE, null); 1836 } 1837 1838 static class SuggestionsCursor extends AbstractCursor { 1839 private static final int ID_INDEX = 0; 1840 private static final int URL_INDEX = 1; 1841 private static final int TITLE_INDEX = 2; 1842 // shared suggestion array index, make sure to match COLUMNS 1843 private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1; 1844 private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2; 1845 private static final int SUGGEST_COLUMN_TEXT_1_ID = 3; 1846 private static final int SUGGEST_COLUMN_TEXT_2_TEXT_ID = 4; 1847 private static final int SUGGEST_COLUMN_TEXT_2_URL_ID = 5; 1848 private static final int SUGGEST_COLUMN_ICON_1_ID = 6; 1849 1850 // shared suggestion columns 1851 private static final String[] COLUMNS = new String[] { 1852 BaseColumns._ID, 1853 SearchManager.SUGGEST_COLUMN_INTENT_ACTION, 1854 SearchManager.SUGGEST_COLUMN_INTENT_DATA, 1855 SearchManager.SUGGEST_COLUMN_TEXT_1, 1856 SearchManager.SUGGEST_COLUMN_TEXT_2, 1857 SearchManager.SUGGEST_COLUMN_TEXT_2_URL, 1858 SearchManager.SUGGEST_COLUMN_ICON_1}; 1859 1860 private Cursor mSource; 1861 1862 public SuggestionsCursor(Cursor cursor) { 1863 mSource = cursor; 1864 } 1865 1866 @Override 1867 public String[] getColumnNames() { 1868 return COLUMNS; 1869 } 1870 1871 @Override 1872 public String getString(int columnIndex) { 1873 switch (columnIndex) { 1874 case ID_INDEX: 1875 return mSource.getString(columnIndex); 1876 case SUGGEST_COLUMN_INTENT_ACTION_ID: 1877 return Intent.ACTION_VIEW; 1878 case SUGGEST_COLUMN_INTENT_DATA_ID: 1879 case SUGGEST_COLUMN_TEXT_2_TEXT_ID: 1880 case SUGGEST_COLUMN_TEXT_2_URL_ID: 1881 return UrlUtils.stripUrl(mSource.getString(URL_INDEX)); 1882 case SUGGEST_COLUMN_TEXT_1_ID: 1883 return mSource.getString(TITLE_INDEX); 1884 case SUGGEST_COLUMN_ICON_1_ID: 1885 return Integer.toString(R.drawable.ic_bookmark_off_holo_dark); 1886 } 1887 return null; 1888 } 1889 1890 @Override 1891 public int getCount() { 1892 return mSource.getCount(); 1893 } 1894 1895 @Override 1896 public double getDouble(int column) { 1897 throw new UnsupportedOperationException(); 1898 } 1899 1900 @Override 1901 public float getFloat(int column) { 1902 throw new UnsupportedOperationException(); 1903 } 1904 1905 @Override 1906 public int getInt(int column) { 1907 throw new UnsupportedOperationException(); 1908 } 1909 1910 @Override 1911 public long getLong(int column) { 1912 switch (column) { 1913 case ID_INDEX: 1914 return mSource.getLong(ID_INDEX); 1915 } 1916 throw new UnsupportedOperationException(); 1917 } 1918 1919 @Override 1920 public short getShort(int column) { 1921 throw new UnsupportedOperationException(); 1922 } 1923 1924 @Override 1925 public boolean isNull(int column) { 1926 return mSource.isNull(column); 1927 } 1928 1929 @Override 1930 public boolean onMove(int oldPosition, int newPosition) { 1931 return mSource.moveToPosition(newPosition); 1932 } 1933 } 1934} 1935