PhotoProvider.java revision 835a0d50318e9cd61bbbd834e36ddda4cff9c59d
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        int deleted = 0;
317        SQLiteDatabase db = getDatabaseHelper().getWritableDatabase();
318        deleted = deleteCascade(db, match, selection, selectionArgs, uri);
319        return deleted;
320    }
321
322    @Override
323    public String getType(Uri uri) {
324        Cursor cursor = query(uri, PROJECTION_MIME_TYPE, null, null, null);
325        String mimeType = null;
326        if (cursor.moveToNext()) {
327            mimeType = cursor.getString(0);
328        }
329        cursor.close();
330        return mimeType;
331    }
332
333    @Override
334    public Uri insertInTransaction(Uri uri, ContentValues values, boolean callerIsSyncAdapter) {
335        int match = matchUri(uri);
336        validateMatchTable(match);
337        String table = getTableFromMatch(match, uri);
338        SQLiteDatabase db = getDatabaseHelper().getWritableDatabase();
339        Uri insertedUri = null;
340        long id = db.insert(table, null, values);
341        if (id != -1) {
342            // uri already matches the table.
343            insertedUri = ContentUris.withAppendedId(uri, id);
344            postNotifyUri(insertedUri);
345        }
346        return insertedUri;
347    }
348
349    @Override
350    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
351            String sortOrder) {
352        return query(uri, projection, selection, selectionArgs, sortOrder, null);
353    }
354
355    @Override
356    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
357            String sortOrder, CancellationSignal cancellationSignal) {
358        int match = matchUri(uri);
359        selection = addIdToSelection(match, selection);
360        selectionArgs = addIdToSelectionArgs(match, uri, selectionArgs);
361        String table = getTableFromMatch(match, uri);
362        Cursor c = query(table, projection, selection, selectionArgs, sortOrder, cancellationSignal);
363        if (c != null) {
364            c.setNotificationUri(getContext().getContentResolver(), uri);
365        }
366        return c;
367    }
368
369    @Override
370    public int updateInTransaction(Uri uri, ContentValues values, String selection,
371            String[] selectionArgs, boolean callerIsSyncAdapter) {
372        int match = matchUri(uri);
373        int rowsUpdated = 0;
374        SQLiteDatabase db = getDatabaseHelper().getWritableDatabase();
375        if (match == MATCH_METADATA) {
376            rowsUpdated = modifyMetadata(db, values);
377        } else {
378            selection = addIdToSelection(match, selection);
379            selectionArgs = addIdToSelectionArgs(match, uri, selectionArgs);
380            String table = getTableFromMatch(match, uri);
381            rowsUpdated = db.update(table, values, selection, selectionArgs);
382        }
383        postNotifyUri(uri);
384        return rowsUpdated;
385    }
386
387    public void setMockNotification(ChangeNotification notification) {
388        mNotifier = notification;
389    }
390
391    protected static String addIdToSelection(int match, String selection) {
392        String where;
393        switch (match) {
394            case MATCH_PHOTO_ID:
395            case MATCH_ALBUM_ID:
396            case MATCH_METADATA_ID:
397                where = WHERE_ID;
398                break;
399            default:
400                return selection;
401        }
402        return DatabaseUtils.concatenateWhere(selection, where);
403    }
404
405    protected static String[] addIdToSelectionArgs(int match, Uri uri, String[] selectionArgs) {
406        String[] whereArgs;
407        switch (match) {
408            case MATCH_PHOTO_ID:
409            case MATCH_ALBUM_ID:
410            case MATCH_METADATA_ID:
411                whereArgs = new String[] {
412                    uri.getPathSegments().get(1),
413                };
414                break;
415            default:
416                return selectionArgs;
417        }
418        return DatabaseUtils.appendSelectionArgs(selectionArgs, whereArgs);
419    }
420
421    protected static String[] addMetadataKeysToSelectionArgs(String[] selectionArgs, Uri uri) {
422        List<String> segments = uri.getPathSegments();
423        String[] additionalArgs = {
424                segments.get(1),
425                segments.get(2),
426        };
427
428        return DatabaseUtils.appendSelectionArgs(selectionArgs, additionalArgs);
429    }
430
431    protected static String getTableFromMatch(int match, Uri uri) {
432        String table;
433        switch (match) {
434            case MATCH_PHOTO:
435            case MATCH_PHOTO_ID:
436                table = Photos.TABLE;
437                break;
438            case MATCH_ALBUM:
439            case MATCH_ALBUM_ID:
440                table = Albums.TABLE;
441                break;
442            case MATCH_METADATA:
443            case MATCH_METADATA_ID:
444                table = Metadata.TABLE;
445                break;
446            case MATCH_ACCOUNT:
447            case MATCH_ACCOUNT_ID:
448                table = Accounts.TABLE;
449                break;
450            default:
451                throw unknownUri(uri);
452        }
453        return table;
454    }
455
456    @Override
457    public SQLiteOpenHelper getDatabaseHelper(Context context) {
458        return new PhotoDatabase(context, DB_NAME);
459    }
460
461    private int modifyMetadata(SQLiteDatabase db, ContentValues values) {
462        int rowCount;
463        if (values.get(Metadata.VALUE) == null) {
464            String[] selectionArgs = {
465                    values.getAsString(Metadata.PHOTO_ID), values.getAsString(Metadata.KEY),
466            };
467            rowCount = db.delete(Metadata.TABLE, WHERE_METADATA_ID, selectionArgs);
468        } else {
469            long rowId = db.replace(Metadata.TABLE, null, values);
470            rowCount = (rowId == -1) ? 0 : 1;
471        }
472        return rowCount;
473    }
474
475    private int matchUri(Uri uri) {
476        int match = sUriMatcher.match(uri);
477        if (match == UriMatcher.NO_MATCH) {
478            throw unknownUri(uri);
479        }
480        if (match == MATCH_IMAGE || match == MATCH_ALBUM_COVER) {
481            throw new IllegalArgumentException("Operation not allowed on image cache database");
482        }
483        return match;
484    }
485
486    @Override
487    protected void notifyChange(ContentResolver resolver, Uri uri, boolean syncToNetwork) {
488        if (mNotifier != null) {
489            mNotifier.notifyChange(uri, syncToNetwork);
490        } else {
491            super.notifyChange(resolver, uri, syncToNetwork);
492        }
493    }
494
495    protected static IllegalArgumentException unknownUri(Uri uri) {
496        return new IllegalArgumentException("Unknown Uri format: " + uri);
497    }
498
499    protected static String nestWhere(String matchColumn, String table, String nestedWhere) {
500        String query = SQLiteQueryBuilder.buildQueryString(false, table, BASE_COLUMNS_ID,
501                nestedWhere, null, null, null, null);
502        return matchColumn + IN + NESTED_SELECT_START + query + NESTED_SELECT_END;
503    }
504
505    protected int deleteCascade(SQLiteDatabase db, int match, String selection,
506            String[] selectionArgs, Uri uri) {
507        switch (match) {
508            case MATCH_PHOTO:
509            case MATCH_PHOTO_ID:
510                deleteCascadeMetadata(db, selection, selectionArgs);
511                break;
512            case MATCH_ALBUM:
513            case MATCH_ALBUM_ID:
514                deleteCascadePhotos(db, selection, selectionArgs);
515                break;
516            case MATCH_ACCOUNT:
517            case MATCH_ACCOUNT_ID:
518                deleteCascadeAccounts(db, selection, selectionArgs);
519                break;
520        }
521        String table = getTableFromMatch(match, uri);
522        int deleted = db.delete(table, selection, selectionArgs);
523        if (deleted > 0) {
524            postNotifyUri(uri);
525        }
526        return deleted;
527    }
528
529    private void deleteCascadeAccounts(SQLiteDatabase db, String accountSelect, String[] args) {
530        // Delete all photos associated with the account
531        String photoWhere = nestWhere(Photos.ACCOUNT_ID, Accounts.TABLE, accountSelect);
532        deleteCascadeMetadata(db, photoWhere, args);
533        db.delete(Photos.TABLE, photoWhere, args);
534
535        // Delete all albums that are associated with this account
536        String albumWhere = nestWhere(Albums.ACCOUNT_ID, Accounts.TABLE, accountSelect);
537        db.delete(Albums.TABLE, albumWhere, args);
538    }
539
540    private void deleteCascadePhotos(SQLiteDatabase db, String albumSelect,
541            String[] selectArgs) {
542        String photoWhere = nestWhere(Photos.ALBUM_ID, Albums.TABLE, albumSelect);
543        deleteCascadeMetadata(db, photoWhere, selectArgs);
544        int deleted = db.delete(Photos.TABLE, photoWhere, selectArgs);
545        if (deleted > 0) {
546            postNotifyUri(Photos.CONTENT_URI);
547        }
548    }
549
550    private void deleteCascadeMetadata(SQLiteDatabase db, String photosSelect,
551            String[] selectArgs) {
552        String metadataWhere = nestWhere(Metadata.PHOTO_ID, Photos.TABLE, photosSelect);
553        int deleted = db.delete(Metadata.TABLE, metadataWhere, selectArgs);
554        if (deleted > 0) {
555            postNotifyUri(Metadata.CONTENT_URI);
556        }
557    }
558
559    private static void validateMatchTable(int match) {
560        switch (match) {
561            case MATCH_PHOTO:
562            case MATCH_ALBUM:
563            case MATCH_METADATA:
564            case MATCH_ACCOUNT:
565                break;
566            default:
567                throw new IllegalArgumentException("Operation not allowed on an existing row.");
568        }
569    }
570
571    protected Cursor query(String table, String[] columns, String selection,
572            String[] selectionArgs, String orderBy, CancellationSignal cancellationSignal) {
573        SQLiteDatabase db = getDatabaseHelper().getReadableDatabase();
574        if (ApiHelper.HAS_CANCELLATION_SIGNAL) {
575            return db.query(false, table, columns, selection, selectionArgs, null, null,
576                    orderBy, null, cancellationSignal);
577        } else {
578            return db.query(table, columns, selection, selectionArgs, null, null, orderBy);
579        }
580    }
581}
582