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