MediaProvider.java revision a82930532f35f34da696dd00f1f511fcdbb56c8a
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.media;
18
19import static android.Manifest.permission.ACCESS_CACHE_FILESYSTEM;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.os.ParcelFileDescriptor.MODE_READ_ONLY;
23import static android.os.ParcelFileDescriptor.MODE_WRITE_ONLY;
24
25import android.app.SearchManager;
26import android.content.BroadcastReceiver;
27import android.content.ComponentName;
28import android.content.ContentProvider;
29import android.content.ContentProviderOperation;
30import android.content.ContentProviderResult;
31import android.content.ContentResolver;
32import android.content.ContentUris;
33import android.content.ContentValues;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.OperationApplicationException;
38import android.content.ServiceConnection;
39import android.content.SharedPreferences;
40import android.content.UriMatcher;
41import android.content.pm.PackageManager.NameNotFoundException;
42import android.content.res.Resources;
43import android.database.Cursor;
44import android.database.DatabaseUtils;
45import android.database.MatrixCursor;
46import android.database.sqlite.SQLiteDatabase;
47import android.database.sqlite.SQLiteOpenHelper;
48import android.database.sqlite.SQLiteQueryBuilder;
49import android.graphics.Bitmap;
50import android.graphics.BitmapFactory;
51import android.media.MediaFile;
52import android.media.MediaScanner;
53import android.media.MediaScannerConnection;
54import android.media.MediaScannerConnection.MediaScannerConnectionClient;
55import android.media.MiniThumbFile;
56import android.mtp.MtpConstants;
57import android.mtp.MtpStorage;
58import android.net.Uri;
59import android.os.Binder;
60import android.os.Bundle;
61import android.os.Environment;
62import android.os.FileUtils;
63import android.os.Handler;
64import android.os.HandlerThread;
65import android.os.Message;
66import android.os.ParcelFileDescriptor;
67import android.os.Process;
68import android.os.RemoteException;
69import android.os.SystemClock;
70import android.os.storage.StorageManager;
71import android.os.storage.StorageVolume;
72import android.preference.PreferenceManager;
73import android.provider.BaseColumns;
74import android.provider.MediaStore;
75import android.provider.MediaStore.Audio;
76import android.provider.MediaStore.Audio.Playlists;
77import android.provider.MediaStore.Files;
78import android.provider.MediaStore.Files.FileColumns;
79import android.provider.MediaStore.Images;
80import android.provider.MediaStore.Images.ImageColumns;
81import android.provider.MediaStore.MediaColumns;
82import android.provider.MediaStore.Video;
83import android.text.TextUtils;
84import android.text.format.DateUtils;
85import android.util.Log;
86
87import java.io.File;
88import java.io.FileDescriptor;
89import java.io.FileInputStream;
90import java.io.FileNotFoundException;
91import java.io.IOException;
92import java.io.OutputStream;
93import java.io.PrintWriter;
94import java.util.ArrayList;
95import java.util.Collection;
96import java.util.HashMap;
97import java.util.HashSet;
98import java.util.Iterator;
99import java.util.List;
100import java.util.Locale;
101import java.util.PriorityQueue;
102import java.util.Stack;
103
104import libcore.io.ErrnoException;
105import libcore.io.IoUtils;
106import libcore.io.Libcore;
107
108/**
109 * Media content provider. See {@link android.provider.MediaStore} for details.
110 * Separate databases are kept for each external storage card we see (using the
111 * card's ID as an index).  The content visible at content://media/external/...
112 * changes with the card.
113 */
114public class MediaProvider extends ContentProvider {
115    private static final Uri MEDIA_URI = Uri.parse("content://media");
116    private static final Uri ALBUMART_URI = Uri.parse("content://media/external/audio/albumart");
117    private static final int ALBUM_THUMB = 1;
118    private static final int IMAGE_THUMB = 2;
119
120    private static final HashMap<String, String> sArtistAlbumsMap = new HashMap<String, String>();
121    private static final HashMap<String, String> sFolderArtMap = new HashMap<String, String>();
122
123    /** Resolved canonical path to external storage. */
124    private static final String sExternalPath;
125    /** Resolved canonical path to cache storage. */
126    private static final String sCachePath;
127
128    static {
129        try {
130            sExternalPath = Environment.getExternalStorageDirectory().getCanonicalPath();
131            sCachePath = Environment.getDownloadCacheDirectory().getCanonicalPath();
132        } catch (IOException e) {
133            throw new RuntimeException("Unable to resolve canonical paths", e);
134        }
135    }
136
137    // In memory cache of path<->id mappings, to speed up inserts during media scan
138    HashMap<String, Long> mDirectoryCache = new HashMap<String, Long>();
139
140    // A HashSet of paths that are pending creation of album art thumbnails.
141    private HashSet mPendingThumbs = new HashSet();
142
143    // A Stack of outstanding thumbnail requests.
144    private Stack mThumbRequestStack = new Stack();
145
146    // The lock of mMediaThumbQueue protects both mMediaThumbQueue and mCurrentThumbRequest.
147    private MediaThumbRequest mCurrentThumbRequest = null;
148    private PriorityQueue<MediaThumbRequest> mMediaThumbQueue =
149            new PriorityQueue<MediaThumbRequest>(MediaThumbRequest.PRIORITY_NORMAL,
150            MediaThumbRequest.getComparator());
151
152    private boolean mCaseInsensitivePaths;
153    private static String[] mExternalStoragePaths;
154
155    // For compatibility with the approximately 0 apps that used mediaprovider search in
156    // releases 1.0, 1.1 or 1.5
157    private String[] mSearchColsLegacy = new String[] {
158            android.provider.BaseColumns._ID,
159            MediaStore.Audio.Media.MIME_TYPE,
160            "(CASE WHEN grouporder=1 THEN " + R.drawable.ic_search_category_music_artist +
161            " ELSE CASE WHEN grouporder=2 THEN " + R.drawable.ic_search_category_music_album +
162            " ELSE " + R.drawable.ic_search_category_music_song + " END END" +
163            ") AS " + SearchManager.SUGGEST_COLUMN_ICON_1,
164            "0 AS " + SearchManager.SUGGEST_COLUMN_ICON_2,
165            "text1 AS " + SearchManager.SUGGEST_COLUMN_TEXT_1,
166            "text1 AS " + SearchManager.SUGGEST_COLUMN_QUERY,
167            "CASE when grouporder=1 THEN data1 ELSE artist END AS data1",
168            "CASE when grouporder=1 THEN data2 ELSE " +
169                "CASE WHEN grouporder=2 THEN NULL ELSE album END END AS data2",
170            "match as ar",
171            SearchManager.SUGGEST_COLUMN_INTENT_DATA,
172            "grouporder",
173            "NULL AS itemorder" // We should be sorting by the artist/album/title keys, but that
174                                // column is not available here, and the list is already sorted.
175    };
176    private String[] mSearchColsFancy = new String[] {
177            android.provider.BaseColumns._ID,
178            MediaStore.Audio.Media.MIME_TYPE,
179            MediaStore.Audio.Artists.ARTIST,
180            MediaStore.Audio.Albums.ALBUM,
181            MediaStore.Audio.Media.TITLE,
182            "data1",
183            "data2",
184    };
185    // If this array gets changed, please update the constant below to point to the correct item.
186    private String[] mSearchColsBasic = new String[] {
187            android.provider.BaseColumns._ID,
188            MediaStore.Audio.Media.MIME_TYPE,
189            "(CASE WHEN grouporder=1 THEN " + R.drawable.ic_search_category_music_artist +
190            " ELSE CASE WHEN grouporder=2 THEN " + R.drawable.ic_search_category_music_album +
191            " ELSE " + R.drawable.ic_search_category_music_song + " END END" +
192            ") AS " + SearchManager.SUGGEST_COLUMN_ICON_1,
193            "text1 AS " + SearchManager.SUGGEST_COLUMN_TEXT_1,
194            "text1 AS " + SearchManager.SUGGEST_COLUMN_QUERY,
195            "(CASE WHEN grouporder=1 THEN '%1'" +  // %1 gets replaced with localized string.
196            " ELSE CASE WHEN grouporder=3 THEN artist || ' - ' || album" +
197            " ELSE CASE WHEN text2!='" + MediaStore.UNKNOWN_STRING + "' THEN text2" +
198            " ELSE NULL END END END) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2,
199            SearchManager.SUGGEST_COLUMN_INTENT_DATA
200    };
201    // Position of the TEXT_2 item in the above array.
202    private final int SEARCH_COLUMN_BASIC_TEXT2 = 5;
203
204    private static final String[] sMediaTableColumns = new String[] {
205            FileColumns._ID,
206            FileColumns.MEDIA_TYPE,
207    };
208
209    private static final String[] sIdOnlyColumn = new String[] {
210        FileColumns._ID
211    };
212
213    private static final String[] sDataOnlyColumn = new String[] {
214        FileColumns.DATA
215    };
216
217    private static final String[] sMediaTypeDataId = new String[] {
218        FileColumns.MEDIA_TYPE,
219        FileColumns.DATA,
220        FileColumns._ID
221    };
222
223    private static final String[] sPlaylistIdPlayOrder = new String[] {
224        Playlists.Members.PLAYLIST_ID,
225        Playlists.Members.PLAY_ORDER
226    };
227
228    private Uri mAlbumArtBaseUri = Uri.parse("content://media/external/audio/albumart");
229
230    private BroadcastReceiver mUnmountReceiver = new BroadcastReceiver() {
231        @Override
232        public void onReceive(Context context, Intent intent) {
233            if (intent.getAction().equals(Intent.ACTION_MEDIA_EJECT)) {
234                StorageVolume storage = (StorageVolume)intent.getParcelableExtra(
235                        StorageVolume.EXTRA_STORAGE_VOLUME);
236                // If primary external storage is ejected, then remove the external volume
237                // notify all cursors backed by data on that volume.
238                if (storage.getPath().equals(mExternalStoragePaths[0])) {
239                    detachVolume(Uri.parse("content://media/external"));
240                    sFolderArtMap.clear();
241                    MiniThumbFile.reset();
242                } else {
243                    // If secondary external storage is ejected, then we delete all database
244                    // entries for that storage from the files table.
245                    synchronized (mDatabases) {
246                        DatabaseHelper database = mDatabases.get(EXTERNAL_VOLUME);
247                        Uri uri = Uri.parse("file://" + storage.getPath());
248                        if (database != null) {
249                            try {
250                                // Send media scanner started and stopped broadcasts for apps that rely
251                                // on these Intents for coarse grained media database notifications.
252                                context.sendBroadcast(
253                                        new Intent(Intent.ACTION_MEDIA_SCANNER_STARTED, uri));
254
255                                // don't send objectRemoved events - MTP be sending StorageRemoved anyway
256                                mDisableMtpObjectCallbacks = true;
257                                Log.d(TAG, "deleting all entries for storage " + storage);
258                                SQLiteDatabase db = database.getWritableDatabase();
259                                // First clear the file path to disable the _DELETE_FILE database hook.
260                                // We do this to avoid deleting files if the volume is remounted while
261                                // we are still processing the unmount event.
262                                ContentValues values = new ContentValues();
263                                values.put(Files.FileColumns.DATA, "");
264                                String where = FileColumns.STORAGE_ID + "=?";
265                                String[] whereArgs = new String[] { Integer.toString(storage.getStorageId()) };
266                                database.mNumUpdates++;
267                                db.update("files", values, where, whereArgs);
268                                // now delete the records
269                                database.mNumDeletes++;
270                                int numpurged = db.delete("files", where, whereArgs);
271                                logToDb(db, "removed " + numpurged +
272                                        " rows for ejected filesystem " + storage.getPath());
273                                // notify on media Uris as well as the files Uri
274                                context.getContentResolver().notifyChange(
275                                        Audio.Media.getContentUri(EXTERNAL_VOLUME), null);
276                                context.getContentResolver().notifyChange(
277                                        Images.Media.getContentUri(EXTERNAL_VOLUME), null);
278                                context.getContentResolver().notifyChange(
279                                        Video.Media.getContentUri(EXTERNAL_VOLUME), null);
280                                context.getContentResolver().notifyChange(
281                                        Files.getContentUri(EXTERNAL_VOLUME), null);
282                            } catch (Exception e) {
283                                Log.e(TAG, "exception deleting storage entries", e);
284                            } finally {
285                                context.sendBroadcast(
286                                        new Intent(Intent.ACTION_MEDIA_SCANNER_FINISHED, uri));
287                                mDisableMtpObjectCallbacks = false;
288                            }
289                        }
290                    }
291                }
292            }
293        }
294    };
295
296    // set to disable sending events when the operation originates from MTP
297    private boolean mDisableMtpObjectCallbacks;
298
299    private final SQLiteDatabase.CustomFunction mObjectRemovedCallback =
300                new SQLiteDatabase.CustomFunction() {
301        public void callback(String[] args) {
302            // We could remove only the deleted entry from the cache, but that
303            // requires the path, which we don't have here, so instead we just
304            // clear the entire cache.
305            // TODO: include the path in the callback and only remove the affected
306            // entry from the cache
307            mDirectoryCache.clear();
308            // do nothing if the operation originated from MTP
309            if (mDisableMtpObjectCallbacks) return;
310
311            Log.d(TAG, "object removed " + args[0]);
312            IMtpService mtpService = mMtpService;
313            if (mtpService != null) {
314                try {
315                    sendObjectRemoved(Integer.parseInt(args[0]));
316                } catch (NumberFormatException e) {
317                    Log.e(TAG, "NumberFormatException in mObjectRemovedCallback", e);
318                }
319            }
320        }
321    };
322
323    /**
324     * Wrapper class for a specific database (associated with one particular
325     * external card, or with internal storage).  Can open the actual database
326     * on demand, create and upgrade the schema, etc.
327     */
328    static final class DatabaseHelper extends SQLiteOpenHelper {
329        final Context mContext;
330        final String mName;
331        final boolean mInternal;  // True if this is the internal database
332        final boolean mEarlyUpgrade;
333        final SQLiteDatabase.CustomFunction mObjectRemovedCallback;
334        boolean mUpgradeAttempted; // Used for upgrade error handling
335        int mNumQueries;
336        int mNumUpdates;
337        int mNumInserts;
338        int mNumDeletes;
339        long mScanStartTime;
340        long mScanStopTime;
341
342        // In memory caches of artist and album data.
343        HashMap<String, Long> mArtistCache = new HashMap<String, Long>();
344        HashMap<String, Long> mAlbumCache = new HashMap<String, Long>();
345
346        public DatabaseHelper(Context context, String name, boolean internal,
347                boolean earlyUpgrade,
348                SQLiteDatabase.CustomFunction objectRemovedCallback) {
349            super(context, name, null, getDatabaseVersion(context));
350            mContext = context;
351            mName = name;
352            mInternal = internal;
353            mEarlyUpgrade = earlyUpgrade;
354            mObjectRemovedCallback = objectRemovedCallback;
355            setWriteAheadLoggingEnabled(true);
356        }
357
358        /**
359         * Creates database the first time we try to open it.
360         */
361        @Override
362        public void onCreate(final SQLiteDatabase db) {
363            updateDatabase(mContext, db, mInternal, 0, getDatabaseVersion(mContext));
364        }
365
366        /**
367         * Updates the database format when a new content provider is used
368         * with an older database format.
369         */
370        @Override
371        public void onUpgrade(final SQLiteDatabase db, final int oldV, final int newV) {
372            mUpgradeAttempted = true;
373            updateDatabase(mContext, db, mInternal, oldV, newV);
374        }
375
376        @Override
377        public synchronized SQLiteDatabase getWritableDatabase() {
378            SQLiteDatabase result = null;
379            mUpgradeAttempted = false;
380            try {
381                result = super.getWritableDatabase();
382            } catch (Exception e) {
383                if (!mUpgradeAttempted) {
384                    Log.e(TAG, "failed to open database " + mName, e);
385                    return null;
386                }
387            }
388
389            // If we failed to open the database during an upgrade, delete the file and try again.
390            // This will result in the creation of a fresh database, which will be repopulated
391            // when the media scanner runs.
392            if (result == null && mUpgradeAttempted) {
393                mContext.getDatabasePath(mName).delete();
394                result = super.getWritableDatabase();
395            }
396            return result;
397        }
398
399        /**
400         * For devices that have removable storage, we support keeping multiple databases
401         * to allow users to switch between a number of cards.
402         * On such devices, touch this particular database and garbage collect old databases.
403         * An LRU cache system is used to clean up databases for old external
404         * storage volumes.
405         */
406        @Override
407        public void onOpen(SQLiteDatabase db) {
408
409            if (mInternal) return;  // The internal database is kept separately.
410
411            if (mEarlyUpgrade) return; // Doing early upgrade.
412
413            if (mObjectRemovedCallback != null) {
414                db.addCustomFunction("_OBJECT_REMOVED", 1, mObjectRemovedCallback);
415            }
416
417            // the code below is only needed on devices with removable storage
418            if (!Environment.isExternalStorageRemovable()) return;
419
420            // touch the database file to show it is most recently used
421            File file = new File(db.getPath());
422            long now = System.currentTimeMillis();
423            file.setLastModified(now);
424
425            // delete least recently used databases if we are over the limit
426            String[] databases = mContext.databaseList();
427            int count = databases.length;
428            int limit = MAX_EXTERNAL_DATABASES;
429
430            // delete external databases that have not been used in the past two months
431            long twoMonthsAgo = now - OBSOLETE_DATABASE_DB;
432            for (int i = 0; i < databases.length; i++) {
433                File other = mContext.getDatabasePath(databases[i]);
434                if (INTERNAL_DATABASE_NAME.equals(databases[i]) || file.equals(other)) {
435                    databases[i] = null;
436                    count--;
437                    if (file.equals(other)) {
438                        // reduce limit to account for the existence of the database we
439                        // are about to open, which we removed from the list.
440                        limit--;
441                    }
442                } else {
443                    long time = other.lastModified();
444                    if (time < twoMonthsAgo) {
445                        if (LOCAL_LOGV) Log.v(TAG, "Deleting old database " + databases[i]);
446                        mContext.deleteDatabase(databases[i]);
447                        databases[i] = null;
448                        count--;
449                    }
450                }
451            }
452
453            // delete least recently used databases until
454            // we are no longer over the limit
455            while (count > limit) {
456                int lruIndex = -1;
457                long lruTime = 0;
458
459                for (int i = 0; i < databases.length; i++) {
460                    if (databases[i] != null) {
461                        long time = mContext.getDatabasePath(databases[i]).lastModified();
462                        if (lruTime == 0 || time < lruTime) {
463                            lruIndex = i;
464                            lruTime = time;
465                        }
466                    }
467                }
468
469                // delete least recently used database
470                if (lruIndex != -1) {
471                    if (LOCAL_LOGV) Log.v(TAG, "Deleting old database " + databases[lruIndex]);
472                    mContext.deleteDatabase(databases[lruIndex]);
473                    databases[lruIndex] = null;
474                    count--;
475                }
476            }
477        }
478    }
479
480    // synchronize on mMtpServiceConnection when accessing mMtpService
481    private IMtpService mMtpService;
482
483    private final ServiceConnection mMtpServiceConnection = new ServiceConnection() {
484         public void onServiceConnected(ComponentName className, android.os.IBinder service) {
485            synchronized (this) {
486                mMtpService = IMtpService.Stub.asInterface(service);
487            }
488        }
489
490        public void onServiceDisconnected(ComponentName className) {
491            synchronized (this) {
492                mMtpService = null;
493            }
494        }
495    };
496
497    private static final String[] sDefaultFolderNames = {
498        Environment.DIRECTORY_MUSIC,
499        Environment.DIRECTORY_PODCASTS,
500        Environment.DIRECTORY_RINGTONES,
501        Environment.DIRECTORY_ALARMS,
502        Environment.DIRECTORY_NOTIFICATIONS,
503        Environment.DIRECTORY_PICTURES,
504        Environment.DIRECTORY_MOVIES,
505        Environment.DIRECTORY_DOWNLOADS,
506        Environment.DIRECTORY_DCIM,
507    };
508
509    // creates default folders (Music, Downloads, etc)
510    private void createDefaultFolders(DatabaseHelper helper, SQLiteDatabase db) {
511        // Use a SharedPreference to ensure we only do this once.
512        // We don't want to annoy the user by recreating the directories
513        // after she has deleted them.
514        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
515        if (prefs.getInt("created_default_folders", 0) == 0) {
516            for (String folderName : sDefaultFolderNames) {
517                File file = Environment.getExternalStoragePublicDirectory(folderName);
518                if (!file.exists()) {
519                    file.mkdirs();
520                    insertDirectory(helper, db, file.getAbsolutePath());
521                }
522            }
523
524            SharedPreferences.Editor e = prefs.edit();
525            e.clear();
526            e.putInt("created_default_folders", 1);
527            e.commit();
528        }
529    }
530
531    public static int getDatabaseVersion(Context context) {
532        try {
533            return context.getPackageManager().getPackageInfo(
534                    context.getPackageName(), 0).versionCode;
535        } catch (NameNotFoundException e) {
536            throw new RuntimeException("couldn't get version code for " + context);
537        }
538    }
539
540    @Override
541    public boolean onCreate() {
542        final Context context = getContext();
543
544        sArtistAlbumsMap.put(MediaStore.Audio.Albums._ID, "audio.album_id AS " +
545                MediaStore.Audio.Albums._ID);
546        sArtistAlbumsMap.put(MediaStore.Audio.Albums.ALBUM, "album");
547        sArtistAlbumsMap.put(MediaStore.Audio.Albums.ALBUM_KEY, "album_key");
548        sArtistAlbumsMap.put(MediaStore.Audio.Albums.FIRST_YEAR, "MIN(year) AS " +
549                MediaStore.Audio.Albums.FIRST_YEAR);
550        sArtistAlbumsMap.put(MediaStore.Audio.Albums.LAST_YEAR, "MAX(year) AS " +
551                MediaStore.Audio.Albums.LAST_YEAR);
552        sArtistAlbumsMap.put(MediaStore.Audio.Media.ARTIST, "artist");
553        sArtistAlbumsMap.put(MediaStore.Audio.Media.ARTIST_ID, "artist");
554        sArtistAlbumsMap.put(MediaStore.Audio.Media.ARTIST_KEY, "artist_key");
555        sArtistAlbumsMap.put(MediaStore.Audio.Albums.NUMBER_OF_SONGS, "count(*) AS " +
556                MediaStore.Audio.Albums.NUMBER_OF_SONGS);
557        sArtistAlbumsMap.put(MediaStore.Audio.Albums.ALBUM_ART, "album_art._data AS " +
558                MediaStore.Audio.Albums.ALBUM_ART);
559
560        mSearchColsBasic[SEARCH_COLUMN_BASIC_TEXT2] =
561                mSearchColsBasic[SEARCH_COLUMN_BASIC_TEXT2].replaceAll(
562                        "%1", context.getString(R.string.artist_label));
563        mDatabases = new HashMap<String, DatabaseHelper>();
564        attachVolume(INTERNAL_VOLUME);
565
566        IntentFilter iFilter = new IntentFilter(Intent.ACTION_MEDIA_EJECT);
567        iFilter.addDataScheme("file");
568        context.registerReceiver(mUnmountReceiver, iFilter);
569
570        StorageManager storageManager =
571                (StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
572        mExternalStoragePaths = storageManager.getVolumePaths();
573
574        // open external database if external storage is mounted
575        String state = Environment.getExternalStorageState();
576        if (Environment.MEDIA_MOUNTED.equals(state) ||
577                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
578            attachVolume(EXTERNAL_VOLUME);
579        }
580
581        HandlerThread ht = new HandlerThread("thumbs thread", Process.THREAD_PRIORITY_BACKGROUND);
582        ht.start();
583        mThumbHandler = new Handler(ht.getLooper()) {
584            @Override
585            public void handleMessage(Message msg) {
586                if (msg.what == IMAGE_THUMB) {
587                    synchronized (mMediaThumbQueue) {
588                        mCurrentThumbRequest = mMediaThumbQueue.poll();
589                    }
590                    if (mCurrentThumbRequest == null) {
591                        Log.w(TAG, "Have message but no request?");
592                    } else {
593                        try {
594                            File origFile = new File(mCurrentThumbRequest.mPath);
595                            if (origFile.exists() && origFile.length() > 0) {
596                                mCurrentThumbRequest.execute();
597                            } else {
598                                // original file hasn't been stored yet
599                                synchronized (mMediaThumbQueue) {
600                                    Log.w(TAG, "original file hasn't been stored yet: " + mCurrentThumbRequest.mPath);
601                                }
602                            }
603                        } catch (IOException ex) {
604                            Log.w(TAG, ex);
605                        } catch (UnsupportedOperationException ex) {
606                            // This could happen if we unplug the sd card during insert/update/delete
607                            // See getDatabaseForUri.
608                            Log.w(TAG, ex);
609                        } catch (OutOfMemoryError err) {
610                            /*
611                             * Note: Catching Errors is in most cases considered
612                             * bad practice. However, in this case it is
613                             * motivated by the fact that corrupt or very large
614                             * images may cause a huge allocation to be
615                             * requested and denied. The bitmap handling API in
616                             * Android offers no other way to guard against
617                             * these problems than by catching OutOfMemoryError.
618                             */
619                            Log.w(TAG, err);
620                        } finally {
621                            synchronized (mCurrentThumbRequest) {
622                                mCurrentThumbRequest.mState = MediaThumbRequest.State.DONE;
623                                mCurrentThumbRequest.notifyAll();
624                            }
625                        }
626                    }
627                } else if (msg.what == ALBUM_THUMB) {
628                    ThumbData d;
629                    synchronized (mThumbRequestStack) {
630                        d = (ThumbData)mThumbRequestStack.pop();
631                    }
632
633                    makeThumbInternal(d);
634                    synchronized (mPendingThumbs) {
635                        mPendingThumbs.remove(d.path);
636                    }
637                }
638            }
639        };
640
641        return true;
642    }
643
644    private static final String TABLE_FILES = "files";
645    private static final String TABLE_ALBUM_ART = "album_art";
646    private static final String TABLE_THUMBNAILS = "thumbnails";
647    private static final String TABLE_VIDEO_THUMBNAILS = "videothumbnails";
648
649    private static final String IMAGE_COLUMNS =
650                        "_data,_size,_display_name,mime_type,title,date_added," +
651                        "date_modified,description,picasa_id,isprivate,latitude,longitude," +
652                        "datetaken,orientation,mini_thumb_magic,bucket_id,bucket_display_name," +
653                        "width,height";
654
655    private static final String IMAGE_COLUMNSv407 =
656                        "_data,_size,_display_name,mime_type,title,date_added," +
657                        "date_modified,description,picasa_id,isprivate,latitude,longitude," +
658                        "datetaken,orientation,mini_thumb_magic,bucket_id,bucket_display_name";
659
660    private static final String AUDIO_COLUMNSv99 =
661                        "_data,_display_name,_size,mime_type,date_added," +
662                        "date_modified,title,title_key,duration,artist_id,composer,album_id," +
663                        "track,year,is_ringtone,is_music,is_alarm,is_notification,is_podcast," +
664                        "bookmark";
665
666    private static final String AUDIO_COLUMNSv100 =
667                        "_data,_display_name,_size,mime_type,date_added," +
668                        "date_modified,title,title_key,duration,artist_id,composer,album_id," +
669                        "track,year,is_ringtone,is_music,is_alarm,is_notification,is_podcast," +
670                        "bookmark,album_artist";
671
672    private static final String AUDIO_COLUMNSv405 =
673                        "_data,_display_name,_size,mime_type,date_added,is_drm," +
674                        "date_modified,title,title_key,duration,artist_id,composer,album_id," +
675                        "track,year,is_ringtone,is_music,is_alarm,is_notification,is_podcast," +
676                        "bookmark,album_artist";
677
678    private static final String VIDEO_COLUMNS =
679                        "_data,_display_name,_size,mime_type,date_added,date_modified," +
680                        "title,duration,artist,album,resolution,description,isprivate,tags," +
681                        "category,language,mini_thumb_data,latitude,longitude,datetaken," +
682                        "mini_thumb_magic,bucket_id,bucket_display_name,bookmark,width," +
683                        "height";
684
685    private static final String VIDEO_COLUMNSv407 =
686                        "_data,_display_name,_size,mime_type,date_added,date_modified," +
687                        "title,duration,artist,album,resolution,description,isprivate,tags," +
688                        "category,language,mini_thumb_data,latitude,longitude,datetaken," +
689                        "mini_thumb_magic,bucket_id,bucket_display_name, bookmark";
690
691    private static final String PLAYLIST_COLUMNS = "_data,name,date_added,date_modified";
692
693    /**
694     * This method takes care of updating all the tables in the database to the
695     * current version, creating them if necessary.
696     * This method can only update databases at schema 63 or higher, which was
697     * created August 1, 2008. Older database will be cleared and recreated.
698     * @param db Database
699     * @param internal True if this is the internal media database
700     */
701    private static void updateDatabase(Context context, SQLiteDatabase db, boolean internal,
702            int fromVersion, int toVersion) {
703
704        // sanity checks
705        int dbversion = getDatabaseVersion(context);
706        if (toVersion != dbversion) {
707            Log.e(TAG, "Illegal update request. Got " + toVersion + ", expected " + dbversion);
708            throw new IllegalArgumentException();
709        } else if (fromVersion > toVersion) {
710            Log.e(TAG, "Illegal update request: can't downgrade from " + fromVersion +
711                    " to " + toVersion + ". Did you forget to wipe data?");
712            throw new IllegalArgumentException();
713        }
714        long startTime = SystemClock.currentTimeMicro();
715
716        // Revisions 84-86 were a failed attempt at supporting the "album artist" id3 tag.
717        // We can't downgrade from those revisions, so start over.
718        // (the initial change to do this was wrong, so now we actually need to start over
719        // if the database version is 84-89)
720        // Post-gingerbread, revisions 91-94 were broken in a way that is not easy to repair.
721        // However version 91 was reused in a divergent development path for gingerbread,
722        // so we need to support upgrades from 91.
723        // Therefore we will only force a reset for versions 92 - 94.
724        if (fromVersion < 63 || (fromVersion >= 84 && fromVersion <= 89) ||
725                    (fromVersion >= 92 && fromVersion <= 94)) {
726            // Drop everything and start over.
727            Log.i(TAG, "Upgrading media database from version " +
728                    fromVersion + " to " + toVersion + ", which will destroy all old data");
729            fromVersion = 63;
730            db.execSQL("DROP TABLE IF EXISTS images");
731            db.execSQL("DROP TRIGGER IF EXISTS images_cleanup");
732            db.execSQL("DROP TABLE IF EXISTS thumbnails");
733            db.execSQL("DROP TRIGGER IF EXISTS thumbnails_cleanup");
734            db.execSQL("DROP TABLE IF EXISTS audio_meta");
735            db.execSQL("DROP TABLE IF EXISTS artists");
736            db.execSQL("DROP TABLE IF EXISTS albums");
737            db.execSQL("DROP TABLE IF EXISTS album_art");
738            db.execSQL("DROP VIEW IF EXISTS artist_info");
739            db.execSQL("DROP VIEW IF EXISTS album_info");
740            db.execSQL("DROP VIEW IF EXISTS artists_albums_map");
741            db.execSQL("DROP TRIGGER IF EXISTS audio_meta_cleanup");
742            db.execSQL("DROP TABLE IF EXISTS audio_genres");
743            db.execSQL("DROP TABLE IF EXISTS audio_genres_map");
744            db.execSQL("DROP TRIGGER IF EXISTS audio_genres_cleanup");
745            db.execSQL("DROP TABLE IF EXISTS audio_playlists");
746            db.execSQL("DROP TABLE IF EXISTS audio_playlists_map");
747            db.execSQL("DROP TRIGGER IF EXISTS audio_playlists_cleanup");
748            db.execSQL("DROP TRIGGER IF EXISTS albumart_cleanup1");
749            db.execSQL("DROP TRIGGER IF EXISTS albumart_cleanup2");
750            db.execSQL("DROP TABLE IF EXISTS video");
751            db.execSQL("DROP TRIGGER IF EXISTS video_cleanup");
752            db.execSQL("DROP TABLE IF EXISTS objects");
753            db.execSQL("DROP TRIGGER IF EXISTS images_objects_cleanup");
754            db.execSQL("DROP TRIGGER IF EXISTS audio_objects_cleanup");
755            db.execSQL("DROP TRIGGER IF EXISTS video_objects_cleanup");
756            db.execSQL("DROP TRIGGER IF EXISTS playlists_objects_cleanup");
757
758            db.execSQL("CREATE TABLE IF NOT EXISTS images (" +
759                    "_id INTEGER PRIMARY KEY," +
760                    "_data TEXT," +
761                    "_size INTEGER," +
762                    "_display_name TEXT," +
763                    "mime_type TEXT," +
764                    "title TEXT," +
765                    "date_added INTEGER," +
766                    "date_modified INTEGER," +
767                    "description TEXT," +
768                    "picasa_id TEXT," +
769                    "isprivate INTEGER," +
770                    "latitude DOUBLE," +
771                    "longitude DOUBLE," +
772                    "datetaken INTEGER," +
773                    "orientation INTEGER," +
774                    "mini_thumb_magic INTEGER," +
775                    "bucket_id TEXT," +
776                    "bucket_display_name TEXT" +
777                   ");");
778
779            db.execSQL("CREATE INDEX IF NOT EXISTS mini_thumb_magic_index on images(mini_thumb_magic);");
780
781            db.execSQL("CREATE TRIGGER IF NOT EXISTS images_cleanup DELETE ON images " +
782                    "BEGIN " +
783                        "DELETE FROM thumbnails WHERE image_id = old._id;" +
784                        "SELECT _DELETE_FILE(old._data);" +
785                    "END");
786
787            // create image thumbnail table
788            db.execSQL("CREATE TABLE IF NOT EXISTS thumbnails (" +
789                       "_id INTEGER PRIMARY KEY," +
790                       "_data TEXT," +
791                       "image_id INTEGER," +
792                       "kind INTEGER," +
793                       "width INTEGER," +
794                       "height INTEGER" +
795                       ");");
796
797            db.execSQL("CREATE INDEX IF NOT EXISTS image_id_index on thumbnails(image_id);");
798
799            db.execSQL("CREATE TRIGGER IF NOT EXISTS thumbnails_cleanup DELETE ON thumbnails " +
800                    "BEGIN " +
801                        "SELECT _DELETE_FILE(old._data);" +
802                    "END");
803
804            // Contains meta data about audio files
805            db.execSQL("CREATE TABLE IF NOT EXISTS audio_meta (" +
806                       "_id INTEGER PRIMARY KEY," +
807                       "_data TEXT UNIQUE NOT NULL," +
808                       "_display_name TEXT," +
809                       "_size INTEGER," +
810                       "mime_type TEXT," +
811                       "date_added INTEGER," +
812                       "date_modified INTEGER," +
813                       "title TEXT NOT NULL," +
814                       "title_key TEXT NOT NULL," +
815                       "duration INTEGER," +
816                       "artist_id INTEGER," +
817                       "composer TEXT," +
818                       "album_id INTEGER," +
819                       "track INTEGER," +    // track is an integer to allow proper sorting
820                       "year INTEGER CHECK(year!=0)," +
821                       "is_ringtone INTEGER," +
822                       "is_music INTEGER," +
823                       "is_alarm INTEGER," +
824                       "is_notification INTEGER" +
825                       ");");
826
827            // Contains a sort/group "key" and the preferred display name for artists
828            db.execSQL("CREATE TABLE IF NOT EXISTS artists (" +
829                        "artist_id INTEGER PRIMARY KEY," +
830                        "artist_key TEXT NOT NULL UNIQUE," +
831                        "artist TEXT NOT NULL" +
832                       ");");
833
834            // Contains a sort/group "key" and the preferred display name for albums
835            db.execSQL("CREATE TABLE IF NOT EXISTS albums (" +
836                        "album_id INTEGER PRIMARY KEY," +
837                        "album_key TEXT NOT NULL UNIQUE," +
838                        "album TEXT NOT NULL" +
839                       ");");
840
841            db.execSQL("CREATE TABLE IF NOT EXISTS album_art (" +
842                    "album_id INTEGER PRIMARY KEY," +
843                    "_data TEXT" +
844                   ");");
845
846            recreateAudioView(db);
847
848
849            // Provides some extra info about artists, like the number of tracks
850            // and albums for this artist
851            db.execSQL("CREATE VIEW IF NOT EXISTS artist_info AS " +
852                        "SELECT artist_id AS _id, artist, artist_key, " +
853                        "COUNT(DISTINCT album) AS number_of_albums, " +
854                        "COUNT(*) AS number_of_tracks FROM audio WHERE is_music=1 "+
855                        "GROUP BY artist_key;");
856
857            // Provides extra info albums, such as the number of tracks
858            db.execSQL("CREATE VIEW IF NOT EXISTS album_info AS " +
859                    "SELECT audio.album_id AS _id, album, album_key, " +
860                    "MIN(year) AS minyear, " +
861                    "MAX(year) AS maxyear, artist, artist_id, artist_key, " +
862                    "count(*) AS " + MediaStore.Audio.Albums.NUMBER_OF_SONGS +
863                    ",album_art._data AS album_art" +
864                    " FROM audio LEFT OUTER JOIN album_art ON audio.album_id=album_art.album_id" +
865                    " WHERE is_music=1 GROUP BY audio.album_id;");
866
867            // For a given artist_id, provides the album_id for albums on
868            // which the artist appears.
869            db.execSQL("CREATE VIEW IF NOT EXISTS artists_albums_map AS " +
870                    "SELECT DISTINCT artist_id, album_id FROM audio_meta;");
871
872            /*
873             * Only external media volumes can handle genres, playlists, etc.
874             */
875            if (!internal) {
876                // Cleans up when an audio file is deleted
877                db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_meta_cleanup DELETE ON audio_meta " +
878                           "BEGIN " +
879                               "DELETE FROM audio_genres_map WHERE audio_id = old._id;" +
880                               "DELETE FROM audio_playlists_map WHERE audio_id = old._id;" +
881                           "END");
882
883                // Contains audio genre definitions
884                db.execSQL("CREATE TABLE IF NOT EXISTS audio_genres (" +
885                           "_id INTEGER PRIMARY KEY," +
886                           "name TEXT NOT NULL" +
887                           ");");
888
889                // Contains mappings between audio genres and audio files
890                db.execSQL("CREATE TABLE IF NOT EXISTS audio_genres_map (" +
891                           "_id INTEGER PRIMARY KEY," +
892                           "audio_id INTEGER NOT NULL," +
893                           "genre_id INTEGER NOT NULL" +
894                           ");");
895
896                // Cleans up when an audio genre is delete
897                db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_genres_cleanup DELETE ON audio_genres " +
898                           "BEGIN " +
899                               "DELETE FROM audio_genres_map WHERE genre_id = old._id;" +
900                           "END");
901
902                // Contains audio playlist definitions
903                db.execSQL("CREATE TABLE IF NOT EXISTS audio_playlists (" +
904                           "_id INTEGER PRIMARY KEY," +
905                           "_data TEXT," +  // _data is path for file based playlists, or null
906                           "name TEXT NOT NULL," +
907                           "date_added INTEGER," +
908                           "date_modified INTEGER" +
909                           ");");
910
911                // Contains mappings between audio playlists and audio files
912                db.execSQL("CREATE TABLE IF NOT EXISTS audio_playlists_map (" +
913                           "_id INTEGER PRIMARY KEY," +
914                           "audio_id INTEGER NOT NULL," +
915                           "playlist_id INTEGER NOT NULL," +
916                           "play_order INTEGER NOT NULL" +
917                           ");");
918
919                // Cleans up when an audio playlist is deleted
920                db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_playlists_cleanup DELETE ON audio_playlists " +
921                           "BEGIN " +
922                               "DELETE FROM audio_playlists_map WHERE playlist_id = old._id;" +
923                               "SELECT _DELETE_FILE(old._data);" +
924                           "END");
925
926                // Cleans up album_art table entry when an album is deleted
927                db.execSQL("CREATE TRIGGER IF NOT EXISTS albumart_cleanup1 DELETE ON albums " +
928                        "BEGIN " +
929                            "DELETE FROM album_art WHERE album_id = old.album_id;" +
930                        "END");
931
932                // Cleans up album_art when an album is deleted
933                db.execSQL("CREATE TRIGGER IF NOT EXISTS albumart_cleanup2 DELETE ON album_art " +
934                        "BEGIN " +
935                            "SELECT _DELETE_FILE(old._data);" +
936                        "END");
937            }
938
939            // Contains meta data about video files
940            db.execSQL("CREATE TABLE IF NOT EXISTS video (" +
941                       "_id INTEGER PRIMARY KEY," +
942                       "_data TEXT NOT NULL," +
943                       "_display_name TEXT," +
944                       "_size INTEGER," +
945                       "mime_type TEXT," +
946                       "date_added INTEGER," +
947                       "date_modified INTEGER," +
948                       "title TEXT," +
949                       "duration INTEGER," +
950                       "artist TEXT," +
951                       "album TEXT," +
952                       "resolution TEXT," +
953                       "description TEXT," +
954                       "isprivate INTEGER," +   // for YouTube videos
955                       "tags TEXT," +           // for YouTube videos
956                       "category TEXT," +       // for YouTube videos
957                       "language TEXT," +       // for YouTube videos
958                       "mini_thumb_data TEXT," +
959                       "latitude DOUBLE," +
960                       "longitude DOUBLE," +
961                       "datetaken INTEGER," +
962                       "mini_thumb_magic INTEGER" +
963                       ");");
964
965            db.execSQL("CREATE TRIGGER IF NOT EXISTS video_cleanup DELETE ON video " +
966                    "BEGIN " +
967                        "SELECT _DELETE_FILE(old._data);" +
968                    "END");
969        }
970
971        // At this point the database is at least at schema version 63 (it was
972        // either created at version 63 by the code above, or was already at
973        // version 63 or later)
974
975        if (fromVersion < 64) {
976            // create the index that updates the database to schema version 64
977            db.execSQL("CREATE INDEX IF NOT EXISTS sort_index on images(datetaken ASC, _id ASC);");
978        }
979
980        /*
981         *  Android 1.0 shipped with database version 64
982         */
983
984        if (fromVersion < 65) {
985            // create the index that updates the database to schema version 65
986            db.execSQL("CREATE INDEX IF NOT EXISTS titlekey_index on audio_meta(title_key);");
987        }
988
989        // In version 66, originally we updateBucketNames(db, "images"),
990        // but we need to do it in version 89 and therefore save the update here.
991
992        if (fromVersion < 67) {
993            // create the indices that update the database to schema version 67
994            db.execSQL("CREATE INDEX IF NOT EXISTS albumkey_index on albums(album_key);");
995            db.execSQL("CREATE INDEX IF NOT EXISTS artistkey_index on artists(artist_key);");
996        }
997
998        if (fromVersion < 68) {
999            // Create bucket_id and bucket_display_name columns for the video table.
1000            db.execSQL("ALTER TABLE video ADD COLUMN bucket_id TEXT;");
1001            db.execSQL("ALTER TABLE video ADD COLUMN bucket_display_name TEXT");
1002
1003            // In version 68, originally we updateBucketNames(db, "video"),
1004            // but we need to do it in version 89 and therefore save the update here.
1005        }
1006
1007        if (fromVersion < 69) {
1008            updateDisplayName(db, "images");
1009        }
1010
1011        if (fromVersion < 70) {
1012            // Create bookmark column for the video table.
1013            db.execSQL("ALTER TABLE video ADD COLUMN bookmark INTEGER;");
1014        }
1015
1016        if (fromVersion < 71) {
1017            // There is no change to the database schema, however a code change
1018            // fixed parsing of metadata for certain files bought from the
1019            // iTunes music store, so we want to rescan files that might need it.
1020            // We do this by clearing the modification date in the database for
1021            // those files, so that the media scanner will see them as updated
1022            // and rescan them.
1023            db.execSQL("UPDATE audio_meta SET date_modified=0 WHERE _id IN (" +
1024                    "SELECT _id FROM audio where mime_type='audio/mp4' AND " +
1025                    "artist='" + MediaStore.UNKNOWN_STRING + "' AND " +
1026                    "album='" + MediaStore.UNKNOWN_STRING + "'" +
1027                    ");");
1028        }
1029
1030        if (fromVersion < 72) {
1031            // Create is_podcast and bookmark columns for the audio table.
1032            db.execSQL("ALTER TABLE audio_meta ADD COLUMN is_podcast INTEGER;");
1033            db.execSQL("UPDATE audio_meta SET is_podcast=1 WHERE _data LIKE '%/podcasts/%';");
1034            db.execSQL("UPDATE audio_meta SET is_music=0 WHERE is_podcast=1" +
1035                    " AND _data NOT LIKE '%/music/%';");
1036            db.execSQL("ALTER TABLE audio_meta ADD COLUMN bookmark INTEGER;");
1037
1038            // New columns added to tables aren't visible in views on those tables
1039            // without opening and closing the database (or using the 'vacuum' command,
1040            // which we can't do here because all this code runs inside a transaction).
1041            // To work around this, we drop and recreate the affected view and trigger.
1042            recreateAudioView(db);
1043        }
1044
1045        /*
1046         *  Android 1.5 shipped with database version 72
1047         */
1048
1049        if (fromVersion < 73) {
1050            // There is no change to the database schema, but we now do case insensitive
1051            // matching of folder names when determining whether something is music, a
1052            // ringtone, podcast, etc, so we might need to reclassify some files.
1053            db.execSQL("UPDATE audio_meta SET is_music=1 WHERE is_music=0 AND " +
1054                    "_data LIKE '%/music/%';");
1055            db.execSQL("UPDATE audio_meta SET is_ringtone=1 WHERE is_ringtone=0 AND " +
1056                    "_data LIKE '%/ringtones/%';");
1057            db.execSQL("UPDATE audio_meta SET is_notification=1 WHERE is_notification=0 AND " +
1058                    "_data LIKE '%/notifications/%';");
1059            db.execSQL("UPDATE audio_meta SET is_alarm=1 WHERE is_alarm=0 AND " +
1060                    "_data LIKE '%/alarms/%';");
1061            db.execSQL("UPDATE audio_meta SET is_podcast=1 WHERE is_podcast=0 AND " +
1062                    "_data LIKE '%/podcasts/%';");
1063        }
1064
1065        if (fromVersion < 74) {
1066            // This view is used instead of the audio view by the union below, to force
1067            // sqlite to use the title_key index. This greatly reduces memory usage
1068            // (no separate copy pass needed for sorting, which could cause errors on
1069            // large datasets) and improves speed (by about 35% on a large dataset)
1070            db.execSQL("CREATE VIEW IF NOT EXISTS searchhelpertitle AS SELECT * FROM audio " +
1071                    "ORDER BY title_key;");
1072
1073            db.execSQL("CREATE VIEW IF NOT EXISTS search AS " +
1074                    "SELECT _id," +
1075                    "'artist' AS mime_type," +
1076                    "artist," +
1077                    "NULL AS album," +
1078                    "NULL AS title," +
1079                    "artist AS text1," +
1080                    "NULL AS text2," +
1081                    "number_of_albums AS data1," +
1082                    "number_of_tracks AS data2," +
1083                    "artist_key AS match," +
1084                    "'content://media/external/audio/artists/'||_id AS suggest_intent_data," +
1085                    "1 AS grouporder " +
1086                    "FROM artist_info WHERE (artist!='" + MediaStore.UNKNOWN_STRING + "') " +
1087                "UNION ALL " +
1088                    "SELECT _id," +
1089                    "'album' AS mime_type," +
1090                    "artist," +
1091                    "album," +
1092                    "NULL AS title," +
1093                    "album AS text1," +
1094                    "artist AS text2," +
1095                    "NULL AS data1," +
1096                    "NULL AS data2," +
1097                    "artist_key||' '||album_key AS match," +
1098                    "'content://media/external/audio/albums/'||_id AS suggest_intent_data," +
1099                    "2 AS grouporder " +
1100                    "FROM album_info WHERE (album!='" + MediaStore.UNKNOWN_STRING + "') " +
1101                "UNION ALL " +
1102                    "SELECT searchhelpertitle._id AS _id," +
1103                    "mime_type," +
1104                    "artist," +
1105                    "album," +
1106                    "title," +
1107                    "title AS text1," +
1108                    "artist AS text2," +
1109                    "NULL AS data1," +
1110                    "NULL AS data2," +
1111                    "artist_key||' '||album_key||' '||title_key AS match," +
1112                    "'content://media/external/audio/media/'||searchhelpertitle._id AS " +
1113                    "suggest_intent_data," +
1114                    "3 AS grouporder " +
1115                    "FROM searchhelpertitle WHERE (title != '') "
1116                    );
1117        }
1118
1119        if (fromVersion < 75) {
1120            // Force a rescan of the audio entries so we can apply the new logic to
1121            // distinguish same-named albums.
1122            db.execSQL("UPDATE audio_meta SET date_modified=0;");
1123            db.execSQL("DELETE FROM albums");
1124        }
1125
1126        if (fromVersion < 76) {
1127            // We now ignore double quotes when building the key, so we have to remove all of them
1128            // from existing keys.
1129            db.execSQL("UPDATE audio_meta SET title_key=" +
1130                    "REPLACE(title_key,x'081D08C29F081D',x'081D') " +
1131                    "WHERE title_key LIKE '%'||x'081D08C29F081D'||'%';");
1132            db.execSQL("UPDATE albums SET album_key=" +
1133                    "REPLACE(album_key,x'081D08C29F081D',x'081D') " +
1134                    "WHERE album_key LIKE '%'||x'081D08C29F081D'||'%';");
1135            db.execSQL("UPDATE artists SET artist_key=" +
1136                    "REPLACE(artist_key,x'081D08C29F081D',x'081D') " +
1137                    "WHERE artist_key LIKE '%'||x'081D08C29F081D'||'%';");
1138        }
1139
1140        /*
1141         *  Android 1.6 shipped with database version 76
1142         */
1143
1144        if (fromVersion < 77) {
1145            // create video thumbnail table
1146            db.execSQL("CREATE TABLE IF NOT EXISTS videothumbnails (" +
1147                    "_id INTEGER PRIMARY KEY," +
1148                    "_data TEXT," +
1149                    "video_id INTEGER," +
1150                    "kind INTEGER," +
1151                    "width INTEGER," +
1152                    "height INTEGER" +
1153                    ");");
1154
1155            db.execSQL("CREATE INDEX IF NOT EXISTS video_id_index on videothumbnails(video_id);");
1156
1157            db.execSQL("CREATE TRIGGER IF NOT EXISTS videothumbnails_cleanup DELETE ON videothumbnails " +
1158                    "BEGIN " +
1159                        "SELECT _DELETE_FILE(old._data);" +
1160                    "END");
1161        }
1162
1163        /*
1164         *  Android 2.0 and 2.0.1 shipped with database version 77
1165         */
1166
1167        if (fromVersion < 78) {
1168            // Force a rescan of the video entries so we can update
1169            // latest changed DATE_TAKEN units (in milliseconds).
1170            db.execSQL("UPDATE video SET date_modified=0;");
1171        }
1172
1173        /*
1174         *  Android 2.1 shipped with database version 78
1175         */
1176
1177        if (fromVersion < 79) {
1178            // move /sdcard/albumthumbs to
1179            // /sdcard/Android/data/com.android.providers.media/albumthumbs,
1180            // and update the database accordingly
1181
1182            String oldthumbspath = mExternalStoragePaths[0] + "/albumthumbs";
1183            String newthumbspath = mExternalStoragePaths[0] + "/" + ALBUM_THUMB_FOLDER;
1184            File thumbsfolder = new File(oldthumbspath);
1185            if (thumbsfolder.exists()) {
1186                // move folder to its new location
1187                File newthumbsfolder = new File(newthumbspath);
1188                newthumbsfolder.getParentFile().mkdirs();
1189                if(thumbsfolder.renameTo(newthumbsfolder)) {
1190                    // update the database
1191                    db.execSQL("UPDATE album_art SET _data=REPLACE(_data, '" +
1192                            oldthumbspath + "','" + newthumbspath + "');");
1193                }
1194            }
1195        }
1196
1197        if (fromVersion < 80) {
1198            // Force rescan of image entries to update DATE_TAKEN as UTC timestamp.
1199            db.execSQL("UPDATE images SET date_modified=0;");
1200        }
1201
1202        if (fromVersion < 81 && !internal) {
1203            // Delete entries starting with /mnt/sdcard. This is for the benefit
1204            // of users running builds between 2.0.1 and 2.1 final only, since
1205            // users updating from 2.0 or earlier will not have such entries.
1206
1207            // First we need to update the _data fields in the affected tables, since
1208            // otherwise deleting the entries will also delete the underlying files
1209            // (via a trigger), and we want to keep them.
1210            db.execSQL("UPDATE audio_playlists SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
1211            db.execSQL("UPDATE images SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
1212            db.execSQL("UPDATE video SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
1213            db.execSQL("UPDATE videothumbnails SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
1214            db.execSQL("UPDATE thumbnails SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
1215            db.execSQL("UPDATE album_art SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
1216            db.execSQL("UPDATE audio_meta SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
1217            // Once the paths have been renamed, we can safely delete the entries
1218            db.execSQL("DELETE FROM audio_playlists WHERE _data IS '////';");
1219            db.execSQL("DELETE FROM images WHERE _data IS '////';");
1220            db.execSQL("DELETE FROM video WHERE _data IS '////';");
1221            db.execSQL("DELETE FROM videothumbnails WHERE _data IS '////';");
1222            db.execSQL("DELETE FROM thumbnails WHERE _data IS '////';");
1223            db.execSQL("DELETE FROM audio_meta WHERE _data  IS '////';");
1224            db.execSQL("DELETE FROM album_art WHERE _data  IS '////';");
1225
1226            // rename existing entries starting with /sdcard to /mnt/sdcard
1227            db.execSQL("UPDATE audio_meta" +
1228                    " SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
1229            db.execSQL("UPDATE audio_playlists" +
1230                    " SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
1231            db.execSQL("UPDATE images" +
1232                    " SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
1233            db.execSQL("UPDATE video" +
1234                    " SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
1235            db.execSQL("UPDATE videothumbnails" +
1236                    " SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
1237            db.execSQL("UPDATE thumbnails" +
1238                    " SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
1239            db.execSQL("UPDATE album_art" +
1240                    " SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
1241
1242            // Delete albums and artists, then clear the modification time on songs, which
1243            // will cause the media scanner to rescan everything, rebuilding the artist and
1244            // album tables along the way, while preserving playlists.
1245            // We need this rescan because ICU also changed, and now generates different
1246            // collation keys
1247            db.execSQL("DELETE from albums");
1248            db.execSQL("DELETE from artists");
1249            db.execSQL("UPDATE audio_meta SET date_modified=0;");
1250        }
1251
1252        if (fromVersion < 82) {
1253            // recreate this view with the correct "group by" specifier
1254            db.execSQL("DROP VIEW IF EXISTS artist_info");
1255            db.execSQL("CREATE VIEW IF NOT EXISTS artist_info AS " +
1256                        "SELECT artist_id AS _id, artist, artist_key, " +
1257                        "COUNT(DISTINCT album_key) AS number_of_albums, " +
1258                        "COUNT(*) AS number_of_tracks FROM audio WHERE is_music=1 "+
1259                        "GROUP BY artist_key;");
1260        }
1261
1262        /* we skipped over version 83, and reverted versions 84, 85 and 86 */
1263
1264        if (fromVersion < 87) {
1265            // The fastscroll thumb needs an index on the strings being displayed,
1266            // otherwise the queries it does to determine the correct position
1267            // becomes really inefficient
1268            db.execSQL("CREATE INDEX IF NOT EXISTS title_idx on audio_meta(title);");
1269            db.execSQL("CREATE INDEX IF NOT EXISTS artist_idx on artists(artist);");
1270            db.execSQL("CREATE INDEX IF NOT EXISTS album_idx on albums(album);");
1271        }
1272
1273        if (fromVersion < 88) {
1274            // Clean up a few more things from versions 84/85/86, and recreate
1275            // the few things worth keeping from those changes.
1276            db.execSQL("DROP TRIGGER IF EXISTS albums_update1;");
1277            db.execSQL("DROP TRIGGER IF EXISTS albums_update2;");
1278            db.execSQL("DROP TRIGGER IF EXISTS albums_update3;");
1279            db.execSQL("DROP TRIGGER IF EXISTS albums_update4;");
1280            db.execSQL("DROP TRIGGER IF EXISTS artist_update1;");
1281            db.execSQL("DROP TRIGGER IF EXISTS artist_update2;");
1282            db.execSQL("DROP TRIGGER IF EXISTS artist_update3;");
1283            db.execSQL("DROP TRIGGER IF EXISTS artist_update4;");
1284            db.execSQL("DROP VIEW IF EXISTS album_artists;");
1285            db.execSQL("CREATE INDEX IF NOT EXISTS album_id_idx on audio_meta(album_id);");
1286            db.execSQL("CREATE INDEX IF NOT EXISTS artist_id_idx on audio_meta(artist_id);");
1287            // For a given artist_id, provides the album_id for albums on
1288            // which the artist appears.
1289            db.execSQL("CREATE VIEW IF NOT EXISTS artists_albums_map AS " +
1290                    "SELECT DISTINCT artist_id, album_id FROM audio_meta;");
1291        }
1292
1293        // In version 89, originally we updateBucketNames(db, "images") and
1294        // updateBucketNames(db, "video"), but in version 101 we now updateBucketNames
1295        //  for all files and therefore can save the update here.
1296
1297        if (fromVersion < 91) {
1298            // Never query by mini_thumb_magic_index
1299            db.execSQL("DROP INDEX IF EXISTS mini_thumb_magic_index");
1300
1301            // sort the items by taken date in each bucket
1302            db.execSQL("CREATE INDEX IF NOT EXISTS image_bucket_index ON images(bucket_id, datetaken)");
1303            db.execSQL("CREATE INDEX IF NOT EXISTS video_bucket_index ON video(bucket_id, datetaken)");
1304        }
1305
1306
1307        // Gingerbread ended up going to version 100, but didn't yet have the "files"
1308        // table, so we need to create that if we're at 100 or lower. This means
1309        // we won't be able to upgrade pre-release Honeycomb.
1310        if (fromVersion <= 100) {
1311            // Remove various stages of work in progress for MTP support
1312            db.execSQL("DROP TABLE IF EXISTS objects");
1313            db.execSQL("DROP TABLE IF EXISTS files");
1314            db.execSQL("DROP TRIGGER IF EXISTS images_objects_cleanup;");
1315            db.execSQL("DROP TRIGGER IF EXISTS audio_objects_cleanup;");
1316            db.execSQL("DROP TRIGGER IF EXISTS video_objects_cleanup;");
1317            db.execSQL("DROP TRIGGER IF EXISTS playlists_objects_cleanup;");
1318            db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_images;");
1319            db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_audio;");
1320            db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_video;");
1321            db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_playlists;");
1322            db.execSQL("DROP TRIGGER IF EXISTS media_cleanup;");
1323
1324            // Create a new table to manage all files in our storage.
1325            // This contains a union of all the columns from the old
1326            // images, audio_meta, videos and audio_playlist tables.
1327            db.execSQL("CREATE TABLE files (" +
1328                        "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
1329                        "_data TEXT," +     // this can be null for playlists
1330                        "_size INTEGER," +
1331                        "format INTEGER," +
1332                        "parent INTEGER," +
1333                        "date_added INTEGER," +
1334                        "date_modified INTEGER," +
1335                        "mime_type TEXT," +
1336                        "title TEXT," +
1337                        "description TEXT," +
1338                        "_display_name TEXT," +
1339
1340                        // for images
1341                        "picasa_id TEXT," +
1342                        "orientation INTEGER," +
1343
1344                        // for images and video
1345                        "latitude DOUBLE," +
1346                        "longitude DOUBLE," +
1347                        "datetaken INTEGER," +
1348                        "mini_thumb_magic INTEGER," +
1349                        "bucket_id TEXT," +
1350                        "bucket_display_name TEXT," +
1351                        "isprivate INTEGER," +
1352
1353                        // for audio
1354                        "title_key TEXT," +
1355                        "artist_id INTEGER," +
1356                        "album_id INTEGER," +
1357                        "composer TEXT," +
1358                        "track INTEGER," +
1359                        "year INTEGER CHECK(year!=0)," +
1360                        "is_ringtone INTEGER," +
1361                        "is_music INTEGER," +
1362                        "is_alarm INTEGER," +
1363                        "is_notification INTEGER," +
1364                        "is_podcast INTEGER," +
1365                        "album_artist TEXT," +
1366
1367                        // for audio and video
1368                        "duration INTEGER," +
1369                        "bookmark INTEGER," +
1370
1371                        // for video
1372                        "artist TEXT," +
1373                        "album TEXT," +
1374                        "resolution TEXT," +
1375                        "tags TEXT," +
1376                        "category TEXT," +
1377                        "language TEXT," +
1378                        "mini_thumb_data TEXT," +
1379
1380                        // for playlists
1381                        "name TEXT," +
1382
1383                        // media_type is used by the views to emulate the old
1384                        // images, audio_meta, videos and audio_playlist tables.
1385                        "media_type INTEGER," +
1386
1387                        // Value of _id from the old media table.
1388                        // Used only for updating other tables during database upgrade.
1389                        "old_id INTEGER" +
1390                       ");");
1391
1392            db.execSQL("CREATE INDEX path_index ON files(_data);");
1393            db.execSQL("CREATE INDEX media_type_index ON files(media_type);");
1394
1395            // Copy all data from our obsolete tables to the new files table
1396
1397            // Copy audio records first, preserving the _id column.
1398            // We do this to maintain compatibility for content Uris for ringtones.
1399            // Unfortunately we cannot do this for images and videos as well.
1400            // We choose to do this for the audio table because the fragility of Uris
1401            // for ringtones are the most common problem we need to avoid.
1402            db.execSQL("INSERT INTO files (_id," + AUDIO_COLUMNSv99 + ",old_id,media_type)" +
1403                    " SELECT _id," + AUDIO_COLUMNSv99 + ",_id," + FileColumns.MEDIA_TYPE_AUDIO +
1404                    " FROM audio_meta;");
1405
1406            db.execSQL("INSERT INTO files (" + IMAGE_COLUMNSv407 + ",old_id,media_type) SELECT "
1407                    + IMAGE_COLUMNSv407 + ",_id," + FileColumns.MEDIA_TYPE_IMAGE + " FROM images;");
1408            db.execSQL("INSERT INTO files (" + VIDEO_COLUMNSv407 + ",old_id,media_type) SELECT "
1409                    + VIDEO_COLUMNSv407 + ",_id," + FileColumns.MEDIA_TYPE_VIDEO + " FROM video;");
1410            if (!internal) {
1411                db.execSQL("INSERT INTO files (" + PLAYLIST_COLUMNS + ",old_id,media_type) SELECT "
1412                        + PLAYLIST_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_PLAYLIST
1413                        + " FROM audio_playlists;");
1414            }
1415
1416            // Delete the old tables
1417            db.execSQL("DROP TABLE IF EXISTS images");
1418            db.execSQL("DROP TABLE IF EXISTS audio_meta");
1419            db.execSQL("DROP TABLE IF EXISTS video");
1420            db.execSQL("DROP TABLE IF EXISTS audio_playlists");
1421
1422            // Create views to replace our old tables
1423            db.execSQL("CREATE VIEW images AS SELECT _id," + IMAGE_COLUMNSv407 +
1424                        " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
1425                        + FileColumns.MEDIA_TYPE_IMAGE + ";");
1426            db.execSQL("CREATE VIEW audio_meta AS SELECT _id," + AUDIO_COLUMNSv100 +
1427                        " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
1428                        + FileColumns.MEDIA_TYPE_AUDIO + ";");
1429            db.execSQL("CREATE VIEW video AS SELECT _id," + VIDEO_COLUMNSv407 +
1430                        " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
1431                        + FileColumns.MEDIA_TYPE_VIDEO + ";");
1432            if (!internal) {
1433                db.execSQL("CREATE VIEW audio_playlists AS SELECT _id," + PLAYLIST_COLUMNS +
1434                        " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
1435                        + FileColumns.MEDIA_TYPE_PLAYLIST + ";");
1436            }
1437
1438            // create temporary index to make the updates go faster
1439            db.execSQL("CREATE INDEX tmp ON files(old_id);");
1440
1441            // update the image_id column in the thumbnails table.
1442            db.execSQL("UPDATE thumbnails SET image_id = (SELECT _id FROM files "
1443                        + "WHERE files.old_id = thumbnails.image_id AND files.media_type = "
1444                        + FileColumns.MEDIA_TYPE_IMAGE + ");");
1445
1446            if (!internal) {
1447                // update audio_id in the audio_genres_map table, and
1448                // audio_playlists_map tables and playlist_id in the audio_playlists_map table
1449                db.execSQL("UPDATE audio_genres_map SET audio_id = (SELECT _id FROM files "
1450                        + "WHERE files.old_id = audio_genres_map.audio_id AND files.media_type = "
1451                        + FileColumns.MEDIA_TYPE_AUDIO + ");");
1452                db.execSQL("UPDATE audio_playlists_map SET audio_id = (SELECT _id FROM files "
1453                        + "WHERE files.old_id = audio_playlists_map.audio_id "
1454                        + "AND files.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + ");");
1455                db.execSQL("UPDATE audio_playlists_map SET playlist_id = (SELECT _id FROM files "
1456                        + "WHERE files.old_id = audio_playlists_map.playlist_id "
1457                        + "AND files.media_type = " + FileColumns.MEDIA_TYPE_PLAYLIST + ");");
1458            }
1459
1460            // update video_id in the videothumbnails table.
1461            db.execSQL("UPDATE videothumbnails SET video_id = (SELECT _id FROM files "
1462                        + "WHERE files.old_id = videothumbnails.video_id AND files.media_type = "
1463                        + FileColumns.MEDIA_TYPE_VIDEO + ");");
1464
1465            // we don't need this index anymore now
1466            db.execSQL("DROP INDEX tmp;");
1467
1468            // update indices to work on the files table
1469            db.execSQL("DROP INDEX IF EXISTS title_idx");
1470            db.execSQL("DROP INDEX IF EXISTS album_id_idx");
1471            db.execSQL("DROP INDEX IF EXISTS image_bucket_index");
1472            db.execSQL("DROP INDEX IF EXISTS video_bucket_index");
1473            db.execSQL("DROP INDEX IF EXISTS sort_index");
1474            db.execSQL("DROP INDEX IF EXISTS titlekey_index");
1475            db.execSQL("DROP INDEX IF EXISTS artist_id_idx");
1476            db.execSQL("CREATE INDEX title_idx ON files(title);");
1477            db.execSQL("CREATE INDEX album_id_idx ON files(album_id);");
1478            db.execSQL("CREATE INDEX bucket_index ON files(bucket_id, datetaken);");
1479            db.execSQL("CREATE INDEX sort_index ON files(datetaken ASC, _id ASC);");
1480            db.execSQL("CREATE INDEX titlekey_index ON files(title_key);");
1481            db.execSQL("CREATE INDEX artist_id_idx ON files(artist_id);");
1482
1483            // Recreate triggers for our obsolete tables on the new files table
1484            db.execSQL("DROP TRIGGER IF EXISTS images_cleanup");
1485            db.execSQL("DROP TRIGGER IF EXISTS audio_meta_cleanup");
1486            db.execSQL("DROP TRIGGER IF EXISTS video_cleanup");
1487            db.execSQL("DROP TRIGGER IF EXISTS audio_playlists_cleanup");
1488            db.execSQL("DROP TRIGGER IF EXISTS audio_delete");
1489
1490            db.execSQL("CREATE TRIGGER IF NOT EXISTS images_cleanup DELETE ON files " +
1491                    "WHEN old.media_type = " + FileColumns.MEDIA_TYPE_IMAGE + " " +
1492                    "BEGIN " +
1493                        "DELETE FROM thumbnails WHERE image_id = old._id;" +
1494                        "SELECT _DELETE_FILE(old._data);" +
1495                    "END");
1496
1497            db.execSQL("CREATE TRIGGER IF NOT EXISTS video_cleanup DELETE ON files " +
1498                    "WHEN old.media_type = " + FileColumns.MEDIA_TYPE_VIDEO + " " +
1499                    "BEGIN " +
1500                        "SELECT _DELETE_FILE(old._data);" +
1501                    "END");
1502
1503            if (!internal) {
1504                db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_meta_cleanup DELETE ON files " +
1505                       "WHEN old.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + " " +
1506                       "BEGIN " +
1507                           "DELETE FROM audio_genres_map WHERE audio_id = old._id;" +
1508                           "DELETE FROM audio_playlists_map WHERE audio_id = old._id;" +
1509                       "END");
1510
1511                db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_playlists_cleanup DELETE ON files " +
1512                       "WHEN old.media_type = " + FileColumns.MEDIA_TYPE_PLAYLIST + " " +
1513                       "BEGIN " +
1514                           "DELETE FROM audio_playlists_map WHERE playlist_id = old._id;" +
1515                           "SELECT _DELETE_FILE(old._data);" +
1516                       "END");
1517
1518                db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_delete INSTEAD OF DELETE ON audio " +
1519                        "BEGIN " +
1520                            "DELETE from files where _id=old._id;" +
1521                            "DELETE from audio_playlists_map where audio_id=old._id;" +
1522                            "DELETE from audio_genres_map where audio_id=old._id;" +
1523                        "END");
1524            }
1525        }
1526
1527        if (fromVersion < 301) {
1528            db.execSQL("DROP INDEX IF EXISTS bucket_index");
1529            db.execSQL("CREATE INDEX bucket_index on files(bucket_id, media_type, datetaken, _id)");
1530            db.execSQL("CREATE INDEX bucket_name on files(bucket_id, media_type, bucket_display_name)");
1531        }
1532
1533        if (fromVersion < 302) {
1534            db.execSQL("CREATE INDEX parent_index ON files(parent);");
1535            db.execSQL("CREATE INDEX format_index ON files(format);");
1536        }
1537
1538        if (fromVersion < 303) {
1539            // the album disambiguator hash changed, so rescan songs and force
1540            // albums to be updated. Artists are unaffected.
1541            db.execSQL("DELETE from albums");
1542            db.execSQL("UPDATE files SET date_modified=0 WHERE " + FileColumns.MEDIA_TYPE + "="
1543                    + FileColumns.MEDIA_TYPE_AUDIO + ";");
1544        }
1545
1546        if (fromVersion < 304 && !internal) {
1547            // notifies host when files are deleted
1548            db.execSQL("CREATE TRIGGER IF NOT EXISTS files_cleanup DELETE ON files " +
1549                    "BEGIN " +
1550                        "SELECT _OBJECT_REMOVED(old._id);" +
1551                    "END");
1552
1553        }
1554
1555        if (fromVersion < 305 && internal) {
1556            // version 304 erroneously added this trigger to the internal database
1557            db.execSQL("DROP TRIGGER IF EXISTS files_cleanup");
1558        }
1559
1560        if (fromVersion < 306 && !internal) {
1561            // The genre list was expanded and genre string parsing was tweaked, so
1562            // rebuild the genre list
1563            db.execSQL("UPDATE files SET date_modified=0 WHERE " + FileColumns.MEDIA_TYPE + "="
1564                    + FileColumns.MEDIA_TYPE_AUDIO + ";");
1565            db.execSQL("DELETE FROM audio_genres_map");
1566            db.execSQL("DELETE FROM audio_genres");
1567        }
1568
1569        if (fromVersion < 307 && !internal) {
1570            // Force rescan of image entries to update DATE_TAKEN by either GPSTimeStamp or
1571            // EXIF local time.
1572            db.execSQL("UPDATE files SET date_modified=0 WHERE " + FileColumns.MEDIA_TYPE + "="
1573                    + FileColumns.MEDIA_TYPE_IMAGE + ";");
1574        }
1575
1576        // Honeycomb went up to version 307, ICS started at 401
1577
1578        // Database version 401 did not add storage_id to the internal database.
1579        // We need it there too, so add it in version 402
1580        if (fromVersion < 401 || (fromVersion == 401 && internal)) {
1581            // Add column for MTP storage ID
1582            db.execSQL("ALTER TABLE files ADD COLUMN storage_id INTEGER;");
1583            // Anything in the database before this upgrade step will be in the primary storage
1584            db.execSQL("UPDATE files SET storage_id=" + MtpStorage.getStorageId(0) + ";");
1585        }
1586
1587        if (fromVersion < 403 && !internal) {
1588            db.execSQL("CREATE VIEW audio_genres_map_noid AS " +
1589                    "SELECT audio_id,genre_id from audio_genres_map;");
1590        }
1591
1592        if (fromVersion < 404) {
1593            // There was a bug that could cause distinct same-named albums to be
1594            // combined again. Delete albums and force a rescan.
1595            db.execSQL("DELETE from albums");
1596            db.execSQL("UPDATE files SET date_modified=0 WHERE " + FileColumns.MEDIA_TYPE + "="
1597                    + FileColumns.MEDIA_TYPE_AUDIO + ";");
1598        }
1599
1600        if (fromVersion < 405) {
1601            // Add is_drm column.
1602            db.execSQL("ALTER TABLE files ADD COLUMN is_drm INTEGER;");
1603
1604            db.execSQL("DROP VIEW IF EXISTS audio_meta");
1605            db.execSQL("CREATE VIEW audio_meta AS SELECT _id," + AUDIO_COLUMNSv405 +
1606                        " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
1607                        + FileColumns.MEDIA_TYPE_AUDIO + ";");
1608
1609            recreateAudioView(db);
1610        }
1611
1612        if (fromVersion < 407) {
1613            // Rescan files in the media database because a new column has been added
1614            // in table files in version 405 and to recover from problems populating
1615            // the genre tables
1616            db.execSQL("UPDATE files SET date_modified=0;");
1617        }
1618
1619        if (fromVersion < 408) {
1620            // Add the width/height columns for images and video
1621            db.execSQL("ALTER TABLE files ADD COLUMN width INTEGER;");
1622            db.execSQL("ALTER TABLE files ADD COLUMN height INTEGER;");
1623
1624            // Rescan files to fill the columns
1625            db.execSQL("UPDATE files SET date_modified=0;");
1626
1627            // Update images and video views to contain the width/height columns
1628            db.execSQL("DROP VIEW IF EXISTS images");
1629            db.execSQL("DROP VIEW IF EXISTS video");
1630            db.execSQL("CREATE VIEW images AS SELECT _id," + IMAGE_COLUMNS +
1631                        " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
1632                        + FileColumns.MEDIA_TYPE_IMAGE + ";");
1633            db.execSQL("CREATE VIEW video AS SELECT _id," + VIDEO_COLUMNS +
1634                        " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
1635                        + FileColumns.MEDIA_TYPE_VIDEO + ";");
1636        }
1637
1638        if (fromVersion < 409 && !internal) {
1639            // A bug that prevented numeric genres from being parsed was fixed, so
1640            // rebuild the genre list
1641            db.execSQL("UPDATE files SET date_modified=0 WHERE " + FileColumns.MEDIA_TYPE + "="
1642                    + FileColumns.MEDIA_TYPE_AUDIO + ";");
1643            db.execSQL("DELETE FROM audio_genres_map");
1644            db.execSQL("DELETE FROM audio_genres");
1645        }
1646
1647        // ICS went out with database version 409, JB started at 500
1648
1649        if (fromVersion < 500) {
1650            // we're now deleting the file in mediaprovider code, rather than via a trigger
1651            db.execSQL("DROP TRIGGER IF EXISTS videothumbnails_cleanup;");
1652        }
1653        if (fromVersion < 501) {
1654            // we're now deleting the file in mediaprovider code, rather than via a trigger
1655            // the images_cleanup trigger would delete the image file and the entry
1656            // in the thumbnail table, which in turn would trigger thumbnails_cleanup
1657            // to delete the thumbnail image
1658            db.execSQL("DROP TRIGGER IF EXISTS images_cleanup;");
1659            db.execSQL("DROP TRIGGER IF EXISTS thumbnails_cleanup;");
1660        }
1661        if (fromVersion < 502) {
1662            // we're now deleting the file in mediaprovider code, rather than via a trigger
1663            db.execSQL("DROP TRIGGER IF EXISTS video_cleanup;");
1664        }
1665        if (fromVersion < 503) {
1666            // genre and playlist cleanup now done in mediaprovider code, instead of in a trigger
1667            db.execSQL("DROP TRIGGER IF EXISTS audio_delete");
1668            db.execSQL("DROP TRIGGER IF EXISTS audio_meta_cleanup");
1669        }
1670        if (fromVersion < 504) {
1671            // add an index to help with case-insensitive matching of paths
1672            db.execSQL(
1673                    "CREATE INDEX IF NOT EXISTS path_index_lower ON files(_data COLLATE NOCASE);");
1674        }
1675        if (fromVersion < 505) {
1676            // Starting with schema 505 we fill in the width/height/resolution columns for videos,
1677            // so force a rescan of videos to fill in the blanks
1678            db.execSQL("UPDATE files SET date_modified=0 WHERE " + FileColumns.MEDIA_TYPE + "="
1679                    + FileColumns.MEDIA_TYPE_VIDEO + ";");
1680        }
1681        if (fromVersion < 506) {
1682            // sd card storage got moved to /storage/sdcard0
1683            // first delete everything that already got scanned in /storage before this
1684            // update step was added
1685            db.execSQL("DROP TRIGGER IF EXISTS files_cleanup");
1686            db.execSQL("DELETE FROM files WHERE _data LIKE '/storage/%';");
1687            db.execSQL("DELETE FROM album_art WHERE _data LIKE '/storage/%';");
1688            db.execSQL("DELETE FROM thumbnails WHERE _data LIKE '/storage/%';");
1689            db.execSQL("DELETE FROM videothumbnails WHERE _data LIKE '/storage/%';");
1690            // then rename everything from /mnt/sdcard/ to /storage/sdcard0,
1691            // and from /mnt/external1 to /storage/sdcard1
1692            db.execSQL("UPDATE files SET " +
1693                "_data='/storage/sdcard0'||SUBSTR(_data,12) WHERE _data LIKE '/mnt/sdcard/%';");
1694            db.execSQL("UPDATE files SET " +
1695                "_data='/storage/sdcard1'||SUBSTR(_data,15) WHERE _data LIKE '/mnt/external1/%';");
1696            db.execSQL("UPDATE album_art SET " +
1697                "_data='/storage/sdcard0'||SUBSTR(_data,12) WHERE _data LIKE '/mnt/sdcard/%';");
1698            db.execSQL("UPDATE album_art SET " +
1699                "_data='/storage/sdcard1'||SUBSTR(_data,15) WHERE _data LIKE '/mnt/external1/%';");
1700            db.execSQL("UPDATE thumbnails SET " +
1701                "_data='/storage/sdcard0'||SUBSTR(_data,12) WHERE _data LIKE '/mnt/sdcard/%';");
1702            db.execSQL("UPDATE thumbnails SET " +
1703                "_data='/storage/sdcard1'||SUBSTR(_data,15) WHERE _data LIKE '/mnt/external1/%';");
1704            db.execSQL("UPDATE videothumbnails SET " +
1705                "_data='/storage/sdcard0'||SUBSTR(_data,12) WHERE _data LIKE '/mnt/sdcard/%';");
1706            db.execSQL("UPDATE videothumbnails SET " +
1707                "_data='/storage/sdcard1'||SUBSTR(_data,15) WHERE _data LIKE '/mnt/external1/%';");
1708
1709            if (!internal) {
1710                db.execSQL("CREATE TRIGGER IF NOT EXISTS files_cleanup DELETE ON files " +
1711                    "BEGIN " +
1712                        "SELECT _OBJECT_REMOVED(old._id);" +
1713                    "END");
1714            }
1715        }
1716        if (fromVersion < 507) {
1717            // we update _data in version 506, we need to update the bucket_id as well
1718            updateBucketNames(db);
1719        }
1720        if (fromVersion < 508 && !internal) {
1721            // ensure we don't get duplicate entries in the genre map
1722            db.execSQL("CREATE TABLE IF NOT EXISTS audio_genres_map_tmp (" +
1723                    "_id INTEGER PRIMARY KEY," +
1724                    "audio_id INTEGER NOT NULL," +
1725                    "genre_id INTEGER NOT NULL," +
1726                    "UNIQUE (audio_id,genre_id) ON CONFLICT IGNORE" +
1727                    ");");
1728            db.execSQL("INSERT INTO audio_genres_map_tmp (audio_id,genre_id)" +
1729                    " SELECT DISTINCT audio_id,genre_id FROM audio_genres_map;");
1730            db.execSQL("DROP TABLE audio_genres_map;");
1731            db.execSQL("ALTER TABLE audio_genres_map_tmp RENAME TO audio_genres_map;");
1732        }
1733
1734        if (fromVersion < 509) {
1735            db.execSQL("CREATE TABLE IF NOT EXISTS log (time DATETIME PRIMARY KEY, message TEXT);");
1736        }
1737
1738        // Emulated external storage moved to user-specific paths
1739        if (fromVersion < 510 && Environment.isExternalStorageEmulated()) {
1740            // File.fixSlashes() removes any trailing slashes
1741            final String externalStorage = Environment.getExternalStorageDirectory().toString();
1742            Log.d(TAG, "Adjusting external storage paths to: " + externalStorage);
1743
1744            final String[] tables = {
1745                    TABLE_FILES, TABLE_ALBUM_ART, TABLE_THUMBNAILS, TABLE_VIDEO_THUMBNAILS };
1746            for (String table : tables) {
1747                db.execSQL("UPDATE " + table + " SET " + "_data='" + externalStorage
1748                        + "'||SUBSTR(_data,17) WHERE _data LIKE '/storage/sdcard0/%';");
1749            }
1750        }
1751        if (fromVersion < 511) {
1752            // we update _data in version 510, we need to update the bucket_id as well
1753            updateBucketNames(db);
1754        }
1755
1756        // JB 4.2 went out with database version 511, starting next release with 600
1757
1758        if (fromVersion < 600) {
1759            // modify _data column to be unique and collate nocase. Because this drops the original
1760            // table and replaces it with a new one by the same name, we need to also recreate all
1761            // indices and triggers that refer to the files table.
1762            // Views don't need to be recreated.
1763
1764            db.execSQL("CREATE TABLE files2 (_id INTEGER PRIMARY KEY AUTOINCREMENT," +
1765                    "_data TEXT UNIQUE" +
1766                    // the internal filesystem is case-sensitive
1767                    (internal ? "," : " COLLATE NOCASE,") +
1768                    "_size INTEGER,format INTEGER,parent INTEGER,date_added INTEGER," +
1769                    "date_modified INTEGER,mime_type TEXT,title TEXT,description TEXT," +
1770                    "_display_name TEXT,picasa_id TEXT,orientation INTEGER,latitude DOUBLE," +
1771                    "longitude DOUBLE,datetaken INTEGER,mini_thumb_magic INTEGER,bucket_id TEXT," +
1772                    "bucket_display_name TEXT,isprivate INTEGER,title_key TEXT,artist_id INTEGER," +
1773                    "album_id INTEGER,composer TEXT,track INTEGER,year INTEGER CHECK(year!=0)," +
1774                    "is_ringtone INTEGER,is_music INTEGER,is_alarm INTEGER," +
1775                    "is_notification INTEGER,is_podcast INTEGER,album_artist TEXT," +
1776                    "duration INTEGER,bookmark INTEGER,artist TEXT,album TEXT,resolution TEXT," +
1777                    "tags TEXT,category TEXT,language TEXT,mini_thumb_data TEXT,name TEXT," +
1778                    "media_type INTEGER,old_id INTEGER,storage_id INTEGER,is_drm INTEGER," +
1779                    "width INTEGER, height INTEGER);");
1780
1781            // copy data from old table, squashing entries with duplicate _data
1782            db.execSQL("INSERT OR REPLACE INTO files2 SELECT * FROM files;");
1783            db.execSQL("DROP TABLE files;");
1784            db.execSQL("ALTER TABLE files2 RENAME TO files;");
1785
1786            // recreate indices and triggers
1787            db.execSQL("CREATE INDEX album_id_idx ON files(album_id);");
1788            db.execSQL("CREATE INDEX artist_id_idx ON files(artist_id);");
1789            db.execSQL("CREATE INDEX bucket_index on files(bucket_id,media_type," +
1790                    "datetaken, _id);");
1791            db.execSQL("CREATE INDEX bucket_name on files(bucket_id,media_type," +
1792                    "bucket_display_name);");
1793            db.execSQL("CREATE INDEX format_index ON files(format);");
1794            db.execSQL("CREATE INDEX media_type_index ON files(media_type);");
1795            db.execSQL("CREATE INDEX parent_index ON files(parent);");
1796            db.execSQL("CREATE INDEX path_index ON files(_data);");
1797            db.execSQL("CREATE INDEX sort_index ON files(datetaken ASC, _id ASC);");
1798            db.execSQL("CREATE INDEX title_idx ON files(title);");
1799            db.execSQL("CREATE INDEX titlekey_index ON files(title_key);");
1800            if (!internal) {
1801                db.execSQL("CREATE TRIGGER audio_playlists_cleanup DELETE ON files" +
1802                        " WHEN old.media_type=4" +
1803                        " BEGIN DELETE FROM audio_playlists_map WHERE playlist_id = old._id;" +
1804                        "SELECT _DELETE_FILE(old._data);END;");
1805                db.execSQL("CREATE TRIGGER files_cleanup DELETE ON files" +
1806                        " BEGIN SELECT _OBJECT_REMOVED(old._id);END;");
1807            }
1808        }
1809
1810        if (fromVersion < 601) {
1811            // remove primary key constraint because column time is not necessarily unique
1812            db.execSQL("CREATE TABLE IF NOT EXISTS log_tmp (time DATETIME, message TEXT);");
1813            db.execSQL("DELETE FROM log_tmp;");
1814            db.execSQL("INSERT INTO log_tmp SELECT time, message FROM log order by rowid;");
1815            db.execSQL("DROP TABLE log;");
1816            db.execSQL("ALTER TABLE log_tmp RENAME TO log;");
1817        }
1818
1819        sanityCheck(db, fromVersion);
1820        long elapsedSeconds = (SystemClock.currentTimeMicro() - startTime) / 1000000;
1821        logToDb(db, "Database upgraded from version " + fromVersion + " to " + toVersion
1822                + " in " + elapsedSeconds + " seconds");
1823    }
1824
1825    /**
1826     * Write a persistent diagnostic message to the log table.
1827     */
1828    static void logToDb(SQLiteDatabase db, String message) {
1829        db.execSQL("INSERT OR REPLACE" +
1830                " INTO log (time,message) VALUES (strftime('%Y-%m-%d %H:%M:%f','now'),?);",
1831                new String[] { message });
1832        // delete all but the last 500 rows
1833        db.execSQL("DELETE FROM log WHERE rowid IN" +
1834                " (SELECT rowid FROM log ORDER BY rowid DESC LIMIT 500,-1);");
1835    }
1836
1837    /**
1838     * Perform a simple sanity check on the database. Currently this tests
1839     * whether all the _data entries in audio_meta are unique
1840     */
1841    private static void sanityCheck(SQLiteDatabase db, int fromVersion) {
1842        Cursor c1 = db.query("audio_meta", new String[] {"count(*)"},
1843                null, null, null, null, null);
1844        Cursor c2 = db.query("audio_meta", new String[] {"count(distinct _data)"},
1845                null, null, null, null, null);
1846        c1.moveToFirst();
1847        c2.moveToFirst();
1848        int num1 = c1.getInt(0);
1849        int num2 = c2.getInt(0);
1850        c1.close();
1851        c2.close();
1852        if (num1 != num2) {
1853            Log.e(TAG, "audio_meta._data column is not unique while upgrading" +
1854                    " from schema " +fromVersion + " : " + num1 +"/" + num2);
1855            // Delete all audio_meta rows so they will be rebuilt by the media scanner
1856            db.execSQL("DELETE FROM audio_meta;");
1857        }
1858    }
1859
1860    private static void recreateAudioView(SQLiteDatabase db) {
1861        // Provides a unified audio/artist/album info view.
1862        db.execSQL("DROP VIEW IF EXISTS audio");
1863        db.execSQL("CREATE VIEW IF NOT EXISTS audio as SELECT * FROM audio_meta " +
1864                    "LEFT OUTER JOIN artists ON audio_meta.artist_id=artists.artist_id " +
1865                    "LEFT OUTER JOIN albums ON audio_meta.album_id=albums.album_id;");
1866    }
1867
1868    /**
1869     * Update the bucket_id and bucket_display_name columns for images and videos
1870     * @param db
1871     * @param tableName
1872     */
1873    private static void updateBucketNames(SQLiteDatabase db) {
1874        // Rebuild the bucket_display_name column using the natural case rather than lower case.
1875        db.beginTransaction();
1876        try {
1877            String[] columns = {BaseColumns._ID, MediaColumns.DATA};
1878            // update only images and videos
1879            Cursor cursor = db.query("files", columns, "media_type=1 OR media_type=3",
1880                    null, null, null, null);
1881            try {
1882                final int idColumnIndex = cursor.getColumnIndex(BaseColumns._ID);
1883                final int dataColumnIndex = cursor.getColumnIndex(MediaColumns.DATA);
1884                String [] rowId = new String[1];
1885                ContentValues values = new ContentValues();
1886                while (cursor.moveToNext()) {
1887                    String data = cursor.getString(dataColumnIndex);
1888                    rowId[0] = cursor.getString(idColumnIndex);
1889                    if (data != null) {
1890                        values.clear();
1891                        computeBucketValues(data, values);
1892                        db.update("files", values, "_id=?", rowId);
1893                    } else {
1894                        Log.w(TAG, "null data at id " + rowId);
1895                    }
1896                }
1897            } finally {
1898                cursor.close();
1899            }
1900            db.setTransactionSuccessful();
1901        } finally {
1902            db.endTransaction();
1903        }
1904    }
1905
1906    /**
1907     * Iterate through the rows of a table in a database, ensuring that the
1908     * display name column has a value.
1909     * @param db
1910     * @param tableName
1911     */
1912    private static void updateDisplayName(SQLiteDatabase db, String tableName) {
1913        // Fill in default values for null displayName values
1914        db.beginTransaction();
1915        try {
1916            String[] columns = {BaseColumns._ID, MediaColumns.DATA, MediaColumns.DISPLAY_NAME};
1917            Cursor cursor = db.query(tableName, columns, null, null, null, null, null);
1918            try {
1919                final int idColumnIndex = cursor.getColumnIndex(BaseColumns._ID);
1920                final int dataColumnIndex = cursor.getColumnIndex(MediaColumns.DATA);
1921                final int displayNameIndex = cursor.getColumnIndex(MediaColumns.DISPLAY_NAME);
1922                ContentValues values = new ContentValues();
1923                while (cursor.moveToNext()) {
1924                    String displayName = cursor.getString(displayNameIndex);
1925                    if (displayName == null) {
1926                        String data = cursor.getString(dataColumnIndex);
1927                        values.clear();
1928                        computeDisplayName(data, values);
1929                        int rowId = cursor.getInt(idColumnIndex);
1930                        db.update(tableName, values, "_id=" + rowId, null);
1931                    }
1932                }
1933            } finally {
1934                cursor.close();
1935            }
1936            db.setTransactionSuccessful();
1937        } finally {
1938            db.endTransaction();
1939        }
1940    }
1941
1942    /**
1943     * @param data The input path
1944     * @param values the content values, where the bucked id name and bucket display name are updated.
1945     *
1946     */
1947    private static void computeBucketValues(String data, ContentValues values) {
1948        File parentFile = new File(data).getParentFile();
1949        if (parentFile == null) {
1950            parentFile = new File("/");
1951        }
1952
1953        // Lowercase the path for hashing. This avoids duplicate buckets if the
1954        // filepath case is changed externally.
1955        // Keep the original case for display.
1956        String path = parentFile.toString().toLowerCase();
1957        String name = parentFile.getName();
1958
1959        // Note: the BUCKET_ID and BUCKET_DISPLAY_NAME attributes are spelled the
1960        // same for both images and video. However, for backwards-compatibility reasons
1961        // there is no common base class. We use the ImageColumns version here
1962        values.put(ImageColumns.BUCKET_ID, path.hashCode());
1963        values.put(ImageColumns.BUCKET_DISPLAY_NAME, name);
1964    }
1965
1966    /**
1967     * @param data The input path
1968     * @param values the content values, where the display name is updated.
1969     *
1970     */
1971    private static void computeDisplayName(String data, ContentValues values) {
1972        String s = (data == null ? "" : data.toString());
1973        int idx = s.lastIndexOf('/');
1974        if (idx >= 0) {
1975            s = s.substring(idx + 1);
1976        }
1977        values.put("_display_name", s);
1978    }
1979
1980    /**
1981     * Copy taken time from date_modified if we lost the original value (e.g. after factory reset)
1982     * This works for both video and image tables.
1983     *
1984     * @param values the content values, where taken time is updated.
1985     */
1986    private static void computeTakenTime(ContentValues values) {
1987        if (! values.containsKey(Images.Media.DATE_TAKEN)) {
1988            // This only happens when MediaScanner finds an image file that doesn't have any useful
1989            // reference to get this value. (e.g. GPSTimeStamp)
1990            Long lastModified = values.getAsLong(MediaColumns.DATE_MODIFIED);
1991            if (lastModified != null) {
1992                values.put(Images.Media.DATE_TAKEN, lastModified * 1000);
1993            }
1994        }
1995    }
1996
1997    /**
1998     * This method blocks until thumbnail is ready.
1999     *
2000     * @param thumbUri
2001     * @return
2002     */
2003    private boolean waitForThumbnailReady(Uri origUri) {
2004        Cursor c = this.query(origUri, new String[] { ImageColumns._ID, ImageColumns.DATA,
2005                ImageColumns.MINI_THUMB_MAGIC}, null, null, null);
2006        if (c == null) return false;
2007
2008        boolean result = false;
2009
2010        if (c.moveToFirst()) {
2011            long id = c.getLong(0);
2012            String path = c.getString(1);
2013            long magic = c.getLong(2);
2014
2015            MediaThumbRequest req = requestMediaThumbnail(path, origUri,
2016                    MediaThumbRequest.PRIORITY_HIGH, magic);
2017            if (req == null) {
2018                return false;
2019            }
2020            synchronized (req) {
2021                try {
2022                    while (req.mState == MediaThumbRequest.State.WAIT) {
2023                        req.wait();
2024                    }
2025                } catch (InterruptedException e) {
2026                    Log.w(TAG, e);
2027                }
2028                if (req.mState == MediaThumbRequest.State.DONE) {
2029                    result = true;
2030                }
2031            }
2032        }
2033        c.close();
2034
2035        return result;
2036    }
2037
2038    private boolean matchThumbRequest(MediaThumbRequest req, int pid, long id, long gid,
2039            boolean isVideo) {
2040        boolean cancelAllOrigId = (id == -1);
2041        boolean cancelAllGroupId = (gid == -1);
2042        return (req.mCallingPid == pid) &&
2043                (cancelAllGroupId || req.mGroupId == gid) &&
2044                (cancelAllOrigId || req.mOrigId == id) &&
2045                (req.mIsVideo == isVideo);
2046    }
2047
2048    private boolean queryThumbnail(SQLiteQueryBuilder qb, Uri uri, String table,
2049            String column, boolean hasThumbnailId) {
2050        qb.setTables(table);
2051        if (hasThumbnailId) {
2052            // For uri dispatched to this method, the 4th path segment is always
2053            // the thumbnail id.
2054            qb.appendWhere("_id = " + uri.getPathSegments().get(3));
2055            // client already knows which thumbnail it wants, bypass it.
2056            return true;
2057        }
2058        String origId = uri.getQueryParameter("orig_id");
2059        // We can't query ready_flag unless we know original id
2060        if (origId == null) {
2061            // this could be thumbnail query for other purpose, bypass it.
2062            return true;
2063        }
2064
2065        boolean needBlocking = "1".equals(uri.getQueryParameter("blocking"));
2066        boolean cancelRequest = "1".equals(uri.getQueryParameter("cancel"));
2067        Uri origUri = uri.buildUpon().encodedPath(
2068                uri.getPath().replaceFirst("thumbnails", "media"))
2069                .appendPath(origId).build();
2070
2071        if (needBlocking && !waitForThumbnailReady(origUri)) {
2072            Log.w(TAG, "original media doesn't exist or it's canceled.");
2073            return false;
2074        } else if (cancelRequest) {
2075            String groupId = uri.getQueryParameter("group_id");
2076            boolean isVideo = "video".equals(uri.getPathSegments().get(1));
2077            int pid = Binder.getCallingPid();
2078            long id = -1;
2079            long gid = -1;
2080
2081            try {
2082                id = Long.parseLong(origId);
2083                gid = Long.parseLong(groupId);
2084            } catch (NumberFormatException ex) {
2085                // invalid cancel request
2086                return false;
2087            }
2088
2089            synchronized (mMediaThumbQueue) {
2090                if (mCurrentThumbRequest != null &&
2091                        matchThumbRequest(mCurrentThumbRequest, pid, id, gid, isVideo)) {
2092                    synchronized (mCurrentThumbRequest) {
2093                        mCurrentThumbRequest.mState = MediaThumbRequest.State.CANCEL;
2094                        mCurrentThumbRequest.notifyAll();
2095                    }
2096                }
2097                for (MediaThumbRequest mtq : mMediaThumbQueue) {
2098                    if (matchThumbRequest(mtq, pid, id, gid, isVideo)) {
2099                        synchronized (mtq) {
2100                            mtq.mState = MediaThumbRequest.State.CANCEL;
2101                            mtq.notifyAll();
2102                        }
2103
2104                        mMediaThumbQueue.remove(mtq);
2105                    }
2106                }
2107            }
2108        }
2109
2110        if (origId != null) {
2111            qb.appendWhere(column + " = " + origId);
2112        }
2113        return true;
2114    }
2115    @SuppressWarnings("fallthrough")
2116    @Override
2117    public Cursor query(Uri uri, String[] projectionIn, String selection,
2118            String[] selectionArgs, String sort) {
2119        int table = URI_MATCHER.match(uri);
2120        List<String> prependArgs = new ArrayList<String>();
2121
2122        // Log.v(TAG, "query: uri="+uri+", selection="+selection);
2123        // handle MEDIA_SCANNER before calling getDatabaseForUri()
2124        if (table == MEDIA_SCANNER) {
2125            if (mMediaScannerVolume == null) {
2126                return null;
2127            } else {
2128                // create a cursor to return volume currently being scanned by the media scanner
2129                MatrixCursor c = new MatrixCursor(new String[] {MediaStore.MEDIA_SCANNER_VOLUME});
2130                c.addRow(new String[] {mMediaScannerVolume});
2131                return c;
2132            }
2133        }
2134
2135        // Used temporarily (until we have unique media IDs) to get an identifier
2136        // for the current sd card, so that the music app doesn't have to use the
2137        // non-public getFatVolumeId method
2138        if (table == FS_ID) {
2139            MatrixCursor c = new MatrixCursor(new String[] {"fsid"});
2140            c.addRow(new Integer[] {mVolumeId});
2141            return c;
2142        }
2143
2144        if (table == VERSION) {
2145            MatrixCursor c = new MatrixCursor(new String[] {"version"});
2146            c.addRow(new Integer[] {getDatabaseVersion(getContext())});
2147            return c;
2148        }
2149
2150        String groupBy = null;
2151        DatabaseHelper helper = getDatabaseForUri(uri);
2152        if (helper == null) {
2153            return null;
2154        }
2155        helper.mNumQueries++;
2156        SQLiteDatabase db = helper.getReadableDatabase();
2157        if (db == null) return null;
2158        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2159        String limit = uri.getQueryParameter("limit");
2160        String filter = uri.getQueryParameter("filter");
2161        String [] keywords = null;
2162        if (filter != null) {
2163            filter = Uri.decode(filter).trim();
2164            if (!TextUtils.isEmpty(filter)) {
2165                String [] searchWords = filter.split(" ");
2166                keywords = new String[searchWords.length];
2167                for (int i = 0; i < searchWords.length; i++) {
2168                    String key = MediaStore.Audio.keyFor(searchWords[i]);
2169                    key = key.replace("\\", "\\\\");
2170                    key = key.replace("%", "\\%");
2171                    key = key.replace("_", "\\_");
2172                    keywords[i] = key;
2173                }
2174            }
2175        }
2176        if (uri.getQueryParameter("distinct") != null) {
2177            qb.setDistinct(true);
2178        }
2179
2180        boolean hasThumbnailId = false;
2181
2182        switch (table) {
2183            case IMAGES_MEDIA:
2184                qb.setTables("images");
2185                if (uri.getQueryParameter("distinct") != null)
2186                    qb.setDistinct(true);
2187
2188                // set the project map so that data dir is prepended to _data.
2189                //qb.setProjectionMap(mImagesProjectionMap, true);
2190                break;
2191
2192            case IMAGES_MEDIA_ID:
2193                qb.setTables("images");
2194                if (uri.getQueryParameter("distinct") != null)
2195                    qb.setDistinct(true);
2196
2197                // set the project map so that data dir is prepended to _data.
2198                //qb.setProjectionMap(mImagesProjectionMap, true);
2199                qb.appendWhere("_id=?");
2200                prependArgs.add(uri.getPathSegments().get(3));
2201                break;
2202
2203            case IMAGES_THUMBNAILS_ID:
2204                hasThumbnailId = true;
2205            case IMAGES_THUMBNAILS:
2206                if (!queryThumbnail(qb, uri, "thumbnails", "image_id", hasThumbnailId)) {
2207                    return null;
2208                }
2209                break;
2210
2211            case AUDIO_MEDIA:
2212                if (projectionIn != null && projectionIn.length == 1 &&  selectionArgs == null
2213                        && (selection == null || selection.equalsIgnoreCase("is_music=1")
2214                          || selection.equalsIgnoreCase("is_podcast=1") )
2215                        && projectionIn[0].equalsIgnoreCase("count(*)")
2216                        && keywords != null) {
2217                    //Log.i("@@@@", "taking fast path for counting songs");
2218                    qb.setTables("audio_meta");
2219                } else {
2220                    qb.setTables("audio");
2221                    for (int i = 0; keywords != null && i < keywords.length; i++) {
2222                        if (i > 0) {
2223                            qb.appendWhere(" AND ");
2224                        }
2225                        qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
2226                                "||" + MediaStore.Audio.Media.ALBUM_KEY +
2227                                "||" + MediaStore.Audio.Media.TITLE_KEY + " LIKE ? ESCAPE '\\'");
2228                        prependArgs.add("%" + keywords[i] + "%");
2229                    }
2230                }
2231                break;
2232
2233            case AUDIO_MEDIA_ID:
2234                qb.setTables("audio");
2235                qb.appendWhere("_id=?");
2236                prependArgs.add(uri.getPathSegments().get(3));
2237                break;
2238
2239            case AUDIO_MEDIA_ID_GENRES:
2240                qb.setTables("audio_genres");
2241                qb.appendWhere("_id IN (SELECT genre_id FROM " +
2242                        "audio_genres_map WHERE audio_id=?)");
2243                prependArgs.add(uri.getPathSegments().get(3));
2244                break;
2245
2246            case AUDIO_MEDIA_ID_GENRES_ID:
2247                qb.setTables("audio_genres");
2248                qb.appendWhere("_id=?");
2249                prependArgs.add(uri.getPathSegments().get(5));
2250                break;
2251
2252            case AUDIO_MEDIA_ID_PLAYLISTS:
2253                qb.setTables("audio_playlists");
2254                qb.appendWhere("_id IN (SELECT playlist_id FROM " +
2255                        "audio_playlists_map WHERE audio_id=?)");
2256                prependArgs.add(uri.getPathSegments().get(3));
2257                break;
2258
2259            case AUDIO_MEDIA_ID_PLAYLISTS_ID:
2260                qb.setTables("audio_playlists");
2261                qb.appendWhere("_id=?");
2262                prependArgs.add(uri.getPathSegments().get(5));
2263                break;
2264
2265            case AUDIO_GENRES:
2266                qb.setTables("audio_genres");
2267                break;
2268
2269            case AUDIO_GENRES_ID:
2270                qb.setTables("audio_genres");
2271                qb.appendWhere("_id=?");
2272                prependArgs.add(uri.getPathSegments().get(3));
2273                break;
2274
2275            case AUDIO_GENRES_ALL_MEMBERS:
2276            case AUDIO_GENRES_ID_MEMBERS:
2277                {
2278                    // if simpleQuery is true, we can do a simpler query on just audio_genres_map
2279                    // we can do this if we have no keywords and our projection includes just columns
2280                    // from audio_genres_map
2281                    boolean simpleQuery = (keywords == null && projectionIn != null
2282                            && (selection == null || selection.equalsIgnoreCase("genre_id=?")));
2283                    if (projectionIn != null) {
2284                        for (int i = 0; i < projectionIn.length; i++) {
2285                            String p = projectionIn[i];
2286                            if (p.equals("_id")) {
2287                                // note, this is different from playlist below, because
2288                                // "_id" used to (wrongly) be the audio id in this query, not
2289                                // the row id of the entry in the map, and we preserve this
2290                                // behavior for backwards compatibility
2291                                simpleQuery = false;
2292                            }
2293                            if (simpleQuery && !(p.equals("audio_id") ||
2294                                    p.equals("genre_id"))) {
2295                                simpleQuery = false;
2296                            }
2297                        }
2298                    }
2299                    if (simpleQuery) {
2300                        qb.setTables("audio_genres_map_noid");
2301                        if (table == AUDIO_GENRES_ID_MEMBERS) {
2302                            qb.appendWhere("genre_id=?");
2303                            prependArgs.add(uri.getPathSegments().get(3));
2304                        }
2305                    } else {
2306                        qb.setTables("audio_genres_map_noid, audio");
2307                        qb.appendWhere("audio._id = audio_id");
2308                        if (table == AUDIO_GENRES_ID_MEMBERS) {
2309                            qb.appendWhere(" AND genre_id=?");
2310                            prependArgs.add(uri.getPathSegments().get(3));
2311                        }
2312                        for (int i = 0; keywords != null && i < keywords.length; i++) {
2313                            qb.appendWhere(" AND ");
2314                            qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
2315                                    "||" + MediaStore.Audio.Media.ALBUM_KEY +
2316                                    "||" + MediaStore.Audio.Media.TITLE_KEY +
2317                                    " LIKE ? ESCAPE '\\'");
2318                            prependArgs.add("%" + keywords[i] + "%");
2319                        }
2320                    }
2321                }
2322                break;
2323
2324            case AUDIO_PLAYLISTS:
2325                qb.setTables("audio_playlists");
2326                break;
2327
2328            case AUDIO_PLAYLISTS_ID:
2329                qb.setTables("audio_playlists");
2330                qb.appendWhere("_id=?");
2331                prependArgs.add(uri.getPathSegments().get(3));
2332                break;
2333
2334            case AUDIO_PLAYLISTS_ID_MEMBERS_ID:
2335            case AUDIO_PLAYLISTS_ID_MEMBERS:
2336                // if simpleQuery is true, we can do a simpler query on just audio_playlists_map
2337                // we can do this if we have no keywords and our projection includes just columns
2338                // from audio_playlists_map
2339                boolean simpleQuery = (keywords == null && projectionIn != null
2340                        && (selection == null || selection.equalsIgnoreCase("playlist_id=?")));
2341                if (projectionIn != null) {
2342                    for (int i = 0; i < projectionIn.length; i++) {
2343                        String p = projectionIn[i];
2344                        if (simpleQuery && !(p.equals("audio_id") ||
2345                                p.equals("playlist_id") || p.equals("play_order"))) {
2346                            simpleQuery = false;
2347                        }
2348                        if (p.equals("_id")) {
2349                            projectionIn[i] = "audio_playlists_map._id AS _id";
2350                        }
2351                    }
2352                }
2353                if (simpleQuery) {
2354                    qb.setTables("audio_playlists_map");
2355                    qb.appendWhere("playlist_id=?");
2356                    prependArgs.add(uri.getPathSegments().get(3));
2357                } else {
2358                    qb.setTables("audio_playlists_map, audio");
2359                    qb.appendWhere("audio._id = audio_id AND playlist_id=?");
2360                    prependArgs.add(uri.getPathSegments().get(3));
2361                    for (int i = 0; keywords != null && i < keywords.length; i++) {
2362                        qb.appendWhere(" AND ");
2363                        qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
2364                                "||" + MediaStore.Audio.Media.ALBUM_KEY +
2365                                "||" + MediaStore.Audio.Media.TITLE_KEY +
2366                                " LIKE ? ESCAPE '\\'");
2367                        prependArgs.add("%" + keywords[i] + "%");
2368                    }
2369                }
2370                if (table == AUDIO_PLAYLISTS_ID_MEMBERS_ID) {
2371                    qb.appendWhere(" AND audio_playlists_map._id=?");
2372                    prependArgs.add(uri.getPathSegments().get(5));
2373                }
2374                break;
2375
2376            case VIDEO_MEDIA:
2377                qb.setTables("video");
2378                break;
2379            case VIDEO_MEDIA_ID:
2380                qb.setTables("video");
2381                qb.appendWhere("_id=?");
2382                prependArgs.add(uri.getPathSegments().get(3));
2383                break;
2384
2385            case VIDEO_THUMBNAILS_ID:
2386                hasThumbnailId = true;
2387            case VIDEO_THUMBNAILS:
2388                if (!queryThumbnail(qb, uri, "videothumbnails", "video_id", hasThumbnailId)) {
2389                    return null;
2390                }
2391                break;
2392
2393            case AUDIO_ARTISTS:
2394                if (projectionIn != null && projectionIn.length == 1 &&  selectionArgs == null
2395                        && (selection == null || selection.length() == 0)
2396                        && projectionIn[0].equalsIgnoreCase("count(*)")
2397                        && keywords != null) {
2398                    //Log.i("@@@@", "taking fast path for counting artists");
2399                    qb.setTables("audio_meta");
2400                    projectionIn[0] = "count(distinct artist_id)";
2401                    qb.appendWhere("is_music=1");
2402                } else {
2403                    qb.setTables("artist_info");
2404                    for (int i = 0; keywords != null && i < keywords.length; i++) {
2405                        if (i > 0) {
2406                            qb.appendWhere(" AND ");
2407                        }
2408                        qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
2409                                " LIKE ? ESCAPE '\\'");
2410                        prependArgs.add("%" + keywords[i] + "%");
2411                    }
2412                }
2413                break;
2414
2415            case AUDIO_ARTISTS_ID:
2416                qb.setTables("artist_info");
2417                qb.appendWhere("_id=?");
2418                prependArgs.add(uri.getPathSegments().get(3));
2419                break;
2420
2421            case AUDIO_ARTISTS_ID_ALBUMS:
2422                String aid = uri.getPathSegments().get(3);
2423                qb.setTables("audio LEFT OUTER JOIN album_art ON" +
2424                        " audio.album_id=album_art.album_id");
2425                qb.appendWhere("is_music=1 AND audio.album_id IN (SELECT album_id FROM " +
2426                        "artists_albums_map WHERE artist_id=?)");
2427                prependArgs.add(aid);
2428                for (int i = 0; keywords != null && i < keywords.length; i++) {
2429                    qb.appendWhere(" AND ");
2430                    qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
2431                            "||" + MediaStore.Audio.Media.ALBUM_KEY +
2432                            " LIKE ? ESCAPE '\\'");
2433                    prependArgs.add("%" + keywords[i] + "%");
2434                }
2435                groupBy = "audio.album_id";
2436                sArtistAlbumsMap.put(MediaStore.Audio.Albums.NUMBER_OF_SONGS_FOR_ARTIST,
2437                        "count(CASE WHEN artist_id==" + aid + " THEN 'foo' ELSE NULL END) AS " +
2438                        MediaStore.Audio.Albums.NUMBER_OF_SONGS_FOR_ARTIST);
2439                qb.setProjectionMap(sArtistAlbumsMap);
2440                break;
2441
2442            case AUDIO_ALBUMS:
2443                if (projectionIn != null && projectionIn.length == 1 &&  selectionArgs == null
2444                        && (selection == null || selection.length() == 0)
2445                        && projectionIn[0].equalsIgnoreCase("count(*)")
2446                        && keywords != null) {
2447                    //Log.i("@@@@", "taking fast path for counting albums");
2448                    qb.setTables("audio_meta");
2449                    projectionIn[0] = "count(distinct album_id)";
2450                    qb.appendWhere("is_music=1");
2451                } else {
2452                    qb.setTables("album_info");
2453                    for (int i = 0; keywords != null && i < keywords.length; i++) {
2454                        if (i > 0) {
2455                            qb.appendWhere(" AND ");
2456                        }
2457                        qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
2458                                "||" + MediaStore.Audio.Media.ALBUM_KEY +
2459                                " LIKE ? ESCAPE '\\'");
2460                        prependArgs.add("%" + keywords[i] + "%");
2461                    }
2462                }
2463                break;
2464
2465            case AUDIO_ALBUMS_ID:
2466                qb.setTables("album_info");
2467                qb.appendWhere("_id=?");
2468                prependArgs.add(uri.getPathSegments().get(3));
2469                break;
2470
2471            case AUDIO_ALBUMART_ID:
2472                qb.setTables("album_art");
2473                qb.appendWhere("album_id=?");
2474                prependArgs.add(uri.getPathSegments().get(3));
2475                break;
2476
2477            case AUDIO_SEARCH_LEGACY:
2478                Log.w(TAG, "Legacy media search Uri used. Please update your code.");
2479                // fall through
2480            case AUDIO_SEARCH_FANCY:
2481            case AUDIO_SEARCH_BASIC:
2482                return doAudioSearch(db, qb, uri, projectionIn, selection,
2483                        combine(prependArgs, selectionArgs), sort, table, limit);
2484
2485            case FILES_ID:
2486            case MTP_OBJECTS_ID:
2487                qb.appendWhere("_id=?");
2488                prependArgs.add(uri.getPathSegments().get(2));
2489                // fall through
2490            case FILES:
2491            case MTP_OBJECTS:
2492                qb.setTables("files");
2493                break;
2494
2495            case MTP_OBJECT_REFERENCES:
2496                int handle = Integer.parseInt(uri.getPathSegments().get(2));
2497                return getObjectReferences(helper, db, handle);
2498
2499            default:
2500                throw new IllegalStateException("Unknown URL: " + uri.toString());
2501        }
2502
2503        // Log.v(TAG, "query = "+ qb.buildQuery(projectionIn, selection,
2504        //        combine(prependArgs, selectionArgs), groupBy, null, sort, limit));
2505        Cursor c = qb.query(db, projectionIn, selection,
2506                combine(prependArgs, selectionArgs), groupBy, null, sort, limit);
2507
2508        if (c != null) {
2509            String nonotify = uri.getQueryParameter("nonotify");
2510            if (nonotify == null || !nonotify.equals("1")) {
2511                c.setNotificationUri(getContext().getContentResolver(), uri);
2512            }
2513        }
2514
2515        return c;
2516    }
2517
2518    private String[] combine(List<String> prepend, String[] userArgs) {
2519        int presize = prepend.size();
2520        if (presize == 0) {
2521            return userArgs;
2522        }
2523
2524        int usersize = (userArgs != null) ? userArgs.length : 0;
2525        String [] combined = new String[presize + usersize];
2526        for (int i = 0; i < presize; i++) {
2527            combined[i] = prepend.get(i);
2528        }
2529        for (int i = 0; i < usersize; i++) {
2530            combined[presize + i] = userArgs[i];
2531        }
2532        return combined;
2533    }
2534
2535    private Cursor doAudioSearch(SQLiteDatabase db, SQLiteQueryBuilder qb,
2536            Uri uri, String[] projectionIn, String selection,
2537            String[] selectionArgs, String sort, int mode,
2538            String limit) {
2539
2540        String mSearchString = uri.getPath().endsWith("/") ? "" : uri.getLastPathSegment();
2541        mSearchString = mSearchString.replaceAll("  ", " ").trim().toLowerCase();
2542
2543        String [] searchWords = mSearchString.length() > 0 ?
2544                mSearchString.split(" ") : new String[0];
2545        String [] wildcardWords = new String[searchWords.length];
2546        int len = searchWords.length;
2547        for (int i = 0; i < len; i++) {
2548            // Because we match on individual words here, we need to remove words
2549            // like 'a' and 'the' that aren't part of the keys.
2550            String key = MediaStore.Audio.keyFor(searchWords[i]);
2551            key = key.replace("\\", "\\\\");
2552            key = key.replace("%", "\\%");
2553            key = key.replace("_", "\\_");
2554            wildcardWords[i] =
2555                (searchWords[i].equals("a") || searchWords[i].equals("an") ||
2556                        searchWords[i].equals("the")) ? "%" : "%" + key + "%";
2557        }
2558
2559        String where = "";
2560        for (int i = 0; i < searchWords.length; i++) {
2561            if (i == 0) {
2562                where = "match LIKE ? ESCAPE '\\'";
2563            } else {
2564                where += " AND match LIKE ? ESCAPE '\\'";
2565            }
2566        }
2567
2568        qb.setTables("search");
2569        String [] cols;
2570        if (mode == AUDIO_SEARCH_FANCY) {
2571            cols = mSearchColsFancy;
2572        } else if (mode == AUDIO_SEARCH_BASIC) {
2573            cols = mSearchColsBasic;
2574        } else {
2575            cols = mSearchColsLegacy;
2576        }
2577        return qb.query(db, cols, where, wildcardWords, null, null, null, limit);
2578    }
2579
2580    @Override
2581    public String getType(Uri url)
2582    {
2583        switch (URI_MATCHER.match(url)) {
2584            case IMAGES_MEDIA_ID:
2585            case AUDIO_MEDIA_ID:
2586            case AUDIO_PLAYLISTS_ID_MEMBERS_ID:
2587            case VIDEO_MEDIA_ID:
2588            case FILES_ID:
2589                Cursor c = null;
2590                try {
2591                    c = query(url, MIME_TYPE_PROJECTION, null, null, null);
2592                    if (c != null && c.getCount() == 1) {
2593                        c.moveToFirst();
2594                        String mimeType = c.getString(1);
2595                        c.deactivate();
2596                        return mimeType;
2597                    }
2598                } finally {
2599                    if (c != null) {
2600                        c.close();
2601                    }
2602                }
2603                break;
2604
2605            case IMAGES_MEDIA:
2606            case IMAGES_THUMBNAILS:
2607                return Images.Media.CONTENT_TYPE;
2608            case AUDIO_ALBUMART_ID:
2609            case IMAGES_THUMBNAILS_ID:
2610                return "image/jpeg";
2611
2612            case AUDIO_MEDIA:
2613            case AUDIO_GENRES_ID_MEMBERS:
2614            case AUDIO_PLAYLISTS_ID_MEMBERS:
2615                return Audio.Media.CONTENT_TYPE;
2616
2617            case AUDIO_GENRES:
2618            case AUDIO_MEDIA_ID_GENRES:
2619                return Audio.Genres.CONTENT_TYPE;
2620            case AUDIO_GENRES_ID:
2621            case AUDIO_MEDIA_ID_GENRES_ID:
2622                return Audio.Genres.ENTRY_CONTENT_TYPE;
2623            case AUDIO_PLAYLISTS:
2624            case AUDIO_MEDIA_ID_PLAYLISTS:
2625                return Audio.Playlists.CONTENT_TYPE;
2626            case AUDIO_PLAYLISTS_ID:
2627            case AUDIO_MEDIA_ID_PLAYLISTS_ID:
2628                return Audio.Playlists.ENTRY_CONTENT_TYPE;
2629
2630            case VIDEO_MEDIA:
2631                return Video.Media.CONTENT_TYPE;
2632        }
2633        throw new IllegalStateException("Unknown URL : " + url);
2634    }
2635
2636    /**
2637     * Ensures there is a file in the _data column of values, if one isn't
2638     * present a new filename is generated. The file itself is not created.
2639     *
2640     * @param initialValues the values passed to insert by the caller
2641     * @return the new values
2642     */
2643    private ContentValues ensureFile(boolean internal, ContentValues initialValues,
2644            String preferredExtension, String directoryName) {
2645        ContentValues values;
2646        String file = initialValues.getAsString(MediaStore.MediaColumns.DATA);
2647        if (TextUtils.isEmpty(file)) {
2648            file = generateFileName(internal, preferredExtension, directoryName);
2649            values = new ContentValues(initialValues);
2650            values.put(MediaStore.MediaColumns.DATA, file);
2651        } else {
2652            values = initialValues;
2653        }
2654
2655        // we used to create the file here, but now defer this until openFile() is called
2656        return values;
2657    }
2658
2659    private void sendObjectAdded(long objectHandle) {
2660        synchronized (mMtpServiceConnection) {
2661            if (mMtpService != null) {
2662                try {
2663                    mMtpService.sendObjectAdded((int)objectHandle);
2664                } catch (RemoteException e) {
2665                    Log.e(TAG, "RemoteException in sendObjectAdded", e);
2666                    mMtpService = null;
2667                }
2668            }
2669        }
2670    }
2671
2672    private void sendObjectRemoved(long objectHandle) {
2673        synchronized (mMtpServiceConnection) {
2674            if (mMtpService != null) {
2675                try {
2676                    mMtpService.sendObjectRemoved((int)objectHandle);
2677                } catch (RemoteException e) {
2678                    Log.e(TAG, "RemoteException in sendObjectRemoved", e);
2679                    mMtpService = null;
2680                }
2681            }
2682        }
2683    }
2684
2685    @Override
2686    public int bulkInsert(Uri uri, ContentValues values[]) {
2687        int match = URI_MATCHER.match(uri);
2688        if (match == VOLUMES) {
2689            return super.bulkInsert(uri, values);
2690        }
2691        DatabaseHelper helper = getDatabaseForUri(uri);
2692        if (helper == null) {
2693            throw new UnsupportedOperationException(
2694                    "Unknown URI: " + uri);
2695        }
2696        SQLiteDatabase db = helper.getWritableDatabase();
2697        if (db == null) {
2698            throw new IllegalStateException("Couldn't open database for " + uri);
2699        }
2700
2701        if (match == AUDIO_PLAYLISTS_ID || match == AUDIO_PLAYLISTS_ID_MEMBERS) {
2702            return playlistBulkInsert(db, uri, values);
2703        } else if (match == MTP_OBJECT_REFERENCES) {
2704            int handle = Integer.parseInt(uri.getPathSegments().get(2));
2705            return setObjectReferences(helper, db, handle, values);
2706        }
2707
2708
2709        db.beginTransaction();
2710        ArrayList<Long> notifyRowIds = new ArrayList<Long>();
2711        int numInserted = 0;
2712        try {
2713            int len = values.length;
2714            for (int i = 0; i < len; i++) {
2715                if (values[i] != null) {
2716                    insertInternal(uri, match, values[i], notifyRowIds);
2717                }
2718            }
2719            numInserted = len;
2720            db.setTransactionSuccessful();
2721        } finally {
2722            db.endTransaction();
2723        }
2724
2725        // Notify MTP (outside of successful transaction)
2726        notifyMtp(notifyRowIds);
2727
2728        getContext().getContentResolver().notifyChange(uri, null);
2729        return numInserted;
2730    }
2731
2732    @Override
2733    public Uri insert(Uri uri, ContentValues initialValues) {
2734        int match = URI_MATCHER.match(uri);
2735
2736        ArrayList<Long> notifyRowIds = new ArrayList<Long>();
2737        Uri newUri = insertInternal(uri, match, initialValues, notifyRowIds);
2738        notifyMtp(notifyRowIds);
2739
2740        // do not signal notification for MTP objects.
2741        // we will signal instead after file transfer is successful.
2742        if (newUri != null && match != MTP_OBJECTS) {
2743            getContext().getContentResolver().notifyChange(uri, null);
2744        }
2745        return newUri;
2746    }
2747
2748    private void notifyMtp(ArrayList<Long> rowIds) {
2749        int size = rowIds.size();
2750        for (int i = 0; i < size; i++) {
2751            sendObjectAdded(rowIds.get(i).longValue());
2752        }
2753    }
2754
2755    private int playlistBulkInsert(SQLiteDatabase db, Uri uri, ContentValues values[]) {
2756        DatabaseUtils.InsertHelper helper =
2757            new DatabaseUtils.InsertHelper(db, "audio_playlists_map");
2758        int audioidcolidx = helper.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
2759        int playlistididx = helper.getColumnIndex(Audio.Playlists.Members.PLAYLIST_ID);
2760        int playorderidx = helper.getColumnIndex(MediaStore.Audio.Playlists.Members.PLAY_ORDER);
2761        long playlistId = Long.parseLong(uri.getPathSegments().get(3));
2762
2763        db.beginTransaction();
2764        int numInserted = 0;
2765        try {
2766            int len = values.length;
2767            for (int i = 0; i < len; i++) {
2768                helper.prepareForInsert();
2769                // getting the raw Object and converting it long ourselves saves
2770                // an allocation (the alternative is ContentValues.getAsLong, which
2771                // returns a Long object)
2772                long audioid = ((Number) values[i].get(
2773                        MediaStore.Audio.Playlists.Members.AUDIO_ID)).longValue();
2774                helper.bind(audioidcolidx, audioid);
2775                helper.bind(playlistididx, playlistId);
2776                // convert to int ourselves to save an allocation.
2777                int playorder = ((Number) values[i].get(
2778                        MediaStore.Audio.Playlists.Members.PLAY_ORDER)).intValue();
2779                helper.bind(playorderidx, playorder);
2780                helper.execute();
2781            }
2782            numInserted = len;
2783            db.setTransactionSuccessful();
2784        } finally {
2785            db.endTransaction();
2786            helper.close();
2787        }
2788        getContext().getContentResolver().notifyChange(uri, null);
2789        return numInserted;
2790    }
2791
2792    private long insertDirectory(DatabaseHelper helper, SQLiteDatabase db, String path) {
2793        if (LOCAL_LOGV) Log.v(TAG, "inserting directory " + path);
2794        ContentValues values = new ContentValues();
2795        values.put(FileColumns.FORMAT, MtpConstants.FORMAT_ASSOCIATION);
2796        values.put(FileColumns.DATA, path);
2797        values.put(FileColumns.PARENT, getParent(helper, db, path));
2798        values.put(FileColumns.STORAGE_ID, getStorageId(path));
2799        File file = new File(path);
2800        if (file.exists()) {
2801            values.put(FileColumns.DATE_MODIFIED, file.lastModified() / 1000);
2802        }
2803        helper.mNumInserts++;
2804        long rowId = db.insert("files", FileColumns.DATE_MODIFIED, values);
2805        sendObjectAdded(rowId);
2806        return rowId;
2807    }
2808
2809    private long getParent(DatabaseHelper helper, SQLiteDatabase db, String path) {
2810        int lastSlash = path.lastIndexOf('/');
2811        if (lastSlash > 0) {
2812            String parentPath = path.substring(0, lastSlash);
2813            for (int i = 0; i < mExternalStoragePaths.length; i++) {
2814                if (parentPath.equals(mExternalStoragePaths[i])) {
2815                    return 0;
2816                }
2817            }
2818            Long cid = mDirectoryCache.get(parentPath);
2819            if (cid != null) {
2820                if (LOCAL_LOGV) Log.v(TAG, "Returning cached entry for " + parentPath);
2821                return cid;
2822            }
2823
2824            String selection = MediaStore.MediaColumns.DATA + "=?";
2825            String [] selargs = { parentPath };
2826            helper.mNumQueries++;
2827            Cursor c = db.query("files", sIdOnlyColumn, selection, selargs, null, null, null);
2828            try {
2829                long id;
2830                if (c == null || c.getCount() == 0) {
2831                    // parent isn't in the database - so add it
2832                    id = insertDirectory(helper, db, parentPath);
2833                    if (LOCAL_LOGV) Log.v(TAG, "Inserted " + parentPath);
2834                } else {
2835                    if (c.getCount() > 1) {
2836                        Log.e(TAG, "more than one match for " + parentPath);
2837                    }
2838                    c.moveToFirst();
2839                    id = c.getLong(0);
2840                    if (LOCAL_LOGV) Log.v(TAG, "Queried " + parentPath);
2841                }
2842                mDirectoryCache.put(parentPath, id);
2843                return id;
2844            } finally {
2845                if (c != null) c.close();
2846            }
2847        } else {
2848            return 0;
2849        }
2850    }
2851
2852    private int getStorageId(String path) {
2853        for (int i = 0; i < mExternalStoragePaths.length; i++) {
2854            String test = mExternalStoragePaths[i];
2855            if (path.startsWith(test)) {
2856                int length = test.length();
2857                if (path.length() == length || path.charAt(length) == '/') {
2858                    return MtpStorage.getStorageId(i);
2859                }
2860            }
2861        }
2862        // default to primary storage
2863        return MtpStorage.getStorageId(0);
2864    }
2865
2866    private long insertFile(DatabaseHelper helper, Uri uri, ContentValues initialValues, int mediaType,
2867                            boolean notify, ArrayList<Long> notifyRowIds) {
2868        SQLiteDatabase db = helper.getWritableDatabase();
2869        ContentValues values = null;
2870
2871        switch (mediaType) {
2872            case FileColumns.MEDIA_TYPE_IMAGE: {
2873                values = ensureFile(helper.mInternal, initialValues, ".jpg", "DCIM/Camera");
2874
2875                values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
2876                String data = values.getAsString(MediaColumns.DATA);
2877                if (! values.containsKey(MediaColumns.DISPLAY_NAME)) {
2878                    computeDisplayName(data, values);
2879                }
2880                computeTakenTime(values);
2881                break;
2882            }
2883
2884            case FileColumns.MEDIA_TYPE_AUDIO: {
2885                // SQLite Views are read-only, so we need to deconstruct this
2886                // insert and do inserts into the underlying tables.
2887                // If doing this here turns out to be a performance bottleneck,
2888                // consider moving this to native code and using triggers on
2889                // the view.
2890                values = new ContentValues(initialValues);
2891
2892                String albumartist = values.getAsString(MediaStore.Audio.Media.ALBUM_ARTIST);
2893                String compilation = values.getAsString(MediaStore.Audio.Media.COMPILATION);
2894                values.remove(MediaStore.Audio.Media.COMPILATION);
2895
2896                // Insert the artist into the artist table and remove it from
2897                // the input values
2898                Object so = values.get("artist");
2899                String s = (so == null ? "" : so.toString());
2900                values.remove("artist");
2901                long artistRowId;
2902                HashMap<String, Long> artistCache = helper.mArtistCache;
2903                String path = values.getAsString(MediaStore.MediaColumns.DATA);
2904                synchronized(artistCache) {
2905                    Long temp = artistCache.get(s);
2906                    if (temp == null) {
2907                        artistRowId = getKeyIdForName(helper, db,
2908                                "artists", "artist_key", "artist",
2909                                s, s, path, 0, null, artistCache, uri);
2910                    } else {
2911                        artistRowId = temp.longValue();
2912                    }
2913                }
2914                String artist = s;
2915
2916                // Do the same for the album field
2917                so = values.get("album");
2918                s = (so == null ? "" : so.toString());
2919                values.remove("album");
2920                long albumRowId;
2921                HashMap<String, Long> albumCache = helper.mAlbumCache;
2922                synchronized(albumCache) {
2923                    int albumhash = 0;
2924                    if (albumartist != null) {
2925                        albumhash = albumartist.hashCode();
2926                    } else if (compilation != null && compilation.equals("1")) {
2927                        // nothing to do, hash already set
2928                    } else {
2929                        albumhash = path.substring(0, path.lastIndexOf('/')).hashCode();
2930                    }
2931                    String cacheName = s + albumhash;
2932                    Long temp = albumCache.get(cacheName);
2933                    if (temp == null) {
2934                        albumRowId = getKeyIdForName(helper, db,
2935                                "albums", "album_key", "album",
2936                                s, cacheName, path, albumhash, artist, albumCache, uri);
2937                    } else {
2938                        albumRowId = temp;
2939                    }
2940                }
2941
2942                values.put("artist_id", Integer.toString((int)artistRowId));
2943                values.put("album_id", Integer.toString((int)albumRowId));
2944                so = values.getAsString("title");
2945                s = (so == null ? "" : so.toString());
2946                values.put("title_key", MediaStore.Audio.keyFor(s));
2947                // do a final trim of the title, in case it started with the special
2948                // "sort first" character (ascii \001)
2949                values.remove("title");
2950                values.put("title", s.trim());
2951
2952                computeDisplayName(values.getAsString(MediaStore.MediaColumns.DATA), values);
2953                break;
2954            }
2955
2956            case FileColumns.MEDIA_TYPE_VIDEO: {
2957                values = ensureFile(helper.mInternal, initialValues, ".3gp", "video");
2958                String data = values.getAsString(MediaStore.MediaColumns.DATA);
2959                computeDisplayName(data, values);
2960                computeTakenTime(values);
2961                break;
2962            }
2963        }
2964
2965        if (values == null) {
2966            values = new ContentValues(initialValues);
2967        }
2968        // compute bucket_id and bucket_display_name for all files
2969        String path = values.getAsString(MediaStore.MediaColumns.DATA);
2970        if (path != null) {
2971            computeBucketValues(path, values);
2972        }
2973        values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
2974
2975        long rowId = 0;
2976        Integer i = values.getAsInteger(
2977                MediaStore.MediaColumns.MEDIA_SCANNER_NEW_OBJECT_ID);
2978        if (i != null) {
2979            rowId = i.intValue();
2980            values = new ContentValues(values);
2981            values.remove(MediaStore.MediaColumns.MEDIA_SCANNER_NEW_OBJECT_ID);
2982        }
2983
2984        String title = values.getAsString(MediaStore.MediaColumns.TITLE);
2985        if (title == null && path != null) {
2986            title = MediaFile.getFileTitle(path);
2987        }
2988        values.put(FileColumns.TITLE, title);
2989
2990        String mimeType = values.getAsString(MediaStore.MediaColumns.MIME_TYPE);
2991        Integer formatObject = values.getAsInteger(FileColumns.FORMAT);
2992        int format = (formatObject == null ? 0 : formatObject.intValue());
2993        if (format == 0) {
2994            if (TextUtils.isEmpty(path)) {
2995                // special case device created playlists
2996                if (mediaType == FileColumns.MEDIA_TYPE_PLAYLIST) {
2997                    values.put(FileColumns.FORMAT, MtpConstants.FORMAT_ABSTRACT_AV_PLAYLIST);
2998                    // create a file path for the benefit of MTP
2999                    path = mExternalStoragePaths[0]
3000                            + "/Playlists/" + values.getAsString(Audio.Playlists.NAME);
3001                    values.put(MediaStore.MediaColumns.DATA, path);
3002                    values.put(FileColumns.PARENT, getParent(helper, db, path));
3003                } else {
3004                    Log.e(TAG, "path is empty in insertFile()");
3005                }
3006            } else {
3007                format = MediaFile.getFormatCode(path, mimeType);
3008            }
3009        }
3010        if (format != 0) {
3011            values.put(FileColumns.FORMAT, format);
3012            if (mimeType == null) {
3013                mimeType = MediaFile.getMimeTypeForFormatCode(format);
3014            }
3015        }
3016
3017        if (mimeType == null && path != null) {
3018            mimeType = MediaFile.getMimeTypeForFile(path);
3019        }
3020        if (mimeType != null) {
3021            values.put(FileColumns.MIME_TYPE, mimeType);
3022
3023            if (mediaType == FileColumns.MEDIA_TYPE_NONE && !MediaScanner.isNoMediaPath(path)) {
3024                int fileType = MediaFile.getFileTypeForMimeType(mimeType);
3025                if (MediaFile.isAudioFileType(fileType)) {
3026                    mediaType = FileColumns.MEDIA_TYPE_AUDIO;
3027                } else if (MediaFile.isVideoFileType(fileType)) {
3028                    mediaType = FileColumns.MEDIA_TYPE_VIDEO;
3029                } else if (MediaFile.isImageFileType(fileType)) {
3030                    mediaType = FileColumns.MEDIA_TYPE_IMAGE;
3031                } else if (MediaFile.isPlayListFileType(fileType)) {
3032                    mediaType = FileColumns.MEDIA_TYPE_PLAYLIST;
3033                }
3034            }
3035        }
3036        values.put(FileColumns.MEDIA_TYPE, mediaType);
3037
3038        if (rowId == 0) {
3039            if (mediaType == FileColumns.MEDIA_TYPE_PLAYLIST) {
3040                String name = values.getAsString(Audio.Playlists.NAME);
3041                if (name == null && path == null) {
3042                    // MediaScanner will compute the name from the path if we have one
3043                    throw new IllegalArgumentException(
3044                            "no name was provided when inserting abstract playlist");
3045                }
3046            } else {
3047                if (path == null) {
3048                    // path might be null for playlists created on the device
3049                    // or transfered via MTP
3050                    throw new IllegalArgumentException(
3051                            "no path was provided when inserting new file");
3052                }
3053            }
3054
3055            // make sure modification date and size are set
3056            if (path != null) {
3057                File file = new File(path);
3058                if (file.exists()) {
3059                    values.put(FileColumns.DATE_MODIFIED, file.lastModified() / 1000);
3060                    if (!values.containsKey(FileColumns.SIZE)) {
3061                        values.put(FileColumns.SIZE, file.length());
3062                    }
3063                }
3064            }
3065
3066            Long parent = values.getAsLong(FileColumns.PARENT);
3067            if (parent == null) {
3068                if (path != null) {
3069                    long parentId = getParent(helper, db, path);
3070                    values.put(FileColumns.PARENT, parentId);
3071                }
3072            }
3073            Integer storage = values.getAsInteger(FileColumns.STORAGE_ID);
3074            if (storage == null) {
3075                int storageId = getStorageId(path);
3076                values.put(FileColumns.STORAGE_ID, storageId);
3077            }
3078
3079            helper.mNumInserts++;
3080            rowId = db.insert("files", FileColumns.DATE_MODIFIED, values);
3081            if (LOCAL_LOGV) Log.v(TAG, "insertFile: values=" + values + " returned: " + rowId);
3082
3083            if (rowId != -1 && notify) {
3084                notifyRowIds.add(rowId);
3085            }
3086        } else {
3087            helper.mNumUpdates++;
3088            db.update("files", values, FileColumns._ID + "=?",
3089                    new String[] { Long.toString(rowId) });
3090        }
3091        if (format == MtpConstants.FORMAT_ASSOCIATION) {
3092            mDirectoryCache.put(path, rowId);
3093        }
3094
3095        return rowId;
3096    }
3097
3098    private Cursor getObjectReferences(DatabaseHelper helper, SQLiteDatabase db, int handle) {
3099        helper.mNumQueries++;
3100        Cursor c = db.query("files", sMediaTableColumns, "_id=?",
3101                new String[] {  Integer.toString(handle) },
3102                null, null, null);
3103        try {
3104            if (c != null && c.moveToNext()) {
3105                long playlistId = c.getLong(0);
3106                int mediaType = c.getInt(1);
3107                if (mediaType != FileColumns.MEDIA_TYPE_PLAYLIST) {
3108                    // we only support object references for playlist objects
3109                    return null;
3110                }
3111                helper.mNumQueries++;
3112                return db.rawQuery(OBJECT_REFERENCES_QUERY,
3113                        new String[] { Long.toString(playlistId) } );
3114            }
3115        } finally {
3116            if (c != null) {
3117                c.close();
3118            }
3119        }
3120        return null;
3121    }
3122
3123    private int setObjectReferences(DatabaseHelper helper, SQLiteDatabase db,
3124            int handle, ContentValues values[]) {
3125        // first look up the media table and media ID for the object
3126        long playlistId = 0;
3127        helper.mNumQueries++;
3128        Cursor c = db.query("files", sMediaTableColumns, "_id=?",
3129                new String[] {  Integer.toString(handle) },
3130                null, null, null);
3131        try {
3132            if (c != null && c.moveToNext()) {
3133                int mediaType = c.getInt(1);
3134                if (mediaType != FileColumns.MEDIA_TYPE_PLAYLIST) {
3135                    // we only support object references for playlist objects
3136                    return 0;
3137                }
3138                playlistId = c.getLong(0);
3139            }
3140        } finally {
3141            if (c != null) {
3142                c.close();
3143            }
3144        }
3145        if (playlistId == 0) {
3146            return 0;
3147        }
3148
3149        // next delete any existing entries
3150        helper.mNumDeletes++;
3151        db.delete("audio_playlists_map", "playlist_id=?",
3152                new String[] { Long.toString(playlistId) });
3153
3154        // finally add the new entries
3155        int count = values.length;
3156        int added = 0;
3157        ContentValues[] valuesList = new ContentValues[count];
3158        for (int i = 0; i < count; i++) {
3159            // convert object ID to audio ID
3160            long audioId = 0;
3161            long objectId = values[i].getAsLong(MediaStore.MediaColumns._ID);
3162            helper.mNumQueries++;
3163            c = db.query("files", sMediaTableColumns, "_id=?",
3164                    new String[] {  Long.toString(objectId) },
3165                    null, null, null);
3166            try {
3167                if (c != null && c.moveToNext()) {
3168                    int mediaType = c.getInt(1);
3169                    if (mediaType != FileColumns.MEDIA_TYPE_AUDIO) {
3170                        // we only allow audio files in playlists, so skip
3171                        continue;
3172                    }
3173                    audioId = c.getLong(0);
3174                }
3175            } finally {
3176                if (c != null) {
3177                    c.close();
3178                }
3179            }
3180            if (audioId != 0) {
3181                ContentValues v = new ContentValues();
3182                v.put(MediaStore.Audio.Playlists.Members.PLAYLIST_ID, playlistId);
3183                v.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, audioId);
3184                v.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, added);
3185                valuesList[added++] = v;
3186            }
3187        }
3188        if (added < count) {
3189            // we weren't able to find everything on the list, so lets resize the array
3190            // and pass what we have.
3191            ContentValues[] newValues = new ContentValues[added];
3192            System.arraycopy(valuesList, 0, newValues, 0, added);
3193            valuesList = newValues;
3194        }
3195        return playlistBulkInsert(db,
3196                Audio.Playlists.Members.getContentUri(EXTERNAL_VOLUME, playlistId),
3197                valuesList);
3198    }
3199
3200    private static final String[] GENRE_LOOKUP_PROJECTION = new String[] {
3201            Audio.Genres._ID, // 0
3202            Audio.Genres.NAME, // 1
3203    };
3204
3205    private void updateGenre(long rowId, String genre) {
3206        Uri uri = null;
3207        Cursor cursor = null;
3208        Uri genresUri = MediaStore.Audio.Genres.getContentUri("external");
3209        try {
3210            // see if the genre already exists
3211            cursor = query(genresUri, GENRE_LOOKUP_PROJECTION, MediaStore.Audio.Genres.NAME + "=?",
3212                            new String[] { genre }, null);
3213            if (cursor == null || cursor.getCount() == 0) {
3214                // genre does not exist, so create the genre in the genre table
3215                ContentValues values = new ContentValues();
3216                values.put(MediaStore.Audio.Genres.NAME, genre);
3217                uri = insert(genresUri, values);
3218            } else {
3219                // genre already exists, so compute its Uri
3220                cursor.moveToNext();
3221                uri = ContentUris.withAppendedId(genresUri, cursor.getLong(0));
3222            }
3223            if (uri != null) {
3224                uri = Uri.withAppendedPath(uri, MediaStore.Audio.Genres.Members.CONTENT_DIRECTORY);
3225            }
3226        } finally {
3227            // release the cursor if it exists
3228            if (cursor != null) {
3229                cursor.close();
3230            }
3231        }
3232
3233        if (uri != null) {
3234            // add entry to audio_genre_map
3235            ContentValues values = new ContentValues();
3236            values.put(MediaStore.Audio.Genres.Members.AUDIO_ID, Long.valueOf(rowId));
3237            insert(uri, values);
3238        }
3239    }
3240
3241    private Uri insertInternal(Uri uri, int match, ContentValues initialValues,
3242                               ArrayList<Long> notifyRowIds) {
3243        long rowId;
3244
3245        if (LOCAL_LOGV) Log.v(TAG, "insertInternal: "+uri+", initValues="+initialValues);
3246        // handle MEDIA_SCANNER before calling getDatabaseForUri()
3247        if (match == MEDIA_SCANNER) {
3248            mMediaScannerVolume = initialValues.getAsString(MediaStore.MEDIA_SCANNER_VOLUME);
3249            DatabaseHelper database = getDatabaseForUri(
3250                    Uri.parse("content://media/" + mMediaScannerVolume + "/audio"));
3251            if (database == null) {
3252                Log.w(TAG, "no database for scanned volume " + mMediaScannerVolume);
3253            } else {
3254                database.mScanStartTime = SystemClock.currentTimeMicro();
3255            }
3256            return MediaStore.getMediaScannerUri();
3257        }
3258
3259        String genre = null;
3260        String path = null;
3261        if (initialValues != null) {
3262            genre = initialValues.getAsString(Audio.AudioColumns.GENRE);
3263            initialValues.remove(Audio.AudioColumns.GENRE);
3264            path = initialValues.getAsString(MediaStore.MediaColumns.DATA);
3265        }
3266
3267
3268        Uri newUri = null;
3269        DatabaseHelper helper = getDatabaseForUri(uri);
3270        if (helper == null && match != VOLUMES && match != MTP_CONNECTED) {
3271            throw new UnsupportedOperationException(
3272                    "Unknown URI: " + uri);
3273        }
3274
3275        SQLiteDatabase db = ((match == VOLUMES || match == MTP_CONNECTED) ? null
3276                : helper.getWritableDatabase());
3277
3278        switch (match) {
3279            case IMAGES_MEDIA: {
3280                rowId = insertFile(helper, uri, initialValues,
3281                        FileColumns.MEDIA_TYPE_IMAGE, true, notifyRowIds);
3282                if (rowId > 0) {
3283                    newUri = ContentUris.withAppendedId(
3284                            Images.Media.getContentUri(uri.getPathSegments().get(0)), rowId);
3285                }
3286                break;
3287            }
3288
3289            // This will be triggered by requestMediaThumbnail (see getThumbnailUri)
3290            case IMAGES_THUMBNAILS: {
3291                ContentValues values = ensureFile(helper.mInternal, initialValues, ".jpg",
3292                        "DCIM/.thumbnails");
3293                helper.mNumInserts++;
3294                rowId = db.insert("thumbnails", "name", values);
3295                if (rowId > 0) {
3296                    newUri = ContentUris.withAppendedId(Images.Thumbnails.
3297                            getContentUri(uri.getPathSegments().get(0)), rowId);
3298                }
3299                break;
3300            }
3301
3302            // This is currently only used by MICRO_KIND video thumbnail (see getThumbnailUri)
3303            case VIDEO_THUMBNAILS: {
3304                ContentValues values = ensureFile(helper.mInternal, initialValues, ".jpg",
3305                        "DCIM/.thumbnails");
3306                helper.mNumInserts++;
3307                rowId = db.insert("videothumbnails", "name", values);
3308                if (rowId > 0) {
3309                    newUri = ContentUris.withAppendedId(Video.Thumbnails.
3310                            getContentUri(uri.getPathSegments().get(0)), rowId);
3311                }
3312                break;
3313            }
3314
3315            case AUDIO_MEDIA: {
3316                rowId = insertFile(helper, uri, initialValues,
3317                        FileColumns.MEDIA_TYPE_AUDIO, true, notifyRowIds);
3318                if (rowId > 0) {
3319                    newUri = ContentUris.withAppendedId(Audio.Media.getContentUri(uri.getPathSegments().get(0)), rowId);
3320                    if (genre != null) {
3321                        updateGenre(rowId, genre);
3322                    }
3323                }
3324                break;
3325            }
3326
3327            case AUDIO_MEDIA_ID_GENRES: {
3328                Long audioId = Long.parseLong(uri.getPathSegments().get(2));
3329                ContentValues values = new ContentValues(initialValues);
3330                values.put(Audio.Genres.Members.AUDIO_ID, audioId);
3331                helper.mNumInserts++;
3332                rowId = db.insert("audio_genres_map", "genre_id", values);
3333                if (rowId > 0) {
3334                    newUri = ContentUris.withAppendedId(uri, rowId);
3335                }
3336                break;
3337            }
3338
3339            case AUDIO_MEDIA_ID_PLAYLISTS: {
3340                Long audioId = Long.parseLong(uri.getPathSegments().get(2));
3341                ContentValues values = new ContentValues(initialValues);
3342                values.put(Audio.Playlists.Members.AUDIO_ID, audioId);
3343                helper.mNumInserts++;
3344                rowId = db.insert("audio_playlists_map", "playlist_id",
3345                        values);
3346                if (rowId > 0) {
3347                    newUri = ContentUris.withAppendedId(uri, rowId);
3348                }
3349                break;
3350            }
3351
3352            case AUDIO_GENRES: {
3353                helper.mNumInserts++;
3354                rowId = db.insert("audio_genres", "audio_id", initialValues);
3355                if (rowId > 0) {
3356                    newUri = ContentUris.withAppendedId(Audio.Genres.getContentUri(uri.getPathSegments().get(0)), rowId);
3357                }
3358                break;
3359            }
3360
3361            case AUDIO_GENRES_ID_MEMBERS: {
3362                Long genreId = Long.parseLong(uri.getPathSegments().get(3));
3363                ContentValues values = new ContentValues(initialValues);
3364                values.put(Audio.Genres.Members.GENRE_ID, genreId);
3365                helper.mNumInserts++;
3366                rowId = db.insert("audio_genres_map", "genre_id", values);
3367                if (rowId > 0) {
3368                    newUri = ContentUris.withAppendedId(uri, rowId);
3369                }
3370                break;
3371            }
3372
3373            case AUDIO_PLAYLISTS: {
3374                ContentValues values = new ContentValues(initialValues);
3375                values.put(MediaStore.Audio.Playlists.DATE_ADDED, System.currentTimeMillis() / 1000);
3376                rowId = insertFile(helper, uri, values,
3377                        FileColumns.MEDIA_TYPE_PLAYLIST, true, notifyRowIds);
3378                if (rowId > 0) {
3379                    newUri = ContentUris.withAppendedId(Audio.Playlists.getContentUri(uri.getPathSegments().get(0)), rowId);
3380                }
3381                break;
3382            }
3383
3384            case AUDIO_PLAYLISTS_ID:
3385            case AUDIO_PLAYLISTS_ID_MEMBERS: {
3386                Long playlistId = Long.parseLong(uri.getPathSegments().get(3));
3387                ContentValues values = new ContentValues(initialValues);
3388                values.put(Audio.Playlists.Members.PLAYLIST_ID, playlistId);
3389                helper.mNumInserts++;
3390                rowId = db.insert("audio_playlists_map", "playlist_id", values);
3391                if (rowId > 0) {
3392                    newUri = ContentUris.withAppendedId(uri, rowId);
3393                }
3394                break;
3395            }
3396
3397            case VIDEO_MEDIA: {
3398                rowId = insertFile(helper, uri, initialValues,
3399                        FileColumns.MEDIA_TYPE_VIDEO, true, notifyRowIds);
3400                if (rowId > 0) {
3401                    newUri = ContentUris.withAppendedId(Video.Media.getContentUri(
3402                            uri.getPathSegments().get(0)), rowId);
3403                }
3404                break;
3405            }
3406
3407            case AUDIO_ALBUMART: {
3408                if (helper.mInternal) {
3409                    throw new UnsupportedOperationException("no internal album art allowed");
3410                }
3411                ContentValues values = null;
3412                try {
3413                    values = ensureFile(false, initialValues, "", ALBUM_THUMB_FOLDER);
3414                } catch (IllegalStateException ex) {
3415                    // probably no more room to store albumthumbs
3416                    values = initialValues;
3417                }
3418                helper.mNumInserts++;
3419                rowId = db.insert("album_art", MediaStore.MediaColumns.DATA, values);
3420                if (rowId > 0) {
3421                    newUri = ContentUris.withAppendedId(uri, rowId);
3422                }
3423                break;
3424            }
3425
3426            case VOLUMES:
3427            {
3428                String name = initialValues.getAsString("name");
3429                Uri attachedVolume = attachVolume(name);
3430                if (mMediaScannerVolume != null && mMediaScannerVolume.equals(name)) {
3431                    DatabaseHelper dbhelper = getDatabaseForUri(attachedVolume);
3432                    if (dbhelper == null) {
3433                        Log.e(TAG, "no database for attached volume " + attachedVolume);
3434                    } else {
3435                        dbhelper.mScanStartTime = SystemClock.currentTimeMicro();
3436                    }
3437                }
3438                return attachedVolume;
3439            }
3440
3441            case MTP_CONNECTED:
3442                synchronized (mMtpServiceConnection) {
3443                    if (mMtpService == null) {
3444                        Context context = getContext();
3445                        // MTP is connected, so grab a connection to MtpService
3446                        context.bindService(new Intent(context, MtpService.class),
3447                                mMtpServiceConnection, Context.BIND_AUTO_CREATE);
3448                    }
3449                }
3450                break;
3451
3452            case FILES:
3453                rowId = insertFile(helper, uri, initialValues,
3454                        FileColumns.MEDIA_TYPE_NONE, true, notifyRowIds);
3455                if (rowId > 0) {
3456                    newUri = Files.getContentUri(uri.getPathSegments().get(0), rowId);
3457                }
3458                break;
3459
3460            case MTP_OBJECTS:
3461                // We don't send a notification if the insert originated from MTP
3462                rowId = insertFile(helper, uri, initialValues,
3463                        FileColumns.MEDIA_TYPE_NONE, false, notifyRowIds);
3464                if (rowId > 0) {
3465                    newUri = Files.getMtpObjectsUri(uri.getPathSegments().get(0), rowId);
3466                }
3467                break;
3468
3469            default:
3470                throw new UnsupportedOperationException("Invalid URI " + uri);
3471        }
3472
3473        if (path != null && path.toLowerCase(Locale.US).endsWith("/.nomedia")) {
3474            // need to set the media_type of all the files below this folder to 0
3475            processNewNoMediaPath(helper, db, path);
3476        }
3477        return newUri;
3478    }
3479
3480    /*
3481     * Sets the media type of all files below the newly added .nomedia file or
3482     * hidden folder to 0, so the entries no longer appear in e.g. the audio and
3483     * images views.
3484     *
3485     * @param path The path to the new .nomedia file or hidden directory
3486     */
3487    private void processNewNoMediaPath(final DatabaseHelper helper, final SQLiteDatabase db,
3488            final String path) {
3489        final File nomedia = new File(path);
3490        if (nomedia.exists()) {
3491            hidePath(helper, db, path);
3492        } else {
3493            // File doesn't exist. Try again in a little while.
3494            // XXX there's probably a better way of doing this
3495            new Thread(new Runnable() {
3496                @Override
3497                public void run() {
3498                    SystemClock.sleep(2000);
3499                    if (nomedia.exists()) {
3500                        hidePath(helper, db, path);
3501                    } else {
3502                        Log.w(TAG, "does not exist: " + path, new Exception());
3503                    }
3504                }}).start();
3505        }
3506    }
3507
3508    private void hidePath(DatabaseHelper helper, SQLiteDatabase db, String path) {
3509        File nomedia = new File(path);
3510        String hiddenroot = nomedia.isDirectory() ? path : nomedia.getParent();
3511        ContentValues mediatype = new ContentValues();
3512        mediatype.put("media_type", 0);
3513        int numrows = db.update("files", mediatype,
3514                "_data >= ? AND _data < ?",
3515                new String[] { hiddenroot  + "/", hiddenroot + "0"});
3516        helper.mNumUpdates += numrows;
3517        ContentResolver res = getContext().getContentResolver();
3518        res.notifyChange(Uri.parse("content://media/"), null);
3519    }
3520
3521    /*
3522     * Rescan files for missing metadata and set their type accordingly.
3523     * There is code for detecting the removal of a nomedia file or renaming of
3524     * a directory from hidden to non-hidden in the MediaScanner and MtpDatabase,
3525     * both of which call here.
3526     */
3527    private void processRemovedNoMediaPath(final String path) {
3528        final DatabaseHelper helper;
3529        if (path.startsWith(mExternalStoragePaths[0])) {
3530            helper = getDatabaseForUri(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
3531        } else {
3532            helper = getDatabaseForUri(MediaStore.Audio.Media.INTERNAL_CONTENT_URI);
3533        }
3534        SQLiteDatabase db = helper.getWritableDatabase();
3535        new ScannerClient(getContext(), db, path);
3536    }
3537
3538    private static final class ScannerClient implements MediaScannerConnectionClient {
3539        String mPath = null;
3540        MediaScannerConnection mScannerConnection;
3541        SQLiteDatabase mDb;
3542
3543        public ScannerClient(Context context, SQLiteDatabase db, String path) {
3544            mDb = db;
3545            mPath = path;
3546            mScannerConnection = new MediaScannerConnection(context, this);
3547            mScannerConnection.connect();
3548        }
3549
3550        @Override
3551        public void onMediaScannerConnected() {
3552            Cursor c = mDb.query("files", openFileColumns,
3553                    "_data >= ? AND _data < ?",
3554                    new String[] { mPath + "/", mPath + "0"},
3555                    null, null, null);
3556            while (c.moveToNext()) {
3557                String d = c.getString(0);
3558                File f = new File(d);
3559                if (f.isFile()) {
3560                    mScannerConnection.scanFile(d, null);
3561                }
3562            }
3563            mScannerConnection.disconnect();
3564            c.close();
3565        }
3566
3567        @Override
3568        public void onScanCompleted(String path, Uri uri) {
3569        }
3570    }
3571
3572    @Override
3573    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
3574                throws OperationApplicationException {
3575
3576        // The operations array provides no overall information about the URI(s) being operated
3577        // on, so begin a transaction for ALL of the databases.
3578        DatabaseHelper ihelper = getDatabaseForUri(MediaStore.Audio.Media.INTERNAL_CONTENT_URI);
3579        DatabaseHelper ehelper = getDatabaseForUri(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
3580        SQLiteDatabase idb = ihelper.getWritableDatabase();
3581        idb.beginTransaction();
3582        SQLiteDatabase edb = null;
3583        if (ehelper != null) {
3584            edb = ehelper.getWritableDatabase();
3585            edb.beginTransaction();
3586        }
3587        try {
3588            ContentProviderResult[] result = super.applyBatch(operations);
3589            idb.setTransactionSuccessful();
3590            if (edb != null) {
3591                edb.setTransactionSuccessful();
3592            }
3593            // Rather than sending targeted change notifications for every Uri
3594            // affected by the batch operation, just invalidate the entire internal
3595            // and external name space.
3596            ContentResolver res = getContext().getContentResolver();
3597            res.notifyChange(Uri.parse("content://media/"), null);
3598            return result;
3599        } finally {
3600            idb.endTransaction();
3601            if (edb != null) {
3602                edb.endTransaction();
3603            }
3604        }
3605    }
3606
3607
3608    private MediaThumbRequest requestMediaThumbnail(String path, Uri uri, int priority, long magic) {
3609        synchronized (mMediaThumbQueue) {
3610            MediaThumbRequest req = null;
3611            try {
3612                req = new MediaThumbRequest(
3613                        getContext().getContentResolver(), path, uri, priority, magic);
3614                mMediaThumbQueue.add(req);
3615                // Trigger the handler.
3616                Message msg = mThumbHandler.obtainMessage(IMAGE_THUMB);
3617                msg.sendToTarget();
3618            } catch (Throwable t) {
3619                Log.w(TAG, t);
3620            }
3621            return req;
3622        }
3623    }
3624
3625    private String generateFileName(boolean internal, String preferredExtension, String directoryName)
3626    {
3627        // create a random file
3628        String name = String.valueOf(System.currentTimeMillis());
3629
3630        if (internal) {
3631            throw new UnsupportedOperationException("Writing to internal storage is not supported.");
3632//            return Environment.getDataDirectory()
3633//                + "/" + directoryName + "/" + name + preferredExtension;
3634        } else {
3635            return mExternalStoragePaths[0] + "/" + directoryName + "/" + name + preferredExtension;
3636        }
3637    }
3638
3639    private boolean ensureFileExists(String path) {
3640        File file = new File(path);
3641        if (file.exists()) {
3642            return true;
3643        } else {
3644            // we will not attempt to create the first directory in the path
3645            // (for example, do not create /sdcard if the SD card is not mounted)
3646            int secondSlash = path.indexOf('/', 1);
3647            if (secondSlash < 1) return false;
3648            String directoryPath = path.substring(0, secondSlash);
3649            File directory = new File(directoryPath);
3650            if (!directory.exists())
3651                return false;
3652            file.getParentFile().mkdirs();
3653            try {
3654                return file.createNewFile();
3655            } catch(IOException ioe) {
3656                Log.e(TAG, "File creation failed", ioe);
3657            }
3658            return false;
3659        }
3660    }
3661
3662    private static final class GetTableAndWhereOutParameter {
3663        public String table;
3664        public String where;
3665    }
3666
3667    static final GetTableAndWhereOutParameter sGetTableAndWhereParam =
3668            new GetTableAndWhereOutParameter();
3669
3670    private void getTableAndWhere(Uri uri, int match, String userWhere,
3671            GetTableAndWhereOutParameter out) {
3672        String where = null;
3673        switch (match) {
3674            case IMAGES_MEDIA:
3675                out.table = "files";
3676                where = FileColumns.MEDIA_TYPE + "=" + FileColumns.MEDIA_TYPE_IMAGE;
3677                break;
3678
3679            case IMAGES_MEDIA_ID:
3680                out.table = "files";
3681                where = "_id = " + uri.getPathSegments().get(3);
3682                break;
3683
3684            case IMAGES_THUMBNAILS_ID:
3685                where = "_id=" + uri.getPathSegments().get(3);
3686            case IMAGES_THUMBNAILS:
3687                out.table = "thumbnails";
3688                break;
3689
3690            case AUDIO_MEDIA:
3691                out.table = "files";
3692                where = FileColumns.MEDIA_TYPE + "=" + FileColumns.MEDIA_TYPE_AUDIO;
3693                break;
3694
3695            case AUDIO_MEDIA_ID:
3696                out.table = "files";
3697                where = "_id=" + uri.getPathSegments().get(3);
3698                break;
3699
3700            case AUDIO_MEDIA_ID_GENRES:
3701                out.table = "audio_genres";
3702                where = "audio_id=" + uri.getPathSegments().get(3);
3703                break;
3704
3705            case AUDIO_MEDIA_ID_GENRES_ID:
3706                out.table = "audio_genres";
3707                where = "audio_id=" + uri.getPathSegments().get(3) +
3708                        " AND genre_id=" + uri.getPathSegments().get(5);
3709               break;
3710
3711            case AUDIO_MEDIA_ID_PLAYLISTS:
3712                out.table = "audio_playlists";
3713                where = "audio_id=" + uri.getPathSegments().get(3);
3714                break;
3715
3716            case AUDIO_MEDIA_ID_PLAYLISTS_ID:
3717                out.table = "audio_playlists";
3718                where = "audio_id=" + uri.getPathSegments().get(3) +
3719                        " AND playlists_id=" + uri.getPathSegments().get(5);
3720                break;
3721
3722            case AUDIO_GENRES:
3723                out.table = "audio_genres";
3724                break;
3725
3726            case AUDIO_GENRES_ID:
3727                out.table = "audio_genres";
3728                where = "_id=" + uri.getPathSegments().get(3);
3729                break;
3730
3731            case AUDIO_GENRES_ID_MEMBERS:
3732                out.table = "audio_genres";
3733                where = "genre_id=" + uri.getPathSegments().get(3);
3734                break;
3735
3736            case AUDIO_PLAYLISTS:
3737                out.table = "files";
3738                where = FileColumns.MEDIA_TYPE + "=" + FileColumns.MEDIA_TYPE_PLAYLIST;
3739                break;
3740
3741            case AUDIO_PLAYLISTS_ID:
3742                out.table = "files";
3743                where = "_id=" + uri.getPathSegments().get(3);
3744                break;
3745
3746            case AUDIO_PLAYLISTS_ID_MEMBERS:
3747                out.table = "audio_playlists_map";
3748                where = "playlist_id=" + uri.getPathSegments().get(3);
3749                break;
3750
3751            case AUDIO_PLAYLISTS_ID_MEMBERS_ID:
3752                out.table = "audio_playlists_map";
3753                where = "playlist_id=" + uri.getPathSegments().get(3) +
3754                        " AND _id=" + uri.getPathSegments().get(5);
3755                break;
3756
3757            case AUDIO_ALBUMART_ID:
3758                out.table = "album_art";
3759                where = "album_id=" + uri.getPathSegments().get(3);
3760                break;
3761
3762            case VIDEO_MEDIA:
3763                out.table = "files";
3764                where = FileColumns.MEDIA_TYPE + "=" + FileColumns.MEDIA_TYPE_VIDEO;
3765                break;
3766
3767            case VIDEO_MEDIA_ID:
3768                out.table = "files";
3769                where = "_id=" + uri.getPathSegments().get(3);
3770                break;
3771
3772            case VIDEO_THUMBNAILS_ID:
3773                where = "_id=" + uri.getPathSegments().get(3);
3774            case VIDEO_THUMBNAILS:
3775                out.table = "videothumbnails";
3776                break;
3777
3778            case FILES_ID:
3779            case MTP_OBJECTS_ID:
3780                where = "_id=" + uri.getPathSegments().get(2);
3781            case FILES:
3782            case MTP_OBJECTS:
3783                out.table = "files";
3784                break;
3785
3786            default:
3787                throw new UnsupportedOperationException(
3788                        "Unknown or unsupported URL: " + uri.toString());
3789        }
3790
3791        // Add in the user requested WHERE clause, if needed
3792        if (!TextUtils.isEmpty(userWhere)) {
3793            if (!TextUtils.isEmpty(where)) {
3794                out.where = where + " AND (" + userWhere + ")";
3795            } else {
3796                out.where = userWhere;
3797            }
3798        } else {
3799            out.where = where;
3800        }
3801    }
3802
3803    @Override
3804    public int delete(Uri uri, String userWhere, String[] whereArgs) {
3805        int count;
3806        int match = URI_MATCHER.match(uri);
3807
3808        // handle MEDIA_SCANNER before calling getDatabaseForUri()
3809        if (match == MEDIA_SCANNER) {
3810            if (mMediaScannerVolume == null) {
3811                return 0;
3812            }
3813            DatabaseHelper database = getDatabaseForUri(
3814                    Uri.parse("content://media/" + mMediaScannerVolume + "/audio"));
3815            if (database == null) {
3816                Log.w(TAG, "no database for scanned volume " + mMediaScannerVolume);
3817            } else {
3818                database.mScanStopTime = SystemClock.currentTimeMicro();
3819                String msg = dump(database, false);
3820                logToDb(database.getWritableDatabase(), msg);
3821            }
3822            mMediaScannerVolume = null;
3823            return 1;
3824        }
3825
3826        if (match == VOLUMES_ID) {
3827            detachVolume(uri);
3828            count = 1;
3829        } else if (match == MTP_CONNECTED) {
3830            synchronized (mMtpServiceConnection) {
3831                if (mMtpService != null) {
3832                    // MTP has disconnected, so release our connection to MtpService
3833                    getContext().unbindService(mMtpServiceConnection);
3834                    count = 1;
3835                    // mMtpServiceConnection.onServiceDisconnected might not get called,
3836                    // so set mMtpService = null here
3837                    mMtpService = null;
3838                } else {
3839                    count = 0;
3840                }
3841            }
3842        } else {
3843            DatabaseHelper database = getDatabaseForUri(uri);
3844            if (database == null) {
3845                throw new UnsupportedOperationException(
3846                        "Unknown URI: " + uri + " match: " + match);
3847            }
3848            database.mNumDeletes++;
3849            SQLiteDatabase db = database.getWritableDatabase();
3850
3851            synchronized (sGetTableAndWhereParam) {
3852                getTableAndWhere(uri, match, userWhere, sGetTableAndWhereParam);
3853
3854                if (sGetTableAndWhereParam.table.equals("files")) {
3855                    String deleteparam = uri.getQueryParameter(MediaStore.PARAM_DELETE_DATA);
3856                    if (deleteparam == null || ! deleteparam.equals("false")) {
3857                        database.mNumQueries++;
3858                        Cursor c = db.query(sGetTableAndWhereParam.table,
3859                                sMediaTypeDataId,
3860                                sGetTableAndWhereParam.where, whereArgs, null, null, null);
3861                        String [] idvalue = new String[] { "" };
3862                        String [] playlistvalues = new String[] { "", "" };
3863                        while (c.moveToNext()) {
3864                            int mediatype = c.getInt(0);
3865                            if (mediatype == FileColumns.MEDIA_TYPE_IMAGE) {
3866                                try {
3867                                    Libcore.os.remove(c.getString(1));
3868                                    idvalue[0] =  "" + c.getLong(2);
3869                                    database.mNumQueries++;
3870                                    Cursor cc = db.query("thumbnails", sDataOnlyColumn,
3871                                            "image_id=?", idvalue, null, null, null);
3872                                    while (cc.moveToNext()) {
3873                                        Libcore.os.remove(cc.getString(0));
3874                                    }
3875                                    cc.close();
3876                                    database.mNumDeletes++;
3877                                    db.delete("thumbnails", "image_id=?", idvalue);
3878                                } catch (ErrnoException e) {
3879                                }
3880                            } else if (mediatype == FileColumns.MEDIA_TYPE_VIDEO) {
3881                                try {
3882                                    Libcore.os.remove(c.getString(1));
3883                                } catch (ErrnoException e) {
3884                                }
3885                            } else if (mediatype == FileColumns.MEDIA_TYPE_AUDIO) {
3886                                if (!database.mInternal) {
3887                                    idvalue[0] =  "" + c.getLong(2);
3888                                    database.mNumDeletes += 2; // also count the one below
3889                                    db.delete("audio_genres_map", "audio_id=?", idvalue);
3890                                    // for each playlist that the item appears in, move
3891                                    // all the items behind it forward by one
3892                                    Cursor cc = db.query("audio_playlists_map",
3893                                            sPlaylistIdPlayOrder,
3894                                            "audio_id=?", idvalue, null, null, null);
3895                                    while (cc.moveToNext()) {
3896                                        playlistvalues[0] = "" + cc.getLong(0);
3897                                        playlistvalues[1] = "" + cc.getInt(1);
3898                                        database.mNumUpdates++;
3899                                        db.execSQL("UPDATE audio_playlists_map" +
3900                                                " SET play_order=play_order-1" +
3901                                                " WHERE playlist_id=? AND play_order>?",
3902                                                playlistvalues);
3903                                    }
3904                                    cc.close();
3905                                    db.delete("audio_playlists_map", "audio_id=?", idvalue);
3906                                }
3907                            } else if (mediatype == FileColumns.MEDIA_TYPE_PLAYLIST) {
3908                                // TODO, maybe: remove the audio_playlists_cleanup trigger and implement
3909                                // it functionality here (clean up the playlist map)
3910                            }
3911                        }
3912                        c.close();
3913                    }
3914                }
3915
3916                switch (match) {
3917                    case MTP_OBJECTS:
3918                    case MTP_OBJECTS_ID:
3919                        try {
3920                            // don't send objectRemoved event since this originated from MTP
3921                            mDisableMtpObjectCallbacks = true;
3922                            database.mNumDeletes++;
3923                            count = db.delete("files", sGetTableAndWhereParam.where, whereArgs);
3924                        } finally {
3925                            mDisableMtpObjectCallbacks = false;
3926                        }
3927                        break;
3928                    case AUDIO_GENRES_ID_MEMBERS:
3929                        database.mNumDeletes++;
3930                        count = db.delete("audio_genres_map",
3931                                sGetTableAndWhereParam.where, whereArgs);
3932                        break;
3933
3934                    case IMAGES_THUMBNAILS_ID:
3935                    case IMAGES_THUMBNAILS:
3936                    case VIDEO_THUMBNAILS_ID:
3937                    case VIDEO_THUMBNAILS:
3938                        // Delete the referenced files first.
3939                        Cursor c = db.query(sGetTableAndWhereParam.table,
3940                                sDataOnlyColumn,
3941                                sGetTableAndWhereParam.where, whereArgs, null, null, null);
3942                        if (c != null) {
3943                            while (c.moveToNext()) {
3944                                try {
3945                                    Libcore.os.remove(c.getString(0));
3946                                } catch (ErrnoException e) {
3947                                }
3948                            }
3949                            c.close();
3950                        }
3951                        database.mNumDeletes++;
3952                        count = db.delete(sGetTableAndWhereParam.table,
3953                                sGetTableAndWhereParam.where, whereArgs);
3954                        break;
3955
3956                    default:
3957                        database.mNumDeletes++;
3958                        count = db.delete(sGetTableAndWhereParam.table,
3959                                sGetTableAndWhereParam.where, whereArgs);
3960                        break;
3961                }
3962                // Since there are multiple Uris that can refer to the same files
3963                // and deletes can affect other objects in storage (like subdirectories
3964                // or playlists) we will notify a change on the entire volume to make
3965                // sure no listeners miss the notification.
3966                String volume = uri.getPathSegments().get(0);
3967                Uri notifyUri = Uri.parse("content://" + MediaStore.AUTHORITY + "/" + volume);
3968                getContext().getContentResolver().notifyChange(notifyUri, null);
3969            }
3970        }
3971
3972        return count;
3973    }
3974
3975    @Override
3976    public Bundle call(String method, String arg, Bundle extras) {
3977        if (MediaStore.UNHIDE_CALL.equals(method)) {
3978            processRemovedNoMediaPath(arg);
3979            return null;
3980        }
3981        throw new UnsupportedOperationException("Unsupported call: " + method);
3982    }
3983
3984    @Override
3985    public int update(Uri uri, ContentValues initialValues, String userWhere,
3986            String[] whereArgs) {
3987        int count;
3988        // Log.v(TAG, "update for uri="+uri+", initValues="+initialValues);
3989        int match = URI_MATCHER.match(uri);
3990        DatabaseHelper helper = getDatabaseForUri(uri);
3991        if (helper == null) {
3992            throw new UnsupportedOperationException(
3993                    "Unknown URI: " + uri);
3994        }
3995        helper.mNumUpdates++;
3996
3997        SQLiteDatabase db = helper.getWritableDatabase();
3998
3999        String genre = null;
4000        if (initialValues != null) {
4001            genre = initialValues.getAsString(Audio.AudioColumns.GENRE);
4002            initialValues.remove(Audio.AudioColumns.GENRE);
4003        }
4004
4005        synchronized (sGetTableAndWhereParam) {
4006            getTableAndWhere(uri, match, userWhere, sGetTableAndWhereParam);
4007
4008            // special case renaming directories via MTP.
4009            // in this case we must update all paths in the database with
4010            // the directory name as a prefix
4011            if ((match == MTP_OBJECTS || match == MTP_OBJECTS_ID)
4012                    && initialValues != null && initialValues.size() == 1) {
4013                String oldPath = null;
4014                String newPath = initialValues.getAsString(MediaStore.MediaColumns.DATA);
4015                mDirectoryCache.remove(newPath);
4016                // MtpDatabase will rename the directory first, so we test the new file name
4017                File f = new File(newPath);
4018                if (newPath != null && f.isDirectory()) {
4019                    helper.mNumQueries++;
4020                    Cursor cursor = db.query(sGetTableAndWhereParam.table, PATH_PROJECTION,
4021                        userWhere, whereArgs, null, null, null);
4022                    try {
4023                        if (cursor != null && cursor.moveToNext()) {
4024                            oldPath = cursor.getString(1);
4025                        }
4026                    } finally {
4027                        if (cursor != null) cursor.close();
4028                    }
4029                    if (oldPath != null) {
4030                        mDirectoryCache.remove(oldPath);
4031                        // first rename the row for the directory
4032                        helper.mNumUpdates++;
4033                        count = db.update(sGetTableAndWhereParam.table, initialValues,
4034                                sGetTableAndWhereParam.where, whereArgs);
4035                        if (count > 0) {
4036                            // update the paths of any files and folders contained in the directory
4037                            Object[] bindArgs = new Object[] {newPath, oldPath.length() + 1,
4038                                    oldPath + "/", oldPath + "0",
4039                                    // update bucket_display_name and bucket_id based on new path
4040                                    f.getName(),
4041                                    f.toString().toLowerCase().hashCode()
4042                                    };
4043                            helper.mNumUpdates++;
4044                            db.execSQL("UPDATE files SET _data=?1||SUBSTR(_data, ?2)" +
4045                                    // also update bucket_display_name
4046                                    ",bucket_display_name=?6" +
4047                                    ",bucket_id=?7" +
4048                                    " WHERE _data >= ?3 AND _data < ?4;",
4049                                    bindArgs);
4050                        }
4051
4052                        if (count > 0 && !db.inTransaction()) {
4053                            getContext().getContentResolver().notifyChange(uri, null);
4054                        }
4055                        if (f.getName().startsWith(".")) {
4056                            // the new directory name is hidden
4057                            processNewNoMediaPath(helper, db, newPath);
4058                        }
4059                        return count;
4060                    }
4061                } else if (newPath.toLowerCase(Locale.US).endsWith("/.nomedia")) {
4062                    processNewNoMediaPath(helper, db, newPath);
4063                }
4064            }
4065
4066            switch (match) {
4067                case AUDIO_MEDIA:
4068                case AUDIO_MEDIA_ID:
4069                    {
4070                        ContentValues values = new ContentValues(initialValues);
4071                        String albumartist = values.getAsString(MediaStore.Audio.Media.ALBUM_ARTIST);
4072                        String compilation = values.getAsString(MediaStore.Audio.Media.COMPILATION);
4073                        values.remove(MediaStore.Audio.Media.COMPILATION);
4074
4075                        // Insert the artist into the artist table and remove it from
4076                        // the input values
4077                        String artist = values.getAsString("artist");
4078                        values.remove("artist");
4079                        if (artist != null) {
4080                            long artistRowId;
4081                            HashMap<String, Long> artistCache = helper.mArtistCache;
4082                            synchronized(artistCache) {
4083                                Long temp = artistCache.get(artist);
4084                                if (temp == null) {
4085                                    artistRowId = getKeyIdForName(helper, db,
4086                                            "artists", "artist_key", "artist",
4087                                            artist, artist, null, 0, null, artistCache, uri);
4088                                } else {
4089                                    artistRowId = temp.longValue();
4090                                }
4091                            }
4092                            values.put("artist_id", Integer.toString((int)artistRowId));
4093                        }
4094
4095                        // Do the same for the album field.
4096                        String so = values.getAsString("album");
4097                        values.remove("album");
4098                        if (so != null) {
4099                            String path = values.getAsString(MediaStore.MediaColumns.DATA);
4100                            int albumHash = 0;
4101                            if (albumartist != null) {
4102                                albumHash = albumartist.hashCode();
4103                            } else if (compilation != null && compilation.equals("1")) {
4104                                // nothing to do, hash already set
4105                            } else {
4106                                if (path == null) {
4107                                    if (match == AUDIO_MEDIA) {
4108                                        Log.w(TAG, "Possible multi row album name update without"
4109                                                + " path could give wrong album key");
4110                                    } else {
4111                                        //Log.w(TAG, "Specify path to avoid extra query");
4112                                        Cursor c = query(uri,
4113                                                new String[] { MediaStore.Audio.Media.DATA},
4114                                                null, null, null);
4115                                        if (c != null) {
4116                                            try {
4117                                                int numrows = c.getCount();
4118                                                if (numrows == 1) {
4119                                                    c.moveToFirst();
4120                                                    path = c.getString(0);
4121                                                } else {
4122                                                    Log.e(TAG, "" + numrows + " rows for " + uri);
4123                                                }
4124                                            } finally {
4125                                                c.close();
4126                                            }
4127                                        }
4128                                    }
4129                                }
4130                                if (path != null) {
4131                                    albumHash = path.substring(0, path.lastIndexOf('/')).hashCode();
4132                                }
4133                            }
4134
4135                            String s = so.toString();
4136                            long albumRowId;
4137                            HashMap<String, Long> albumCache = helper.mAlbumCache;
4138                            synchronized(albumCache) {
4139                                String cacheName = s + albumHash;
4140                                Long temp = albumCache.get(cacheName);
4141                                if (temp == null) {
4142                                    albumRowId = getKeyIdForName(helper, db,
4143                                            "albums", "album_key", "album",
4144                                            s, cacheName, path, albumHash, artist, albumCache, uri);
4145                                } else {
4146                                    albumRowId = temp.longValue();
4147                                }
4148                            }
4149                            values.put("album_id", Integer.toString((int)albumRowId));
4150                        }
4151
4152                        // don't allow the title_key field to be updated directly
4153                        values.remove("title_key");
4154                        // If the title field is modified, update the title_key
4155                        so = values.getAsString("title");
4156                        if (so != null) {
4157                            String s = so.toString();
4158                            values.put("title_key", MediaStore.Audio.keyFor(s));
4159                            // do a final trim of the title, in case it started with the special
4160                            // "sort first" character (ascii \001)
4161                            values.remove("title");
4162                            values.put("title", s.trim());
4163                        }
4164
4165                        helper.mNumUpdates++;
4166                        count = db.update(sGetTableAndWhereParam.table, values,
4167                                sGetTableAndWhereParam.where, whereArgs);
4168                        if (genre != null) {
4169                            if (count == 1 && match == AUDIO_MEDIA_ID) {
4170                                long rowId = Long.parseLong(uri.getPathSegments().get(3));
4171                                updateGenre(rowId, genre);
4172                            } else {
4173                                // can't handle genres for bulk update or for non-audio files
4174                                Log.w(TAG, "ignoring genre in update: count = "
4175                                        + count + " match = " + match);
4176                            }
4177                        }
4178                    }
4179                    break;
4180                case IMAGES_MEDIA:
4181                case IMAGES_MEDIA_ID:
4182                case VIDEO_MEDIA:
4183                case VIDEO_MEDIA_ID:
4184                    {
4185                        ContentValues values = new ContentValues(initialValues);
4186                        // Don't allow bucket id or display name to be updated directly.
4187                        // The same names are used for both images and table columns, so
4188                        // we use the ImageColumns constants here.
4189                        values.remove(ImageColumns.BUCKET_ID);
4190                        values.remove(ImageColumns.BUCKET_DISPLAY_NAME);
4191                        // If the data is being modified update the bucket values
4192                        String data = values.getAsString(MediaColumns.DATA);
4193                        if (data != null) {
4194                            computeBucketValues(data, values);
4195                        }
4196                        computeTakenTime(values);
4197                        helper.mNumUpdates++;
4198                        count = db.update(sGetTableAndWhereParam.table, values,
4199                                sGetTableAndWhereParam.where, whereArgs);
4200                        // if this is a request from MediaScanner, DATA should contains file path
4201                        // we only process update request from media scanner, otherwise the requests
4202                        // could be duplicate.
4203                        if (count > 0 && values.getAsString(MediaStore.MediaColumns.DATA) != null) {
4204                            helper.mNumQueries++;
4205                            Cursor c = db.query(sGetTableAndWhereParam.table,
4206                                    READY_FLAG_PROJECTION, sGetTableAndWhereParam.where,
4207                                    whereArgs, null, null, null);
4208                            if (c != null) {
4209                                try {
4210                                    while (c.moveToNext()) {
4211                                        long magic = c.getLong(2);
4212                                        if (magic == 0) {
4213                                            requestMediaThumbnail(c.getString(1), uri,
4214                                                    MediaThumbRequest.PRIORITY_NORMAL, 0);
4215                                        }
4216                                    }
4217                                } finally {
4218                                    c.close();
4219                                }
4220                            }
4221                        }
4222                    }
4223                    break;
4224
4225                case AUDIO_PLAYLISTS_ID_MEMBERS_ID:
4226                    String moveit = uri.getQueryParameter("move");
4227                    if (moveit != null) {
4228                        String key = MediaStore.Audio.Playlists.Members.PLAY_ORDER;
4229                        if (initialValues.containsKey(key)) {
4230                            int newpos = initialValues.getAsInteger(key);
4231                            List <String> segments = uri.getPathSegments();
4232                            long playlist = Long.valueOf(segments.get(3));
4233                            int oldpos = Integer.valueOf(segments.get(5));
4234                            return movePlaylistEntry(helper, db, playlist, oldpos, newpos);
4235                        }
4236                        throw new IllegalArgumentException("Need to specify " + key +
4237                                " when using 'move' parameter");
4238                    }
4239                    // fall through
4240                default:
4241                    helper.mNumUpdates++;
4242                    count = db.update(sGetTableAndWhereParam.table, initialValues,
4243                        sGetTableAndWhereParam.where, whereArgs);
4244                    break;
4245            }
4246        }
4247        // in a transaction, the code that began the transaction should be taking
4248        // care of notifications once it ends the transaction successfully
4249        if (count > 0 && !db.inTransaction()) {
4250            getContext().getContentResolver().notifyChange(uri, null);
4251        }
4252        return count;
4253    }
4254
4255    private int movePlaylistEntry(DatabaseHelper helper, SQLiteDatabase db,
4256            long playlist, int from, int to) {
4257        if (from == to) {
4258            return 0;
4259        }
4260        db.beginTransaction();
4261        int numlines = 0;
4262        try {
4263            helper.mNumUpdates += 3;
4264            Cursor c = db.query("audio_playlists_map",
4265                    new String [] {"play_order" },
4266                    "playlist_id=?", new String[] {"" + playlist}, null, null, "play_order",
4267                    from + ",1");
4268            c.moveToFirst();
4269            int from_play_order = c.getInt(0);
4270            c.close();
4271            c = db.query("audio_playlists_map",
4272                    new String [] {"play_order" },
4273                    "playlist_id=?", new String[] {"" + playlist}, null, null, "play_order",
4274                    to + ",1");
4275            c.moveToFirst();
4276            int to_play_order = c.getInt(0);
4277            c.close();
4278            db.execSQL("UPDATE audio_playlists_map SET play_order=-1" +
4279                    " WHERE play_order=" + from_play_order +
4280                    " AND playlist_id=" + playlist);
4281            // We could just run both of the next two statements, but only one of
4282            // of them will actually do anything, so might as well skip the compile
4283            // and execute steps.
4284            if (from  < to) {
4285                db.execSQL("UPDATE audio_playlists_map SET play_order=play_order-1" +
4286                        " WHERE play_order<=" + to_play_order +
4287                        " AND play_order>" + from_play_order +
4288                        " AND playlist_id=" + playlist);
4289                numlines = to - from + 1;
4290            } else {
4291                db.execSQL("UPDATE audio_playlists_map SET play_order=play_order+1" +
4292                        " WHERE play_order>=" + to_play_order +
4293                        " AND play_order<" + from_play_order +
4294                        " AND playlist_id=" + playlist);
4295                numlines = from - to + 1;
4296            }
4297            db.execSQL("UPDATE audio_playlists_map SET play_order=" + to_play_order +
4298                    " WHERE play_order=-1 AND playlist_id=" + playlist);
4299            db.setTransactionSuccessful();
4300        } finally {
4301            db.endTransaction();
4302        }
4303
4304        Uri uri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI
4305                .buildUpon().appendEncodedPath(String.valueOf(playlist)).build();
4306        // notifyChange() must be called after the database transaction is ended
4307        // or the listeners will read the old data in the callback
4308        getContext().getContentResolver().notifyChange(uri, null);
4309
4310        return numlines;
4311    }
4312
4313    private static final String[] openFileColumns = new String[] {
4314        MediaStore.MediaColumns.DATA,
4315    };
4316
4317    @Override
4318    public ParcelFileDescriptor openFile(Uri uri, String mode)
4319            throws FileNotFoundException {
4320
4321        ParcelFileDescriptor pfd = null;
4322
4323        if (URI_MATCHER.match(uri) == AUDIO_ALBUMART_FILE_ID) {
4324            // get album art for the specified media file
4325            DatabaseHelper database = getDatabaseForUri(uri);
4326            if (database == null) {
4327                throw new IllegalStateException("Couldn't open database for " + uri);
4328            }
4329            SQLiteDatabase db = database.getReadableDatabase();
4330            if (db == null) {
4331                throw new IllegalStateException("Couldn't open database for " + uri);
4332            }
4333            SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
4334            int songid = Integer.parseInt(uri.getPathSegments().get(3));
4335            qb.setTables("audio_meta");
4336            qb.appendWhere("_id=" + songid);
4337            Cursor c = qb.query(db,
4338                    new String [] {
4339                        MediaStore.Audio.Media.DATA,
4340                        MediaStore.Audio.Media.ALBUM_ID },
4341                    null, null, null, null, null);
4342            if (c.moveToFirst()) {
4343                String audiopath = c.getString(0);
4344                int albumid = c.getInt(1);
4345                // Try to get existing album art for this album first, which
4346                // could possibly have been obtained from a different file.
4347                // If that fails, try to get it from this specific file.
4348                Uri newUri = ContentUris.withAppendedId(ALBUMART_URI, albumid);
4349                try {
4350                    pfd = openFileAndEnforcePathPermissionsHelper(newUri, mode);
4351                } catch (FileNotFoundException ex) {
4352                    // That didn't work, now try to get it from the specific file
4353                    pfd = getThumb(database, db, audiopath, albumid, null);
4354                }
4355            }
4356            c.close();
4357            return pfd;
4358        }
4359
4360        try {
4361            pfd = openFileAndEnforcePathPermissionsHelper(uri, mode);
4362        } catch (FileNotFoundException ex) {
4363            if (mode.contains("w")) {
4364                // if the file couldn't be created, we shouldn't extract album art
4365                throw ex;
4366            }
4367
4368            if (URI_MATCHER.match(uri) == AUDIO_ALBUMART_ID) {
4369                // Tried to open an album art file which does not exist. Regenerate.
4370                DatabaseHelper database = getDatabaseForUri(uri);
4371                if (database == null) {
4372                    throw ex;
4373                }
4374                SQLiteDatabase db = database.getReadableDatabase();
4375                if (db == null) {
4376                    throw new IllegalStateException("Couldn't open database for " + uri);
4377                }
4378                SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
4379                int albumid = Integer.parseInt(uri.getPathSegments().get(3));
4380                qb.setTables("audio_meta");
4381                qb.appendWhere("album_id=" + albumid);
4382                Cursor c = qb.query(db,
4383                        new String [] {
4384                            MediaStore.Audio.Media.DATA },
4385                        null, null, null, null, MediaStore.Audio.Media.TRACK);
4386                if (c.moveToFirst()) {
4387                    String audiopath = c.getString(0);
4388                    pfd = getThumb(database, db, audiopath, albumid, uri);
4389                }
4390                c.close();
4391            }
4392            if (pfd == null) {
4393                throw ex;
4394            }
4395        }
4396        return pfd;
4397    }
4398
4399    /**
4400     * Return the {@link MediaColumns#DATA} field for the given {@code Uri}.
4401     */
4402    private File queryForDataFile(Uri uri) throws FileNotFoundException {
4403        final Cursor cursor = query(
4404                uri, new String[] { MediaColumns.DATA }, null, null, null);
4405        if (cursor == null) {
4406            throw new FileNotFoundException("Missing cursor for " + uri);
4407        }
4408
4409        try {
4410            switch (cursor.getCount()) {
4411                case 0:
4412                    throw new FileNotFoundException("No entry for " + uri);
4413                case 1:
4414                    if (cursor.moveToFirst()) {
4415                        return new File(cursor.getString(0));
4416                    } else {
4417                        throw new FileNotFoundException("Unable to read entry for " + uri);
4418                    }
4419                default:
4420                    throw new FileNotFoundException("Multiple items at " + uri);
4421            }
4422        } finally {
4423            cursor.close();
4424        }
4425    }
4426
4427    /**
4428     * Replacement for {@link #openFileHelper(Uri, String)} which enforces any
4429     * permissions applicable to the path before returning.
4430     */
4431    private ParcelFileDescriptor openFileAndEnforcePathPermissionsHelper(Uri uri, String mode)
4432            throws FileNotFoundException {
4433        final int modeBits = ContentResolver.modeToMode(uri, mode);
4434        final boolean isWrite = (modeBits & MODE_WRITE_ONLY) != 0;
4435
4436        File file = queryForDataFile(uri);
4437        final String path;
4438        try {
4439            path = file.getCanonicalPath();
4440        } catch (IOException e) {
4441            throw new IllegalArgumentException("Unable to resolve canonical path for " + file, e);
4442        }
4443
4444        if (path.startsWith(sExternalPath)) {
4445            getContext().enforceCallingOrSelfPermission(
4446                    READ_EXTERNAL_STORAGE, "External path: " + path);
4447
4448            if (isWrite) {
4449                getContext().enforceCallingOrSelfPermission(
4450                        WRITE_EXTERNAL_STORAGE, "External path: " + path);
4451            }
4452
4453            // Bypass emulation layer when file is opened for reading, but only
4454            // when opening read-only and we have an exact match.
4455            if (modeBits == MODE_READ_ONLY) {
4456                file = Environment.maybeTranslateEmulatedPathToInternal(file);
4457            }
4458
4459        } else if (path.startsWith(sCachePath)) {
4460            getContext().enforceCallingOrSelfPermission(
4461                    ACCESS_CACHE_FILESYSTEM, "Cache path: " + path);
4462        }
4463
4464        return ParcelFileDescriptor.open(file, modeBits);
4465    }
4466
4467    private class ThumbData {
4468        DatabaseHelper helper;
4469        SQLiteDatabase db;
4470        String path;
4471        long album_id;
4472        Uri albumart_uri;
4473    }
4474
4475    private void makeThumbAsync(DatabaseHelper helper, SQLiteDatabase db,
4476            String path, long album_id) {
4477        synchronized (mPendingThumbs) {
4478            if (mPendingThumbs.contains(path)) {
4479                // There's already a request to make an album art thumbnail
4480                // for this audio file in the queue.
4481                return;
4482            }
4483
4484            mPendingThumbs.add(path);
4485        }
4486
4487        ThumbData d = new ThumbData();
4488        d.helper = helper;
4489        d.db = db;
4490        d.path = path;
4491        d.album_id = album_id;
4492        d.albumart_uri = ContentUris.withAppendedId(mAlbumArtBaseUri, album_id);
4493
4494        // Instead of processing thumbnail requests in the order they were
4495        // received we instead process them stack-based, i.e. LIFO.
4496        // The idea behind this is that the most recently requested thumbnails
4497        // are most likely the ones still in the user's view, whereas those
4498        // requested earlier may have already scrolled off.
4499        synchronized (mThumbRequestStack) {
4500            mThumbRequestStack.push(d);
4501        }
4502
4503        // Trigger the handler.
4504        Message msg = mThumbHandler.obtainMessage(ALBUM_THUMB);
4505        msg.sendToTarget();
4506    }
4507
4508    //Return true if the artPath is the dir as it in mExternalStoragePaths
4509    //for multi storage support
4510    private static boolean isRootStorageDir(String artPath) {
4511        for ( int i = 0; i < mExternalStoragePaths.length; i++) {
4512            if ((mExternalStoragePaths[i] != null) &&
4513                    (artPath.equalsIgnoreCase(mExternalStoragePaths[i])))
4514                return true;
4515        }
4516        return false;
4517    }
4518
4519    // Extract compressed image data from the audio file itself or, if that fails,
4520    // look for a file "AlbumArt.jpg" in the containing directory.
4521    private static byte[] getCompressedAlbumArt(Context context, String path) {
4522        byte[] compressed = null;
4523
4524        try {
4525            File f = new File(path);
4526            ParcelFileDescriptor pfd = ParcelFileDescriptor.open(f,
4527                    ParcelFileDescriptor.MODE_READ_ONLY);
4528
4529            MediaScanner scanner = new MediaScanner(context);
4530            compressed = scanner.extractAlbumArt(pfd.getFileDescriptor());
4531            pfd.close();
4532
4533            // If no embedded art exists, look for a suitable image file in the
4534            // same directory as the media file, except if that directory is
4535            // is the root directory of the sd card or the download directory.
4536            // We look for, in order of preference:
4537            // 0 AlbumArt.jpg
4538            // 1 AlbumArt*Large.jpg
4539            // 2 Any other jpg image with 'albumart' anywhere in the name
4540            // 3 Any other jpg image
4541            // 4 any other png image
4542            if (compressed == null && path != null) {
4543                int lastSlash = path.lastIndexOf('/');
4544                if (lastSlash > 0) {
4545
4546                    String artPath = path.substring(0, lastSlash);
4547                    String dwndir = Environment.getExternalStoragePublicDirectory(
4548                            Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
4549
4550                    String bestmatch = null;
4551                    synchronized (sFolderArtMap) {
4552                        if (sFolderArtMap.containsKey(artPath)) {
4553                            bestmatch = sFolderArtMap.get(artPath);
4554                        } else if (!isRootStorageDir(artPath) &&
4555                                !artPath.equalsIgnoreCase(dwndir)) {
4556                            File dir = new File(artPath);
4557                            String [] entrynames = dir.list();
4558                            if (entrynames == null) {
4559                                return null;
4560                            }
4561                            bestmatch = null;
4562                            int matchlevel = 1000;
4563                            for (int i = entrynames.length - 1; i >=0; i--) {
4564                                String entry = entrynames[i].toLowerCase();
4565                                if (entry.equals("albumart.jpg")) {
4566                                    bestmatch = entrynames[i];
4567                                    break;
4568                                } else if (entry.startsWith("albumart")
4569                                        && entry.endsWith("large.jpg")
4570                                        && matchlevel > 1) {
4571                                    bestmatch = entrynames[i];
4572                                    matchlevel = 1;
4573                                } else if (entry.contains("albumart")
4574                                        && entry.endsWith(".jpg")
4575                                        && matchlevel > 2) {
4576                                    bestmatch = entrynames[i];
4577                                    matchlevel = 2;
4578                                } else if (entry.endsWith(".jpg") && matchlevel > 3) {
4579                                    bestmatch = entrynames[i];
4580                                    matchlevel = 3;
4581                                } else if (entry.endsWith(".png") && matchlevel > 4) {
4582                                    bestmatch = entrynames[i];
4583                                    matchlevel = 4;
4584                                }
4585                            }
4586                            // note that this may insert null if no album art was found
4587                            sFolderArtMap.put(artPath, bestmatch);
4588                        }
4589                    }
4590
4591                    if (bestmatch != null) {
4592                        File file = new File(artPath, bestmatch);
4593                        if (file.exists()) {
4594                            compressed = new byte[(int)file.length()];
4595                            FileInputStream stream = null;
4596                            try {
4597                                stream = new FileInputStream(file);
4598                                stream.read(compressed);
4599                            } catch (IOException ex) {
4600                                compressed = null;
4601                            } finally {
4602                                if (stream != null) {
4603                                    stream.close();
4604                                }
4605                            }
4606                        }
4607                    }
4608                }
4609            }
4610        } catch (IOException e) {
4611        }
4612
4613        return compressed;
4614    }
4615
4616    // Return a URI to write the album art to and update the database as necessary.
4617    Uri getAlbumArtOutputUri(DatabaseHelper helper, SQLiteDatabase db, long album_id, Uri albumart_uri) {
4618        Uri out = null;
4619        // TODO: this could be done more efficiently with a call to db.replace(), which
4620        // replaces or inserts as needed, making it unnecessary to query() first.
4621        if (albumart_uri != null) {
4622            Cursor c = query(albumart_uri, new String [] { MediaStore.MediaColumns.DATA },
4623                    null, null, null);
4624            try {
4625                if (c != null && c.moveToFirst()) {
4626                    String albumart_path = c.getString(0);
4627                    if (ensureFileExists(albumart_path)) {
4628                        out = albumart_uri;
4629                    }
4630                } else {
4631                    albumart_uri = null;
4632                }
4633            } finally {
4634                if (c != null) {
4635                    c.close();
4636                }
4637            }
4638        }
4639        if (albumart_uri == null){
4640            ContentValues initialValues = new ContentValues();
4641            initialValues.put("album_id", album_id);
4642            try {
4643                ContentValues values = ensureFile(false, initialValues, "", ALBUM_THUMB_FOLDER);
4644                helper.mNumInserts++;
4645                long rowId = db.insert("album_art", MediaStore.MediaColumns.DATA, values);
4646                if (rowId > 0) {
4647                    out = ContentUris.withAppendedId(ALBUMART_URI, rowId);
4648                    // ensure the parent directory exists
4649                    String albumart_path = values.getAsString(MediaStore.MediaColumns.DATA);
4650                    ensureFileExists(albumart_path);
4651                }
4652            } catch (IllegalStateException ex) {
4653                Log.e(TAG, "error creating album thumb file");
4654            }
4655        }
4656        return out;
4657    }
4658
4659    // Write out the album art to the output URI, recompresses the given Bitmap
4660    // if necessary, otherwise writes the compressed data.
4661    private void writeAlbumArt(
4662            boolean need_to_recompress, Uri out, byte[] compressed, Bitmap bm) throws IOException {
4663        OutputStream outstream = null;
4664        try {
4665            outstream = getContext().getContentResolver().openOutputStream(out);
4666
4667            if (!need_to_recompress) {
4668                // No need to recompress here, just write out the original
4669                // compressed data here.
4670                outstream.write(compressed);
4671            } else {
4672                if (!bm.compress(Bitmap.CompressFormat.JPEG, 85, outstream)) {
4673                    throw new IOException("failed to compress bitmap");
4674                }
4675            }
4676        } finally {
4677            IoUtils.closeQuietly(outstream);
4678        }
4679    }
4680
4681    private ParcelFileDescriptor getThumb(DatabaseHelper helper, SQLiteDatabase db, String path,
4682            long album_id, Uri albumart_uri) {
4683        ThumbData d = new ThumbData();
4684        d.helper = helper;
4685        d.db = db;
4686        d.path = path;
4687        d.album_id = album_id;
4688        d.albumart_uri = albumart_uri;
4689        return makeThumbInternal(d);
4690    }
4691
4692    private ParcelFileDescriptor makeThumbInternal(ThumbData d) {
4693        byte[] compressed = getCompressedAlbumArt(getContext(), d.path);
4694
4695        if (compressed == null) {
4696            return null;
4697        }
4698
4699        Bitmap bm = null;
4700        boolean need_to_recompress = true;
4701
4702        try {
4703            // get the size of the bitmap
4704            BitmapFactory.Options opts = new BitmapFactory.Options();
4705            opts.inJustDecodeBounds = true;
4706            opts.inSampleSize = 1;
4707            BitmapFactory.decodeByteArray(compressed, 0, compressed.length, opts);
4708
4709            // request a reasonably sized output image
4710            final Resources r = getContext().getResources();
4711            final int maximumThumbSize = r.getDimensionPixelSize(R.dimen.maximum_thumb_size);
4712            while (opts.outHeight > maximumThumbSize || opts.outWidth > maximumThumbSize) {
4713                opts.outHeight /= 2;
4714                opts.outWidth /= 2;
4715                opts.inSampleSize *= 2;
4716            }
4717
4718            if (opts.inSampleSize == 1) {
4719                // The original album art was of proper size, we won't have to
4720                // recompress the bitmap later.
4721                need_to_recompress = false;
4722            } else {
4723                // get the image for real now
4724                opts.inJustDecodeBounds = false;
4725                opts.inPreferredConfig = Bitmap.Config.RGB_565;
4726                bm = BitmapFactory.decodeByteArray(compressed, 0, compressed.length, opts);
4727
4728                if (bm != null && bm.getConfig() == null) {
4729                    Bitmap nbm = bm.copy(Bitmap.Config.RGB_565, false);
4730                    if (nbm != null && nbm != bm) {
4731                        bm.recycle();
4732                        bm = nbm;
4733                    }
4734                }
4735            }
4736        } catch (Exception e) {
4737        }
4738
4739        if (need_to_recompress && bm == null) {
4740            return null;
4741        }
4742
4743        if (d.albumart_uri == null) {
4744            // this one doesn't need to be saved (probably a song with an unknown album),
4745            // so stick it in a memory file and return that
4746            try {
4747                return ParcelFileDescriptor.fromData(compressed, "albumthumb");
4748            } catch (IOException e) {
4749            }
4750        } else {
4751            // This one needs to actually be saved on the sd card.
4752            // This is wrapped in a transaction because there are various things
4753            // that could go wrong while generating the thumbnail, and we only want
4754            // to update the database when all steps succeeded.
4755            d.db.beginTransaction();
4756            Uri out = null;
4757            ParcelFileDescriptor pfd = null;
4758            try {
4759                out = getAlbumArtOutputUri(d.helper, d.db, d.album_id, d.albumart_uri);
4760
4761                if (out != null) {
4762                    writeAlbumArt(need_to_recompress, out, compressed, bm);
4763                    getContext().getContentResolver().notifyChange(MEDIA_URI, null);
4764                    pfd = openFileHelper(out, "r");
4765                    d.db.setTransactionSuccessful();
4766                    return pfd;
4767                }
4768            } catch (IOException ex) {
4769                // do nothing, just return null below
4770            } catch (UnsupportedOperationException ex) {
4771                // do nothing, just return null below
4772            } finally {
4773                d.db.endTransaction();
4774                if (bm != null) {
4775                    bm.recycle();
4776                }
4777                if (pfd == null && out != null) {
4778                    // Thumbnail was not written successfully, delete the entry that refers to it.
4779                    // Note that this only does something if getAlbumArtOutputUri() reused an
4780                    // existing entry from the database. If a new entry was created, it will
4781                    // have been rolled back as part of backing out the transaction.
4782                    getContext().getContentResolver().delete(out, null, null);
4783                }
4784            }
4785        }
4786        return null;
4787    }
4788
4789    /**
4790     * Look up the artist or album entry for the given name, creating that entry
4791     * if it does not already exists.
4792     * @param db        The database
4793     * @param table     The table to store the key/name pair in.
4794     * @param keyField  The name of the key-column
4795     * @param nameField The name of the name-column
4796     * @param rawName   The name that the calling app was trying to insert into the database
4797     * @param cacheName The string that will be inserted in to the cache
4798     * @param path      The full path to the file being inserted in to the audio table
4799     * @param albumHash A hash to distinguish between different albums of the same name
4800     * @param artist    The name of the artist, if known
4801     * @param cache     The cache to add this entry to
4802     * @param srcuri    The Uri that prompted the call to this method, used for determining whether this is
4803     *                  the internal or external database
4804     * @return          The row ID for this artist/album, or -1 if the provided name was invalid
4805     */
4806    private long getKeyIdForName(DatabaseHelper helper, SQLiteDatabase db,
4807            String table, String keyField, String nameField,
4808            String rawName, String cacheName, String path, int albumHash,
4809            String artist, HashMap<String, Long> cache, Uri srcuri) {
4810        long rowId;
4811
4812        if (rawName == null || rawName.length() == 0) {
4813            rawName = MediaStore.UNKNOWN_STRING;
4814        }
4815        String k = MediaStore.Audio.keyFor(rawName);
4816
4817        if (k == null) {
4818            // shouldn't happen, since we only get null keys for null inputs
4819            Log.e(TAG, "null key", new Exception());
4820            return -1;
4821        }
4822
4823        boolean isAlbum = table.equals("albums");
4824        boolean isUnknown = MediaStore.UNKNOWN_STRING.equals(rawName);
4825
4826        // To distinguish same-named albums, we append a hash. The hash is based
4827        // on the "album artist" tag if present, otherwise on the "compilation" tag
4828        // if present, otherwise on the path.
4829        // Ideally we would also take things like CDDB ID in to account, so
4830        // we can group files from the same album that aren't in the same
4831        // folder, but this is a quick and easy start that works immediately
4832        // without requiring support from the mp3, mp4 and Ogg meta data
4833        // readers, as long as the albums are in different folders.
4834        if (isAlbum) {
4835            k = k + albumHash;
4836            if (isUnknown) {
4837                k = k + artist;
4838            }
4839        }
4840
4841        String [] selargs = { k };
4842        helper.mNumQueries++;
4843        Cursor c = db.query(table, null, keyField + "=?", selargs, null, null, null);
4844
4845        try {
4846            switch (c.getCount()) {
4847                case 0: {
4848                        // insert new entry into table
4849                        ContentValues otherValues = new ContentValues();
4850                        otherValues.put(keyField, k);
4851                        otherValues.put(nameField, rawName);
4852                        helper.mNumInserts++;
4853                        rowId = db.insert(table, "duration", otherValues);
4854                        if (path != null && isAlbum && ! isUnknown) {
4855                            // We just inserted a new album. Now create an album art thumbnail for it.
4856                            makeThumbAsync(helper, db, path, rowId);
4857                        }
4858                        if (rowId > 0) {
4859                            String volume = srcuri.toString().substring(16, 24); // extract internal/external
4860                            Uri uri = Uri.parse("content://media/" + volume + "/audio/" + table + "/" + rowId);
4861                            getContext().getContentResolver().notifyChange(uri, null);
4862                        }
4863                    }
4864                    break;
4865                case 1: {
4866                        // Use the existing entry
4867                        c.moveToFirst();
4868                        rowId = c.getLong(0);
4869
4870                        // Determine whether the current rawName is better than what's
4871                        // currently stored in the table, and update the table if it is.
4872                        String currentFancyName = c.getString(2);
4873                        String bestName = makeBestName(rawName, currentFancyName);
4874                        if (!bestName.equals(currentFancyName)) {
4875                            // update the table with the new name
4876                            ContentValues newValues = new ContentValues();
4877                            newValues.put(nameField, bestName);
4878                            helper.mNumUpdates++;
4879                            db.update(table, newValues, "rowid="+Integer.toString((int)rowId), null);
4880                            String volume = srcuri.toString().substring(16, 24); // extract internal/external
4881                            Uri uri = Uri.parse("content://media/" + volume + "/audio/" + table + "/" + rowId);
4882                            getContext().getContentResolver().notifyChange(uri, null);
4883                        }
4884                    }
4885                    break;
4886                default:
4887                    // corrupt database
4888                    Log.e(TAG, "Multiple entries in table " + table + " for key " + k);
4889                    rowId = -1;
4890                    break;
4891            }
4892        } finally {
4893            if (c != null) c.close();
4894        }
4895
4896        if (cache != null && ! isUnknown) {
4897            cache.put(cacheName, rowId);
4898        }
4899        return rowId;
4900    }
4901
4902    /**
4903     * Returns the best string to use for display, given two names.
4904     * Note that this function does not necessarily return either one
4905     * of the provided names; it may decide to return a better alternative
4906     * (for example, specifying the inputs "Police" and "Police, The" will
4907     * return "The Police")
4908     *
4909     * The basic assumptions are:
4910     * - longer is better ("The police" is better than "Police")
4911     * - prefix is better ("The Police" is better than "Police, The")
4912     * - accents are better ("Mot&ouml;rhead" is better than "Motorhead")
4913     *
4914     * @param one The first of the two names to consider
4915     * @param two The last of the two names to consider
4916     * @return The actual name to use
4917     */
4918    String makeBestName(String one, String two) {
4919        String name;
4920
4921        // Longer names are usually better.
4922        if (one.length() > two.length()) {
4923            name = one;
4924        } else {
4925            // Names with accents are usually better, and conveniently sort later
4926            if (one.toLowerCase().compareTo(two.toLowerCase()) > 0) {
4927                name = one;
4928            } else {
4929                name = two;
4930            }
4931        }
4932
4933        // Prefixes are better than postfixes.
4934        if (name.endsWith(", the") || name.endsWith(",the") ||
4935            name.endsWith(", an") || name.endsWith(",an") ||
4936            name.endsWith(", a") || name.endsWith(",a")) {
4937            String fix = name.substring(1 + name.lastIndexOf(','));
4938            name = fix.trim() + " " + name.substring(0, name.lastIndexOf(','));
4939        }
4940
4941        // TODO: word-capitalize the resulting name
4942        return name;
4943    }
4944
4945
4946    /**
4947     * Looks up the database based on the given URI.
4948     *
4949     * @param uri The requested URI
4950     * @returns the database for the given URI
4951     */
4952    private DatabaseHelper getDatabaseForUri(Uri uri) {
4953        synchronized (mDatabases) {
4954            if (uri.getPathSegments().size() >= 1) {
4955                return mDatabases.get(uri.getPathSegments().get(0));
4956            }
4957        }
4958        return null;
4959    }
4960
4961    static boolean isMediaDatabaseName(String name) {
4962        if (INTERNAL_DATABASE_NAME.equals(name)) {
4963            return true;
4964        }
4965        if (EXTERNAL_DATABASE_NAME.equals(name)) {
4966            return true;
4967        }
4968        if (name.startsWith("external-") && name.endsWith(".db")) {
4969            return true;
4970        }
4971        return false;
4972    }
4973
4974    static boolean isInternalMediaDatabaseName(String name) {
4975        if (INTERNAL_DATABASE_NAME.equals(name)) {
4976            return true;
4977        }
4978        return false;
4979    }
4980
4981    /**
4982     * Attach the database for a volume (internal or external).
4983     * Does nothing if the volume is already attached, otherwise
4984     * checks the volume ID and sets up the corresponding database.
4985     *
4986     * @param volume to attach, either {@link #INTERNAL_VOLUME} or {@link #EXTERNAL_VOLUME}.
4987     * @return the content URI of the attached volume.
4988     */
4989    private Uri attachVolume(String volume) {
4990        if (Binder.getCallingPid() != Process.myPid()) {
4991            throw new SecurityException(
4992                    "Opening and closing databases not allowed.");
4993        }
4994
4995        synchronized (mDatabases) {
4996            if (mDatabases.get(volume) != null) {  // Already attached
4997                return Uri.parse("content://media/" + volume);
4998            }
4999
5000            Context context = getContext();
5001            DatabaseHelper helper;
5002            if (INTERNAL_VOLUME.equals(volume)) {
5003                helper = new DatabaseHelper(context, INTERNAL_DATABASE_NAME, true,
5004                        false, mObjectRemovedCallback);
5005            } else if (EXTERNAL_VOLUME.equals(volume)) {
5006                if (Environment.isExternalStorageRemovable()) {
5007                    String path = mExternalStoragePaths[0];
5008                    int volumeID = FileUtils.getFatVolumeId(path);
5009                    if (LOCAL_LOGV) Log.v(TAG, path + " volume ID: " + volumeID);
5010
5011                    // Must check for failure!
5012                    // If the volume is not (yet) mounted, this will create a new
5013                    // external-ffffffff.db database instead of the one we expect.  Then, if
5014                    // android.process.media is later killed and respawned, the real external
5015                    // database will be attached, containing stale records, or worse, be empty.
5016                    if (volumeID == -1) {
5017                        String state = Environment.getExternalStorageState();
5018                        if (Environment.MEDIA_MOUNTED.equals(state) ||
5019                                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
5020                            // This may happen if external storage was _just_ mounted.  It may also
5021                            // happen if the volume ID is _actually_ 0xffffffff, in which case it
5022                            // must be changed since FileUtils::getFatVolumeId doesn't allow for
5023                            // that.  It may also indicate that FileUtils::getFatVolumeId is broken
5024                            // (missing ioctl), which is also impossible to disambiguate.
5025                            Log.e(TAG, "Can't obtain external volume ID even though it's mounted.");
5026                        } else {
5027                            Log.i(TAG, "External volume is not (yet) mounted, cannot attach.");
5028                        }
5029
5030                        throw new IllegalArgumentException("Can't obtain external volume ID for " +
5031                                volume + " volume.");
5032                    }
5033
5034                    // generate database name based on volume ID
5035                    String dbName = "external-" + Integer.toHexString(volumeID) + ".db";
5036                    helper = new DatabaseHelper(context, dbName, false,
5037                            false, mObjectRemovedCallback);
5038                    mVolumeId = volumeID;
5039                } else {
5040                    // external database name should be EXTERNAL_DATABASE_NAME
5041                    // however earlier releases used the external-XXXXXXXX.db naming
5042                    // for devices without removable storage, and in that case we need to convert
5043                    // to this new convention
5044                    File dbFile = context.getDatabasePath(EXTERNAL_DATABASE_NAME);
5045                    if (!dbFile.exists()) {
5046                        // find the most recent external database and rename it to
5047                        // EXTERNAL_DATABASE_NAME, and delete any other older
5048                        // external database files
5049                        File recentDbFile = null;
5050                        for (String database : context.databaseList()) {
5051                            if (database.startsWith("external-") && database.endsWith(".db")) {
5052                                File file = context.getDatabasePath(database);
5053                                if (recentDbFile == null) {
5054                                    recentDbFile = file;
5055                                } else if (file.lastModified() > recentDbFile.lastModified()) {
5056                                    context.deleteDatabase(recentDbFile.getName());
5057                                    recentDbFile = file;
5058                                } else {
5059                                    context.deleteDatabase(file.getName());
5060                                }
5061                            }
5062                        }
5063                        if (recentDbFile != null) {
5064                            if (recentDbFile.renameTo(dbFile)) {
5065                                Log.d(TAG, "renamed database " + recentDbFile.getName() +
5066                                        " to " + EXTERNAL_DATABASE_NAME);
5067                            } else {
5068                                Log.e(TAG, "Failed to rename database " + recentDbFile.getName() +
5069                                        " to " + EXTERNAL_DATABASE_NAME);
5070                                // This shouldn't happen, but if it does, continue using
5071                                // the file under its old name
5072                                dbFile = recentDbFile;
5073                            }
5074                        }
5075                        // else DatabaseHelper will create one named EXTERNAL_DATABASE_NAME
5076                    }
5077                    helper = new DatabaseHelper(context, dbFile.getName(), false,
5078                            false, mObjectRemovedCallback);
5079                }
5080            } else {
5081                throw new IllegalArgumentException("There is no volume named " + volume);
5082            }
5083
5084            mDatabases.put(volume, helper);
5085
5086            if (!helper.mInternal) {
5087                // create default directories (only happens on first boot)
5088                createDefaultFolders(helper, helper.getWritableDatabase());
5089
5090                // clean up stray album art files: delete every file not in the database
5091                File[] files = new File(mExternalStoragePaths[0], ALBUM_THUMB_FOLDER).listFiles();
5092                HashSet<String> fileSet = new HashSet();
5093                for (int i = 0; files != null && i < files.length; i++) {
5094                    fileSet.add(files[i].getPath());
5095                }
5096
5097                Cursor cursor = query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
5098                        new String[] { MediaStore.Audio.Albums.ALBUM_ART }, null, null, null);
5099                try {
5100                    while (cursor != null && cursor.moveToNext()) {
5101                        fileSet.remove(cursor.getString(0));
5102                    }
5103                } finally {
5104                    if (cursor != null) cursor.close();
5105                }
5106
5107                Iterator<String> iterator = fileSet.iterator();
5108                while (iterator.hasNext()) {
5109                    String filename = iterator.next();
5110                    if (LOCAL_LOGV) Log.v(TAG, "deleting obsolete album art " + filename);
5111                    new File(filename).delete();
5112                }
5113            }
5114        }
5115
5116        if (LOCAL_LOGV) Log.v(TAG, "Attached volume: " + volume);
5117        return Uri.parse("content://media/" + volume);
5118    }
5119
5120    /**
5121     * Detach the database for a volume (must be external).
5122     * Does nothing if the volume is already detached, otherwise
5123     * closes the database and sends a notification to listeners.
5124     *
5125     * @param uri The content URI of the volume, as returned by {@link #attachVolume}
5126     */
5127    private void detachVolume(Uri uri) {
5128        if (Binder.getCallingPid() != Process.myPid()) {
5129            throw new SecurityException(
5130                    "Opening and closing databases not allowed.");
5131        }
5132
5133        String volume = uri.getPathSegments().get(0);
5134        if (INTERNAL_VOLUME.equals(volume)) {
5135            throw new UnsupportedOperationException(
5136                    "Deleting the internal volume is not allowed");
5137        } else if (!EXTERNAL_VOLUME.equals(volume)) {
5138            throw new IllegalArgumentException(
5139                    "There is no volume named " + volume);
5140        }
5141
5142        synchronized (mDatabases) {
5143            DatabaseHelper database = mDatabases.get(volume);
5144            if (database == null) return;
5145
5146            try {
5147                // touch the database file to show it is most recently used
5148                File file = new File(database.getReadableDatabase().getPath());
5149                file.setLastModified(System.currentTimeMillis());
5150            } catch (Exception e) {
5151                Log.e(TAG, "Can't touch database file", e);
5152            }
5153
5154            mDatabases.remove(volume);
5155            database.close();
5156        }
5157
5158        getContext().getContentResolver().notifyChange(uri, null);
5159        if (LOCAL_LOGV) Log.v(TAG, "Detached volume: " + volume);
5160    }
5161
5162    private static String TAG = "MediaProvider";
5163    private static final boolean LOCAL_LOGV = false;
5164
5165    private static final String INTERNAL_DATABASE_NAME = "internal.db";
5166    private static final String EXTERNAL_DATABASE_NAME = "external.db";
5167
5168    // maximum number of cached external databases to keep
5169    private static final int MAX_EXTERNAL_DATABASES = 3;
5170
5171    // Delete databases that have not been used in two months
5172    // 60 days in milliseconds (1000 * 60 * 60 * 24 * 60)
5173    private static final long OBSOLETE_DATABASE_DB = 5184000000L;
5174
5175    private HashMap<String, DatabaseHelper> mDatabases;
5176
5177    private Handler mThumbHandler;
5178
5179    // name of the volume currently being scanned by the media scanner (or null)
5180    private String mMediaScannerVolume;
5181
5182    // current FAT volume ID
5183    private int mVolumeId = -1;
5184
5185    static final String INTERNAL_VOLUME = "internal";
5186    static final String EXTERNAL_VOLUME = "external";
5187    static final String ALBUM_THUMB_FOLDER = "Android/data/com.android.providers.media/albumthumbs";
5188
5189    // path for writing contents of in memory temp database
5190    private String mTempDatabasePath;
5191
5192    // WARNING: the values of IMAGES_MEDIA, AUDIO_MEDIA, and VIDEO_MEDIA and AUDIO_PLAYLISTS
5193    // are stored in the "files" table, so do not renumber them unless you also add
5194    // a corresponding database upgrade step for it.
5195    private static final int IMAGES_MEDIA = 1;
5196    private static final int IMAGES_MEDIA_ID = 2;
5197    private static final int IMAGES_THUMBNAILS = 3;
5198    private static final int IMAGES_THUMBNAILS_ID = 4;
5199
5200    private static final int AUDIO_MEDIA = 100;
5201    private static final int AUDIO_MEDIA_ID = 101;
5202    private static final int AUDIO_MEDIA_ID_GENRES = 102;
5203    private static final int AUDIO_MEDIA_ID_GENRES_ID = 103;
5204    private static final int AUDIO_MEDIA_ID_PLAYLISTS = 104;
5205    private static final int AUDIO_MEDIA_ID_PLAYLISTS_ID = 105;
5206    private static final int AUDIO_GENRES = 106;
5207    private static final int AUDIO_GENRES_ID = 107;
5208    private static final int AUDIO_GENRES_ID_MEMBERS = 108;
5209    private static final int AUDIO_GENRES_ALL_MEMBERS = 109;
5210    private static final int AUDIO_PLAYLISTS = 110;
5211    private static final int AUDIO_PLAYLISTS_ID = 111;
5212    private static final int AUDIO_PLAYLISTS_ID_MEMBERS = 112;
5213    private static final int AUDIO_PLAYLISTS_ID_MEMBERS_ID = 113;
5214    private static final int AUDIO_ARTISTS = 114;
5215    private static final int AUDIO_ARTISTS_ID = 115;
5216    private static final int AUDIO_ALBUMS = 116;
5217    private static final int AUDIO_ALBUMS_ID = 117;
5218    private static final int AUDIO_ARTISTS_ID_ALBUMS = 118;
5219    private static final int AUDIO_ALBUMART = 119;
5220    private static final int AUDIO_ALBUMART_ID = 120;
5221    private static final int AUDIO_ALBUMART_FILE_ID = 121;
5222
5223    private static final int VIDEO_MEDIA = 200;
5224    private static final int VIDEO_MEDIA_ID = 201;
5225    private static final int VIDEO_THUMBNAILS = 202;
5226    private static final int VIDEO_THUMBNAILS_ID = 203;
5227
5228    private static final int VOLUMES = 300;
5229    private static final int VOLUMES_ID = 301;
5230
5231    private static final int AUDIO_SEARCH_LEGACY = 400;
5232    private static final int AUDIO_SEARCH_BASIC = 401;
5233    private static final int AUDIO_SEARCH_FANCY = 402;
5234
5235    private static final int MEDIA_SCANNER = 500;
5236
5237    private static final int FS_ID = 600;
5238    private static final int VERSION = 601;
5239
5240    private static final int FILES = 700;
5241    private static final int FILES_ID = 701;
5242
5243    // Used only by the MTP implementation
5244    private static final int MTP_OBJECTS = 702;
5245    private static final int MTP_OBJECTS_ID = 703;
5246    private static final int MTP_OBJECT_REFERENCES = 704;
5247    // UsbReceiver calls insert() and delete() with this URI to tell us
5248    // when MTP is connected and disconnected
5249    private static final int MTP_CONNECTED = 705;
5250
5251    private static final UriMatcher URI_MATCHER =
5252            new UriMatcher(UriMatcher.NO_MATCH);
5253
5254    private static final String[] ID_PROJECTION = new String[] {
5255        MediaStore.MediaColumns._ID
5256    };
5257
5258    private static final String[] PATH_PROJECTION = new String[] {
5259        MediaStore.MediaColumns._ID,
5260            MediaStore.MediaColumns.DATA,
5261    };
5262
5263    private static final String[] MIME_TYPE_PROJECTION = new String[] {
5264            MediaStore.MediaColumns._ID, // 0
5265            MediaStore.MediaColumns.MIME_TYPE, // 1
5266    };
5267
5268    private static final String[] READY_FLAG_PROJECTION = new String[] {
5269            MediaStore.MediaColumns._ID,
5270            MediaStore.MediaColumns.DATA,
5271            Images.Media.MINI_THUMB_MAGIC
5272    };
5273
5274    private static final String OBJECT_REFERENCES_QUERY =
5275        "SELECT " + Audio.Playlists.Members.AUDIO_ID + " FROM audio_playlists_map"
5276        + " WHERE " + Audio.Playlists.Members.PLAYLIST_ID + "=?"
5277        + " ORDER BY " + Audio.Playlists.Members.PLAY_ORDER;
5278
5279    static
5280    {
5281        URI_MATCHER.addURI("media", "*/images/media", IMAGES_MEDIA);
5282        URI_MATCHER.addURI("media", "*/images/media/#", IMAGES_MEDIA_ID);
5283        URI_MATCHER.addURI("media", "*/images/thumbnails", IMAGES_THUMBNAILS);
5284        URI_MATCHER.addURI("media", "*/images/thumbnails/#", IMAGES_THUMBNAILS_ID);
5285
5286        URI_MATCHER.addURI("media", "*/audio/media", AUDIO_MEDIA);
5287        URI_MATCHER.addURI("media", "*/audio/media/#", AUDIO_MEDIA_ID);
5288        URI_MATCHER.addURI("media", "*/audio/media/#/genres", AUDIO_MEDIA_ID_GENRES);
5289        URI_MATCHER.addURI("media", "*/audio/media/#/genres/#", AUDIO_MEDIA_ID_GENRES_ID);
5290        URI_MATCHER.addURI("media", "*/audio/media/#/playlists", AUDIO_MEDIA_ID_PLAYLISTS);
5291        URI_MATCHER.addURI("media", "*/audio/media/#/playlists/#", AUDIO_MEDIA_ID_PLAYLISTS_ID);
5292        URI_MATCHER.addURI("media", "*/audio/genres", AUDIO_GENRES);
5293        URI_MATCHER.addURI("media", "*/audio/genres/#", AUDIO_GENRES_ID);
5294        URI_MATCHER.addURI("media", "*/audio/genres/#/members", AUDIO_GENRES_ID_MEMBERS);
5295        URI_MATCHER.addURI("media", "*/audio/genres/all/members", AUDIO_GENRES_ALL_MEMBERS);
5296        URI_MATCHER.addURI("media", "*/audio/playlists", AUDIO_PLAYLISTS);
5297        URI_MATCHER.addURI("media", "*/audio/playlists/#", AUDIO_PLAYLISTS_ID);
5298        URI_MATCHER.addURI("media", "*/audio/playlists/#/members", AUDIO_PLAYLISTS_ID_MEMBERS);
5299        URI_MATCHER.addURI("media", "*/audio/playlists/#/members/#", AUDIO_PLAYLISTS_ID_MEMBERS_ID);
5300        URI_MATCHER.addURI("media", "*/audio/artists", AUDIO_ARTISTS);
5301        URI_MATCHER.addURI("media", "*/audio/artists/#", AUDIO_ARTISTS_ID);
5302        URI_MATCHER.addURI("media", "*/audio/artists/#/albums", AUDIO_ARTISTS_ID_ALBUMS);
5303        URI_MATCHER.addURI("media", "*/audio/albums", AUDIO_ALBUMS);
5304        URI_MATCHER.addURI("media", "*/audio/albums/#", AUDIO_ALBUMS_ID);
5305        URI_MATCHER.addURI("media", "*/audio/albumart", AUDIO_ALBUMART);
5306        URI_MATCHER.addURI("media", "*/audio/albumart/#", AUDIO_ALBUMART_ID);
5307        URI_MATCHER.addURI("media", "*/audio/media/#/albumart", AUDIO_ALBUMART_FILE_ID);
5308
5309        URI_MATCHER.addURI("media", "*/video/media", VIDEO_MEDIA);
5310        URI_MATCHER.addURI("media", "*/video/media/#", VIDEO_MEDIA_ID);
5311        URI_MATCHER.addURI("media", "*/video/thumbnails", VIDEO_THUMBNAILS);
5312        URI_MATCHER.addURI("media", "*/video/thumbnails/#", VIDEO_THUMBNAILS_ID);
5313
5314        URI_MATCHER.addURI("media", "*/media_scanner", MEDIA_SCANNER);
5315
5316        URI_MATCHER.addURI("media", "*/fs_id", FS_ID);
5317        URI_MATCHER.addURI("media", "*/version", VERSION);
5318
5319        URI_MATCHER.addURI("media", "*/mtp_connected", MTP_CONNECTED);
5320
5321        URI_MATCHER.addURI("media", "*", VOLUMES_ID);
5322        URI_MATCHER.addURI("media", null, VOLUMES);
5323
5324        // Used by MTP implementation
5325        URI_MATCHER.addURI("media", "*/file", FILES);
5326        URI_MATCHER.addURI("media", "*/file/#", FILES_ID);
5327        URI_MATCHER.addURI("media", "*/object", MTP_OBJECTS);
5328        URI_MATCHER.addURI("media", "*/object/#", MTP_OBJECTS_ID);
5329        URI_MATCHER.addURI("media", "*/object/#/references", MTP_OBJECT_REFERENCES);
5330
5331        /**
5332         * @deprecated use the 'basic' or 'fancy' search Uris instead
5333         */
5334        URI_MATCHER.addURI("media", "*/audio/" + SearchManager.SUGGEST_URI_PATH_QUERY,
5335                AUDIO_SEARCH_LEGACY);
5336        URI_MATCHER.addURI("media", "*/audio/" + SearchManager.SUGGEST_URI_PATH_QUERY + "/*",
5337                AUDIO_SEARCH_LEGACY);
5338
5339        // used for search suggestions
5340        URI_MATCHER.addURI("media", "*/audio/search/" + SearchManager.SUGGEST_URI_PATH_QUERY,
5341                AUDIO_SEARCH_BASIC);
5342        URI_MATCHER.addURI("media", "*/audio/search/" + SearchManager.SUGGEST_URI_PATH_QUERY +
5343                "/*", AUDIO_SEARCH_BASIC);
5344
5345        // used by the music app's search activity
5346        URI_MATCHER.addURI("media", "*/audio/search/fancy", AUDIO_SEARCH_FANCY);
5347        URI_MATCHER.addURI("media", "*/audio/search/fancy/*", AUDIO_SEARCH_FANCY);
5348    }
5349
5350    @Override
5351    public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
5352        Collection<DatabaseHelper> foo = mDatabases.values();
5353        for (DatabaseHelper dbh: foo) {
5354            writer.println(dump(dbh, true));
5355        }
5356        writer.flush();
5357    }
5358
5359    private String dump(DatabaseHelper dbh, boolean dumpDbLog) {
5360        StringBuilder s = new StringBuilder();
5361        s.append(dbh.mName);
5362        s.append(": ");
5363        SQLiteDatabase db = dbh.getReadableDatabase();
5364        if (db == null) {
5365            s.append("null");
5366        } else {
5367            s.append("version " + db.getVersion() + ", ");
5368            Cursor c = db.query("files", new String[] {"count(*)"}, null, null, null, null, null);
5369            try {
5370                if (c != null && c.moveToFirst()) {
5371                    int num = c.getInt(0);
5372                    s.append(num + " rows, ");
5373                } else {
5374                    s.append("couldn't get row count, ");
5375                }
5376            } finally {
5377                if (c != null) {
5378                    c.close();
5379                }
5380            }
5381            s.append(dbh.mNumInserts + " inserts, ");
5382            s.append(dbh.mNumUpdates + " updates, ");
5383            s.append(dbh.mNumDeletes + " deletes, ");
5384            s.append(dbh.mNumQueries + " queries, ");
5385            if (dbh.mScanStartTime != 0) {
5386                s.append("scan started " + DateUtils.formatDateTime(getContext(),
5387                        dbh.mScanStartTime / 1000,
5388                        DateUtils.FORMAT_SHOW_DATE
5389                        | DateUtils.FORMAT_SHOW_TIME
5390                        | DateUtils.FORMAT_ABBREV_ALL));
5391                long now = dbh.mScanStopTime;
5392                if (now < dbh.mScanStartTime) {
5393                    now = SystemClock.currentTimeMicro();
5394                }
5395                s.append(" (" + DateUtils.formatElapsedTime(
5396                        (now - dbh.mScanStartTime) / 1000000) + ")");
5397                if (dbh.mScanStopTime < dbh.mScanStartTime) {
5398                    if (mMediaScannerVolume != null &&
5399                            dbh.mName.startsWith(mMediaScannerVolume)) {
5400                        s.append(" (ongoing)");
5401                    } else {
5402                        s.append(" (scanning " + mMediaScannerVolume + ")");
5403                    }
5404                }
5405            }
5406            if (dumpDbLog) {
5407                c = db.query("log", new String[] {"time", "message"},
5408                        null, null, null, null, "rowid");
5409                try {
5410                    if (c != null) {
5411                        while (c.moveToNext()) {
5412                            String when = c.getString(0);
5413                            String msg = c.getString(1);
5414                            s.append("\n" + when + " : " + msg);
5415                        }
5416                    }
5417                } finally {
5418                    if (c != null) {
5419                        c.close();
5420                    }
5421                }
5422            }
5423        }
5424        return s.toString();
5425    }
5426}
5427