PhotoProvider.java revision 8324b3355817e8f6d08ac0b1f7349926df8a9bc7
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.ContentResolver;
19import android.content.ContentUris;
20import android.content.ContentValues;
21import android.content.Context;
22import android.content.UriMatcher;
23import android.database.Cursor;
24import android.database.DatabaseUtils;
25import android.database.sqlite.SQLiteDatabase;
26import android.database.sqlite.SQLiteOpenHelper;
27import android.database.sqlite.SQLiteQueryBuilder;
28import android.media.ExifInterface;
29import android.net.Uri;
30import android.os.CancellationSignal;
31import android.provider.BaseColumns;
32
33import com.android.gallery3d.common.ApiHelper;
34
35import java.util.List;
36
37/**
38 * A provider that gives access to photo and video information for media stored
39 * on the server. Only media that is or will be put on the server will be
40 * accessed by this provider. Use Photos.CONTENT_URI to query all photos and
41 * videos. Use Albums.CONTENT_URI to query all albums. Use Metadata.CONTENT_URI
42 * to query metadata about a photo or video, based on the ID of the media. Use
43 * ImageCache.THUMBNAIL_CONTENT_URI, ImageCache.PREVIEW_CONTENT_URI, or
44 * ImageCache.ORIGINAL_CONTENT_URI to query the path of the thumbnail, preview,
45 * or original-sized image respectfully. <br/>
46 * To add or update metadata, use the update function rather than insert. All
47 * values for the metadata must be in the ContentValues, even if they are also
48 * in the selection. The selection and selectionArgs are not used when updating
49 * metadata. If the metadata values are null, the row will be deleted.
50 */
51public class PhotoProvider extends SQLiteContentProvider {
52    @SuppressWarnings("unused")
53    private static final String TAG = PhotoProvider.class.getSimpleName();
54
55    protected static final String DB_NAME = "photo.db";
56    public static final String AUTHORITY = PhotoProviderAuthority.AUTHORITY;
57    static final Uri BASE_CONTENT_URI = new Uri.Builder().scheme("content").authority(AUTHORITY)
58            .build();
59
60    // Used to allow mocking out the change notification because
61    // MockContextResolver disallows system-wide notification.
62    public static interface ChangeNotification {
63        void notifyChange(Uri uri, boolean syncToNetwork);
64    }
65
66    /**
67     * Contains columns that can be accessed via Accounts.CONTENT_URI
68     */
69    public static interface Accounts extends BaseColumns {
70        /**
71         * Internal database table used for account information
72         */
73        public static final String TABLE = "accounts";
74        /**
75         * Content URI for account information
76         */
77        public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, TABLE);
78        /**
79         * User name for this account.
80         */
81        public static final String ACCOUNT_NAME = "name";
82    }
83
84    /**
85     * Contains columns that can be accessed via Photos.CONTENT_URI.
86     */
87    public static interface Photos extends BaseColumns {
88        /** Internal database table used for basic photo information. */
89        public static final String TABLE = "photos";
90        /** Content URI for basic photo and video information. */
91        public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, TABLE);
92
93        /** Long foreign key to Accounts._ID */
94        public static final String ACCOUNT_ID = "account_id";
95        /** Column name for the width of the original image. Integer value. */
96        public static final String WIDTH = "width";
97        /** Column name for the height of the original image. Integer value. */
98        public static final String HEIGHT = "height";
99        /**
100         * Column name for the date that the original image was taken. Long
101         * value indicating the milliseconds since epoch in the GMT time zone.
102         */
103        public static final String DATE_TAKEN = "date_taken";
104        /**
105         * Column name indicating the long value of the album id that this image
106         * resides in. Will be NULL if it it has not been uploaded to the
107         * server.
108         */
109        public static final String ALBUM_ID = "album_id";
110        /** The column name for the mime-type String. */
111        public static final String MIME_TYPE = "mime_type";
112        /** The title of the photo. String value. */
113        public static final String TITLE = "title";
114        /** The date the photo entry was last updated. Long value. */
115        public static final String DATE_MODIFIED = "date_modified";
116        /**
117         * The rotation of the photo in degrees, if rotation has not already
118         * been applied. Integer value.
119         */
120        public static final String ROTATION = "rotation";
121    }
122
123    /**
124     * Contains columns and Uri for accessing album information.
125     */
126    public static interface Albums extends BaseColumns {
127        /** Internal database table used album information. */
128        public static final String TABLE = "albums";
129        /** Content URI for album information. */
130        public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, TABLE);
131
132        /** Long foreign key to Accounts._ID */
133        public static final String ACCOUNT_ID = "account_id";
134        /** Parent directory or null if this is in the root. */
135        public static final String PARENT_ID = "parent_id";
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    protected static final String[] BASE_COLUMNS_ID = {
273        BaseColumns._ID,
274    };
275
276    protected ChangeNotification mNotifier = null;
277    protected static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
278
279    protected static final int MATCH_PHOTO = 1;
280    protected static final int MATCH_PHOTO_ID = 2;
281    protected static final int MATCH_ALBUM = 3;
282    protected static final int MATCH_ALBUM_ID = 4;
283    protected static final int MATCH_METADATA = 5;
284    protected static final int MATCH_METADATA_ID = 6;
285    protected static final int MATCH_IMAGE = 7;
286    protected static final int MATCH_ALBUM_COVER = 8;
287    protected static final int MATCH_ACCOUNT = 9;
288    protected static final int MATCH_ACCOUNT_ID = 10;
289
290    static {
291        sUriMatcher.addURI(AUTHORITY, Photos.TABLE, MATCH_PHOTO);
292        // match against Photos._ID
293        sUriMatcher.addURI(AUTHORITY, Photos.TABLE + "/#", MATCH_PHOTO_ID);
294        sUriMatcher.addURI(AUTHORITY, Albums.TABLE, MATCH_ALBUM);
295        // match against Albums._ID
296        sUriMatcher.addURI(AUTHORITY, Albums.TABLE + "/#", MATCH_ALBUM_ID);
297        sUriMatcher.addURI(AUTHORITY, Metadata.TABLE, MATCH_METADATA);
298        // match against metadata/<Metadata._ID>
299        sUriMatcher.addURI(AUTHORITY, Metadata.TABLE + "/#", MATCH_METADATA_ID);
300        // match against image_cache/<ImageCache.PHOTO_ID>
301        sUriMatcher.addURI(AUTHORITY, ImageCache.TABLE + "/#", MATCH_IMAGE);
302        // match against image_cache/album/<Albums._ID>
303        sUriMatcher.addURI(AUTHORITY, ImageCache.TABLE + "/" + Albums.TABLE + "/#",
304                MATCH_ALBUM_COVER);
305        sUriMatcher.addURI(AUTHORITY, Accounts.TABLE, MATCH_ACCOUNT);
306        // match against Accounts._ID
307        sUriMatcher.addURI(AUTHORITY, Accounts.TABLE + "/#", MATCH_ACCOUNT_ID);
308    }
309
310    @Override
311    public int deleteInTransaction(Uri uri, String selection, String[] selectionArgs,
312            boolean callerIsSyncAdapter) {
313        int match = matchUri(uri);
314        selection = addIdToSelection(match, selection);
315        selectionArgs = addIdToSelectionArgs(match, uri, selectionArgs);
316        return deleteCascade(uri, match, selection, selectionArgs);
317    }
318
319    @Override
320    public String getType(Uri uri) {
321        Cursor cursor = query(uri, PROJECTION_MIME_TYPE, null, null, null);
322        String mimeType = null;
323        if (cursor.moveToNext()) {
324            mimeType = cursor.getString(0);
325        }
326        cursor.close();
327        return mimeType;
328    }
329
330    @Override
331    public Uri insertInTransaction(Uri uri, ContentValues values, boolean callerIsSyncAdapter) {
332        int match = matchUri(uri);
333        validateMatchTable(match);
334        String table = getTableFromMatch(match, uri);
335        SQLiteDatabase db = getDatabaseHelper().getWritableDatabase();
336        Uri insertedUri = null;
337        long id = db.insert(table, null, values);
338        if (id != -1) {
339            // uri already matches the table.
340            insertedUri = ContentUris.withAppendedId(uri, id);
341            postNotifyUri(insertedUri);
342        }
343        return insertedUri;
344    }
345
346    @Override
347    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
348            String sortOrder) {
349        return query(uri, projection, selection, selectionArgs, sortOrder, null);
350    }
351
352    @Override
353    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
354            String sortOrder, CancellationSignal cancellationSignal) {
355        int match = matchUri(uri);
356        selection = addIdToSelection(match, selection);
357        selectionArgs = addIdToSelectionArgs(match, uri, selectionArgs);
358        String table = getTableFromMatch(match, uri);
359        return query(table, projection, selection, selectionArgs, sortOrder, cancellationSignal);
360    }
361
362    @Override
363    public int updateInTransaction(Uri uri, ContentValues values, String selection,
364            String[] selectionArgs, boolean callerIsSyncAdapter) {
365        int match = matchUri(uri);
366        int rowsUpdated = 0;
367        SQLiteDatabase db = getDatabaseHelper().getWritableDatabase();
368        if (match == MATCH_METADATA) {
369            rowsUpdated = modifyMetadata(db, values);
370        } else {
371            selection = addIdToSelection(match, selection);
372            selectionArgs = addIdToSelectionArgs(match, uri, selectionArgs);
373            String table = getTableFromMatch(match, uri);
374            rowsUpdated = db.update(table, values, selection, selectionArgs);
375        }
376        postNotifyUri(uri);
377        return rowsUpdated;
378    }
379
380    public void setMockNotification(ChangeNotification notification) {
381        mNotifier = notification;
382    }
383
384    protected static String addIdToSelection(int match, String selection) {
385        String where;
386        switch (match) {
387            case MATCH_PHOTO_ID:
388            case MATCH_ALBUM_ID:
389            case MATCH_METADATA_ID:
390                where = WHERE_ID;
391                break;
392            default:
393                return selection;
394        }
395        return DatabaseUtils.concatenateWhere(selection, where);
396    }
397
398    protected static String[] addIdToSelectionArgs(int match, Uri uri, String[] selectionArgs) {
399        String[] whereArgs;
400        switch (match) {
401            case MATCH_PHOTO_ID:
402            case MATCH_ALBUM_ID:
403            case MATCH_METADATA_ID:
404                whereArgs = new String[] {
405                    uri.getPathSegments().get(1),
406                };
407                break;
408            default:
409                return selectionArgs;
410        }
411        return DatabaseUtils.appendSelectionArgs(selectionArgs, whereArgs);
412    }
413
414    protected static String[] addMetadataKeysToSelectionArgs(String[] selectionArgs, Uri uri) {
415        List<String> segments = uri.getPathSegments();
416        String[] additionalArgs = {
417                segments.get(1),
418                segments.get(2),
419        };
420
421        return DatabaseUtils.appendSelectionArgs(selectionArgs, additionalArgs);
422    }
423
424    protected static String getTableFromMatch(int match, Uri uri) {
425        String table;
426        switch (match) {
427            case MATCH_PHOTO:
428            case MATCH_PHOTO_ID:
429                table = Photos.TABLE;
430                break;
431            case MATCH_ALBUM:
432            case MATCH_ALBUM_ID:
433                table = Albums.TABLE;
434                break;
435            case MATCH_METADATA:
436            case MATCH_METADATA_ID:
437                table = Metadata.TABLE;
438                break;
439            case MATCH_ACCOUNT:
440            case MATCH_ACCOUNT_ID:
441                table = Accounts.TABLE;
442                break;
443            default:
444                throw unknownUri(uri);
445        }
446        return table;
447    }
448
449    @Override
450    public SQLiteOpenHelper getDatabaseHelper(Context context) {
451        return new PhotoDatabase(context, DB_NAME);
452    }
453
454    private int modifyMetadata(SQLiteDatabase db, ContentValues values) {
455        int rowCount;
456        if (values.get(Metadata.VALUE) == null) {
457            String[] selectionArgs = {
458                    values.getAsString(Metadata.PHOTO_ID), values.getAsString(Metadata.KEY),
459            };
460            rowCount = db.delete(Metadata.TABLE, WHERE_METADATA_ID, selectionArgs);
461        } else {
462            long rowId = db.replace(Metadata.TABLE, null, values);
463            rowCount = (rowId == -1) ? 0 : 1;
464        }
465        return rowCount;
466    }
467
468    private int matchUri(Uri uri) {
469        int match = sUriMatcher.match(uri);
470        if (match == UriMatcher.NO_MATCH) {
471            throw unknownUri(uri);
472        }
473        if (match == MATCH_IMAGE || match == MATCH_ALBUM_COVER) {
474            throw new IllegalArgumentException("Operation not allowed on image cache database");
475        }
476        return match;
477    }
478
479    @Override
480    protected void notifyChange(ContentResolver resolver, Uri uri, boolean syncToNetwork) {
481        if (mNotifier != null) {
482            mNotifier.notifyChange(uri, syncToNetwork);
483        } else {
484            resolver.notifyChange(uri, null, syncToNetwork);
485        }
486    }
487
488    protected static IllegalArgumentException unknownUri(Uri uri) {
489        return new IllegalArgumentException("Unknown Uri format: " + uri);
490    }
491
492    protected static String nestWhere(String matchColumn, String table, String nestedWhere) {
493        String query = SQLiteQueryBuilder.buildQueryString(false, table, BASE_COLUMNS_ID,
494                nestedWhere, null, null, null, null);
495        return matchColumn + IN + NESTED_SELECT_START + query + NESTED_SELECT_END;
496    }
497
498    protected static String metadataSelectionFromPhotos(String where) {
499        return nestWhere(Metadata.PHOTO_ID, Photos.TABLE, where);
500    }
501
502    protected static String photoSelectionFromAlbums(String where) {
503        return nestWhere(Photos.ALBUM_ID, Albums.TABLE, where);
504    }
505
506    protected static String photoSelectionFromAccounts(String where) {
507        return nestWhere(Photos.ACCOUNT_ID, Accounts.TABLE, where);
508    }
509
510    protected static String albumSelectionFromAccounts(String where) {
511        return nestWhere(Albums.ACCOUNT_ID, Accounts.TABLE, where);
512    }
513
514    protected int deleteCascade(Uri uri, int match, String selection, String[] selectionArgs) {
515        switch (match) {
516            case MATCH_PHOTO:
517            case MATCH_PHOTO_ID:
518                deleteCascade(Metadata.CONTENT_URI, MATCH_METADATA,
519                        metadataSelectionFromPhotos(selection), selectionArgs);
520                break;
521            case MATCH_ALBUM:
522            case MATCH_ALBUM_ID:
523                deleteCascade(Photos.CONTENT_URI, MATCH_PHOTO,
524                        photoSelectionFromAlbums(selection), selectionArgs);
525                break;
526            case MATCH_ACCOUNT:
527            case MATCH_ACCOUNT_ID:
528                deleteCascade(Photos.CONTENT_URI, MATCH_PHOTO,
529                        photoSelectionFromAccounts(selection), selectionArgs);
530                deleteCascade(Albums.CONTENT_URI, MATCH_ALBUM,
531                        albumSelectionFromAccounts(selection), selectionArgs);
532                break;
533        }
534        SQLiteDatabase db = getDatabaseHelper().getWritableDatabase();
535        String table = getTableFromMatch(match, uri);
536        int deleted = db.delete(table, selection, selectionArgs);
537        if (deleted > 0) {
538            postNotifyUri(uri);
539        }
540        return deleted;
541    }
542
543    private static void validateMatchTable(int match) {
544        switch (match) {
545            case MATCH_PHOTO:
546            case MATCH_ALBUM:
547            case MATCH_METADATA:
548            case MATCH_ACCOUNT:
549                break;
550            default:
551                throw new IllegalArgumentException("Operation not allowed on an existing row.");
552        }
553    }
554
555    protected Cursor query(String table, String[] columns, String selection,
556            String[] selectionArgs, String orderBy, CancellationSignal cancellationSignal) {
557        SQLiteDatabase db = getDatabaseHelper().getReadableDatabase();
558        if (ApiHelper.HAS_CANCELLATION_SIGNAL) {
559            return db.query(false, table, columns, selection, selectionArgs, null, null,
560                    orderBy, null, cancellationSignal);
561        } else {
562            return db.query(table, columns, selection, selectionArgs, null, null, orderBy);
563        }
564    }
565}
566