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