PhotoProvider.java revision aebb3b012aef838001c5f9e6adfa4bbcc7bb6569
1/* 2 * Copyright (C) 2013 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 */ 16package com.android.photos.data; 17 18import android.content.ContentProvider; 19import android.content.ContentUris; 20import android.content.ContentValues; 21import android.content.UriMatcher; 22import android.database.Cursor; 23import android.database.DatabaseUtils; 24import android.database.sqlite.SQLiteDatabase; 25import android.database.sqlite.SQLiteOpenHelper; 26import android.database.sqlite.SQLiteQueryBuilder; 27import android.media.ExifInterface; 28import android.net.Uri; 29import android.os.CancellationSignal; 30import android.provider.BaseColumns; 31 32import java.util.ArrayList; 33import java.util.List; 34 35/** 36 * A provider that gives access to photo and video information for media stored 37 * on the server. Only media that is or will be put on the server will be 38 * accessed by this provider. Use Photos.CONTENT_URI to query all photos and 39 * videos. Use Albums.CONTENT_URI to query all albums. Use Metadata.CONTENT_URI 40 * to query metadata about a photo or video, based on the ID of the media. Use 41 * ImageCache.THUMBNAIL_CONTENT_URI, ImageCache.PREVIEW_CONTENT_URI, or 42 * ImageCache.ORIGINAL_CONTENT_URI to query the path of the thumbnail, preview, 43 * or original-sized image respectfully. <br/> 44 * To add or update metadata, use the update function rather than insert. All 45 * values for the metadata must be in the ContentValues, even if they are also 46 * in the selection. The selection and selectionArgs are not used when updating 47 * metadata. If the metadata values are null, the row will be deleted. 48 */ 49public class PhotoProvider extends ContentProvider { 50 @SuppressWarnings("unused") 51 private static final String TAG = PhotoProvider.class.getSimpleName(); 52 53 protected static final String DB_NAME = "photo.db"; 54 public static final String AUTHORITY = PhotoProviderAuthority.AUTHORITY; 55 static final Uri BASE_CONTENT_URI = new Uri.Builder().scheme("content").authority(AUTHORITY) 56 .build(); 57 58 // Used to allow mocking out the change notification because 59 // MockContextResolver disallows system-wide notification. 60 public static interface ChangeNotification { 61 void notifyChange(Uri uri); 62 } 63 64 /** 65 * Contains columns that can be accessed via Accounts.CONTENT_URI 66 */ 67 public static interface Accounts extends BaseColumns { 68 /** 69 * Internal database table used for account information 70 */ 71 public static final String TABLE = "accounts"; 72 /** 73 * Content URI for account information 74 */ 75 public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, TABLE); 76 /** 77 * User name for this account. 78 */ 79 public static final String ACCOUNT_NAME = "name"; 80 } 81 82 /** 83 * Contains columns that can be accessed via Photos.CONTENT_URI. 84 */ 85 public static interface Photos extends BaseColumns { 86 /** Internal database table used for basic photo information. */ 87 public static final String TABLE = "photo"; 88 /** Content URI for basic photo and video information. */ 89 public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, TABLE); 90 91 /** Long foreign key to Accounts._ID */ 92 public static final String ACCOUNT_ID = "account_id"; 93 /** Column name for the width of the original image. Integer value. */ 94 public static final String WIDTH = "width"; 95 /** Column name for the height of the original image. Integer value. */ 96 public static final String HEIGHT = "height"; 97 /** 98 * Column name for the date that the original image was taken. Long 99 * value indicating the milliseconds since epoch in the GMT time zone. 100 */ 101 public static final String DATE_TAKEN = "date_taken"; 102 /** 103 * Column name indicating the long value of the album id that this image 104 * resides in. Will be NULL if it it has not been uploaded to the 105 * server. 106 */ 107 public static final String ALBUM_ID = "album_id"; 108 /** The column name for the mime-type String. */ 109 public static final String MIME_TYPE = "mime_type"; 110 /** The title of the photo. String value. */ 111 public static final String TITLE = "title"; 112 /** The date the photo entry was last updated. Long value. */ 113 public static final String DATE_MODIFIED = "date_modified"; 114 /** 115 * The rotation of the photo in degrees, if rotation has not already 116 * been applied. Integer value. 117 */ 118 public static final String ROTATION = "rotation"; 119 } 120 121 /** 122 * Contains columns and Uri for accessing album information. 123 */ 124 public static interface Albums extends BaseColumns { 125 /** Internal database table used album information. */ 126 public static final String TABLE = "album"; 127 /** Content URI for album information. */ 128 public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, TABLE); 129 130 /** Long foreign key to Accounts._ID */ 131 public static final String ACCOUNT_ID = "account_id"; 132 /** Parent directory or null if this is in the root. */ 133 public static final String PARENT_ID = "parent_id"; 134 /** Column name for the name of the album. String value. */ 135 public static final String NAME = "name"; 136 /** 137 * Column name for the visibility level of the album. Can be any of the 138 * VISIBILITY_* values. 139 */ 140 public static final String VISIBILITY = "visibility"; 141 /** The user-specified location associated with the album. String value. */ 142 public static final String LOCATION_STRING = "location_string"; 143 /** The title of the album. String value. */ 144 public static final String TITLE = "title"; 145 /** A short summary of the contents of the album. String value. */ 146 public static final String SUMMARY = "summary"; 147 /** The date the album was created. Long value */ 148 public static final String DATE_PUBLISHED = "date_published"; 149 /** The date the album entry was last updated. Long value. */ 150 public static final String DATE_MODIFIED = "date_modified"; 151 152 // Privacy values for Albums.VISIBILITY 153 public static final int VISIBILITY_PRIVATE = 1; 154 public static final int VISIBILITY_SHARED = 2; 155 public static final int VISIBILITY_PUBLIC = 3; 156 } 157 158 /** 159 * Contains columns and Uri for accessing photo and video metadata 160 */ 161 public static interface Metadata extends BaseColumns { 162 /** Internal database table used metadata information. */ 163 public static final String TABLE = "metadata"; 164 /** Content URI for photo and video metadata. */ 165 public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, TABLE); 166 /** Foreign key to photo_id. Long value. */ 167 public static final String PHOTO_ID = "photo_id"; 168 /** Metadata key. String value */ 169 public static final String KEY = "key"; 170 /** 171 * Metadata value. Type is based on key. 172 */ 173 public static final String VALUE = "value"; 174 175 /** A short summary of the photo. String value. */ 176 public static final String KEY_SUMMARY = "summary"; 177 /** The date the photo was added. Long value. */ 178 public static final String KEY_PUBLISHED = "date_published"; 179 /** The date the photo was last updated. Long value. */ 180 public static final String KEY_DATE_UPDATED = "date_updated"; 181 /** The size of the photo is bytes. Integer value. */ 182 public static final String KEY_SIZE_IN_BTYES = "size"; 183 /** The latitude associated with the photo. Double value. */ 184 public static final String KEY_LATITUDE = "latitude"; 185 /** The longitude associated with the photo. Double value. */ 186 public static final String KEY_LONGITUDE = "longitude"; 187 188 /** The make of the camera used. String value. */ 189 public static final String KEY_EXIF_MAKE = ExifInterface.TAG_MAKE; 190 /** The model of the camera used. String value. */ 191 public static final String KEY_EXIF_MODEL = ExifInterface.TAG_MODEL;; 192 /** The exposure time used. Float value. */ 193 public static final String KEY_EXIF_EXPOSURE = ExifInterface.TAG_EXPOSURE_TIME; 194 /** Whether the flash was used. Boolean value. */ 195 public static final String KEY_EXIF_FLASH = ExifInterface.TAG_FLASH; 196 /** The focal length used. Float value. */ 197 public static final String KEY_EXIF_FOCAL_LENGTH = ExifInterface.TAG_FOCAL_LENGTH; 198 /** The fstop value used. Float value. */ 199 public static final String KEY_EXIF_FSTOP = ExifInterface.TAG_APERTURE; 200 /** The ISO equivalent value used. Integer value. */ 201 public static final String KEY_EXIF_ISO = ExifInterface.TAG_ISO; 202 } 203 204 /** 205 * Contains columns and Uri for maintaining the image cache. 206 */ 207 public static interface ImageCache extends BaseColumns { 208 /** Internal database table used for the image cache */ 209 public static final String TABLE = "image_cache"; 210 211 /** 212 * The image_type query parameter required for accessing a specific 213 * image 214 */ 215 public static final String IMAGE_TYPE_QUERY_PARAMETER = "image_type"; 216 217 // ImageCache.IMAGE_TYPE values 218 public static final int IMAGE_TYPE_ALBUM_COVER = 1; 219 public static final int IMAGE_TYPE_THUMBNAIL = 2; 220 public static final int IMAGE_TYPE_PREVIEW = 3; 221 public static final int IMAGE_TYPE_ORIGINAL = 4; 222 223 /** 224 * Content URI for retrieving image paths. The 225 * IMAGE_TYPE_QUERY_PARAMETER must be used in queries. 226 */ 227 public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, TABLE); 228 229 /** 230 * Content URI for retrieving the album cover art. The album ID must be 231 * appended to the URI. 232 */ 233 public static final Uri ALBUM_COVER_CONTENT_URI = Uri.withAppendedPath(CONTENT_URI, 234 Albums.TABLE); 235 236 /** 237 * An _ID from Albums or Photos, depending on whether IMAGE_TYPE is 238 * IMAGE_TYPE_ALBUM or not. Long value. 239 */ 240 public static final String REMOTE_ID = "remote_id"; 241 /** One of IMAGE_TYPE_* values. */ 242 public static final String IMAGE_TYPE = "image_type"; 243 /** The String path to the image. */ 244 public static final String PATH = "path"; 245 }; 246 247 // SQL used within this class. 248 protected static final String WHERE_ID = BaseColumns._ID + " = ?"; 249 protected static final String WHERE_METADATA_ID = Metadata.PHOTO_ID + " = ? AND " 250 + Metadata.KEY + " = ?"; 251 252 protected static final String SELECT_ALBUM_ID = "SELECT " + Albums._ID + " FROM " 253 + Albums.TABLE; 254 protected static final String SELECT_PHOTO_ID = "SELECT " + Photos._ID + " FROM " 255 + Photos.TABLE; 256 protected static final String SELECT_PHOTO_COUNT = "SELECT COUNT(*) FROM " + Photos.TABLE; 257 protected static final String DELETE_PHOTOS = "DELETE FROM " + Photos.TABLE; 258 protected static final String DELETE_METADATA = "DELETE FROM " + Metadata.TABLE; 259 protected static final String SELECT_METADATA_COUNT = "SELECT COUNT(*) FROM " + Metadata.TABLE; 260 protected static final String WHERE = " WHERE "; 261 protected static final String IN = " IN "; 262 protected static final String NESTED_SELECT_START = "("; 263 protected static final String NESTED_SELECT_END = ")"; 264 265 /** 266 * For selecting the mime-type for an image. 267 */ 268 private static final String[] PROJECTION_MIME_TYPE = { 269 Photos.MIME_TYPE, 270 }; 271 272 private static final String[] BASE_COLUMNS_ID = { 273 BaseColumns._ID, 274 }; 275 276 protected ChangeNotification mNotifier = null; 277 private SQLiteOpenHelper mOpenHelper; 278 protected static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); 279 280 protected static final int MATCH_PHOTO = 1; 281 protected static final int MATCH_PHOTO_ID = 2; 282 protected static final int MATCH_ALBUM = 3; 283 protected static final int MATCH_ALBUM_ID = 4; 284 protected static final int MATCH_METADATA = 5; 285 protected static final int MATCH_METADATA_ID = 6; 286 protected static final int MATCH_IMAGE = 7; 287 protected static final int MATCH_ALBUM_COVER = 8; 288 289 static { 290 sUriMatcher.addURI(AUTHORITY, Photos.TABLE, MATCH_PHOTO); 291 // match against Photos._ID 292 sUriMatcher.addURI(AUTHORITY, Photos.TABLE + "/#", MATCH_PHOTO_ID); 293 sUriMatcher.addURI(AUTHORITY, Albums.TABLE, MATCH_ALBUM); 294 // match against Albums._ID 295 sUriMatcher.addURI(AUTHORITY, Albums.TABLE + "/#", MATCH_ALBUM_ID); 296 sUriMatcher.addURI(AUTHORITY, Metadata.TABLE, MATCH_METADATA); 297 // match against metadata/<Metadata._ID> 298 sUriMatcher.addURI(AUTHORITY, Metadata.TABLE + "/#", MATCH_METADATA_ID); 299 // match against image_cache/<ImageCache.PHOTO_ID> 300 sUriMatcher.addURI(AUTHORITY, ImageCache.TABLE + "/#", MATCH_IMAGE); 301 // match against image_cache/album/<Albums._ID> 302 sUriMatcher.addURI(AUTHORITY, ImageCache.TABLE + "/" + Albums.TABLE + "/#", 303 MATCH_ALBUM_COVER); 304 } 305 306 @Override 307 public int delete(Uri uri, String selection, String[] selectionArgs) { 308 int match = matchUri(uri); 309 selection = addIdToSelection(match, selection); 310 selectionArgs = addIdToSelectionArgs(match, uri, selectionArgs); 311 List<Uri> changeUris = new ArrayList<Uri>(); 312 int deleted = 0; 313 SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 314 db.beginTransaction(); 315 try { 316 deleted = deleteCascade(db, match, selection, selectionArgs, changeUris, uri); 317 db.setTransactionSuccessful(); 318 } finally { 319 db.endTransaction(); 320 } 321 for (Uri changeUri : changeUris) { 322 notifyChanges(changeUri); 323 } 324 return deleted; 325 } 326 327 @Override 328 public String getType(Uri uri) { 329 Cursor cursor = query(uri, PROJECTION_MIME_TYPE, null, null, null); 330 String mimeType = null; 331 if (cursor.moveToNext()) { 332 mimeType = cursor.getString(0); 333 } 334 cursor.close(); 335 return mimeType; 336 } 337 338 @Override 339 public Uri insert(Uri uri, ContentValues values) { 340 int match = matchUri(uri); 341 validateMatchTable(match); 342 String table = getTableFromMatch(match, uri); 343 SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 344 Uri insertedUri = null; 345 db.beginTransaction(); 346 try { 347 long id = db.insert(table, null, values); 348 if (id != -1) { 349 // uri already matches the table. 350 insertedUri = ContentUris.withAppendedId(uri, id); 351 } 352 db.setTransactionSuccessful(); 353 } finally { 354 db.endTransaction(); 355 } 356 notifyChanges(insertedUri); 357 return insertedUri; 358 } 359 360 @Override 361 public boolean onCreate() { 362 mOpenHelper = createDatabaseHelper(); 363 return true; 364 } 365 366 @Override 367 public void shutdown() { 368 getDatabaseHelper().close(); 369 } 370 371 @Override 372 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, 373 String sortOrder) { 374 return query(uri, projection, selection, selectionArgs, sortOrder, null); 375 } 376 377 @Override 378 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, 379 String sortOrder, CancellationSignal cancellationSignal) { 380 int match = matchUri(uri); 381 selection = addIdToSelection(match, selection); 382 selectionArgs = addIdToSelectionArgs(match, uri, selectionArgs); 383 String table = getTableFromMatch(match, uri); 384 SQLiteDatabase db = mOpenHelper.getReadableDatabase(); 385 return db.query(false, table, projection, selection, selectionArgs, null, null, sortOrder, 386 null, cancellationSignal); 387 } 388 389 @Override 390 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { 391 int match = matchUri(uri); 392 int rowsUpdated = 0; 393 SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 394 db.beginTransaction(); 395 try { 396 if (match == MATCH_METADATA) { 397 rowsUpdated = modifyMetadata(db, values); 398 } else { 399 selection = addIdToSelection(match, selection); 400 selectionArgs = addIdToSelectionArgs(match, uri, selectionArgs); 401 String table = getTableFromMatch(match, uri); 402 rowsUpdated = db.update(table, values, selection, selectionArgs); 403 } 404 db.setTransactionSuccessful(); 405 } finally { 406 db.endTransaction(); 407 } 408 notifyChanges(uri); 409 return rowsUpdated; 410 } 411 412 public void setMockNotification(ChangeNotification notification) { 413 mNotifier = notification; 414 } 415 416 protected static String addIdToSelection(int match, String selection) { 417 String where; 418 switch (match) { 419 case MATCH_PHOTO_ID: 420 case MATCH_ALBUM_ID: 421 case MATCH_METADATA_ID: 422 where = WHERE_ID; 423 break; 424 default: 425 return selection; 426 } 427 return DatabaseUtils.concatenateWhere(selection, where); 428 } 429 430 protected static String[] addIdToSelectionArgs(int match, Uri uri, String[] selectionArgs) { 431 String[] whereArgs; 432 switch (match) { 433 case MATCH_PHOTO_ID: 434 case MATCH_ALBUM_ID: 435 case MATCH_METADATA_ID: 436 whereArgs = new String[] { 437 uri.getPathSegments().get(1), 438 }; 439 break; 440 default: 441 return selectionArgs; 442 } 443 return DatabaseUtils.appendSelectionArgs(selectionArgs, whereArgs); 444 } 445 446 protected static String[] addMetadataKeysToSelectionArgs(String[] selectionArgs, Uri uri) { 447 List<String> segments = uri.getPathSegments(); 448 String[] additionalArgs = { 449 segments.get(1), 450 segments.get(2), 451 }; 452 453 return DatabaseUtils.appendSelectionArgs(selectionArgs, additionalArgs); 454 } 455 456 protected static String getTableFromMatch(int match, Uri uri) { 457 String table; 458 switch (match) { 459 case MATCH_PHOTO: 460 case MATCH_PHOTO_ID: 461 table = Photos.TABLE; 462 break; 463 case MATCH_ALBUM: 464 case MATCH_ALBUM_ID: 465 table = Albums.TABLE; 466 break; 467 case MATCH_METADATA: 468 case MATCH_METADATA_ID: 469 table = Metadata.TABLE; 470 break; 471 default: 472 throw unknownUri(uri); 473 } 474 return table; 475 } 476 477 protected final SQLiteOpenHelper getDatabaseHelper() { 478 return mOpenHelper; 479 } 480 481 protected SQLiteOpenHelper createDatabaseHelper() { 482 return new PhotoDatabase(getContext(), DB_NAME); 483 } 484 485 private int modifyMetadata(SQLiteDatabase db, ContentValues values) { 486 int rowCount; 487 if (values.get(Metadata.VALUE) == null) { 488 String[] selectionArgs = { 489 values.getAsString(Metadata.PHOTO_ID), values.getAsString(Metadata.KEY), 490 }; 491 rowCount = db.delete(Metadata.TABLE, WHERE_METADATA_ID, selectionArgs); 492 } else { 493 long rowId = db.replace(Metadata.TABLE, null, values); 494 rowCount = (rowId == -1) ? 0 : 1; 495 } 496 return rowCount; 497 } 498 499 private int matchUri(Uri uri) { 500 int match = sUriMatcher.match(uri); 501 if (match == UriMatcher.NO_MATCH) { 502 throw unknownUri(uri); 503 } 504 if (match == MATCH_IMAGE || match == MATCH_ALBUM_COVER) { 505 throw new IllegalArgumentException("Operation not allowed on image cache database"); 506 } 507 return match; 508 } 509 510 protected void notifyChanges(Uri uri) { 511 if (mNotifier != null) { 512 mNotifier.notifyChange(uri); 513 } else { 514 getContext().getContentResolver().notifyChange(uri, null, false); 515 } 516 } 517 518 protected static IllegalArgumentException unknownUri(Uri uri) { 519 return new IllegalArgumentException("Unknown Uri format: " + uri); 520 } 521 522 protected static String nestWhere(String matchColumn, String table, String nestedWhere) { 523 String query = SQLiteQueryBuilder.buildQueryString(false, table, BASE_COLUMNS_ID, 524 nestedWhere, null, null, null, null); 525 return matchColumn + IN + NESTED_SELECT_START + query + NESTED_SELECT_END; 526 } 527 528 protected static int deleteCascade(SQLiteDatabase db, int match, String selection, 529 String[] selectionArgs, List<Uri> changeUris, Uri uri) { 530 switch (match) { 531 case MATCH_PHOTO: 532 case MATCH_PHOTO_ID: { 533 deleteCascadeMetadata(db, selection, selectionArgs, changeUris); 534 break; 535 } 536 case MATCH_ALBUM: 537 case MATCH_ALBUM_ID: { 538 deleteCascadePhotos(db, selection, selectionArgs, changeUris); 539 break; 540 } 541 } 542 String table = getTableFromMatch(match, uri); 543 int deleted = db.delete(table, selection, selectionArgs); 544 if (deleted > 0) { 545 changeUris.add(uri); 546 } 547 return deleted; 548 } 549 550 private static void deleteCascadePhotos(SQLiteDatabase db, String albumSelect, 551 String[] selectArgs, List<Uri> changeUris) { 552 String photoWhere = nestWhere(Photos.ALBUM_ID, Albums.TABLE, albumSelect); 553 deleteCascadeMetadata(db, photoWhere, selectArgs, changeUris); 554 int deleted = db.delete(Photos.TABLE, photoWhere, selectArgs); 555 if (deleted > 0) { 556 changeUris.add(Photos.CONTENT_URI); 557 } 558 } 559 560 private static void deleteCascadeMetadata(SQLiteDatabase db, String photosSelect, 561 String[] selectArgs, List<Uri> changeUris) { 562 String metadataWhere = nestWhere(Metadata.PHOTO_ID, Photos.TABLE, photosSelect); 563 int deleted = db.delete(Metadata.TABLE, metadataWhere, selectArgs); 564 if (deleted > 0) { 565 changeUris.add(Metadata.CONTENT_URI); 566 } 567 } 568 569 private static void validateMatchTable(int match) { 570 switch (match) { 571 case MATCH_PHOTO: 572 case MATCH_ALBUM: 573 case MATCH_METADATA: 574 break; 575 default: 576 throw new IllegalArgumentException("Operation not allowed on an existing row."); 577 } 578 } 579} 580