-
Notifications
You must be signed in to change notification settings - Fork 0
/
MediaProvider.java
6740 lines (6055 loc) · 291 KB
/
MediaProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.providers.media;
import static android.app.PendingIntent.FLAG_CANCEL_CURRENT;
import static android.app.PendingIntent.FLAG_IMMUTABLE;
import static android.app.PendingIntent.FLAG_ONE_SHOT;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.os.Environment.buildPath;
import static android.os.ParcelFileDescriptor.MODE_APPEND;
import static android.os.ParcelFileDescriptor.MODE_CREATE;
import static android.os.ParcelFileDescriptor.MODE_READ_ONLY;
import static android.os.ParcelFileDescriptor.MODE_READ_WRITE;
import static android.os.ParcelFileDescriptor.MODE_TRUNCATE;
import static android.os.ParcelFileDescriptor.MODE_WRITE_ONLY;
import static android.os.Trace.TRACE_TAG_DATABASE;
import static android.provider.MediaStore.AUTHORITY;
import static android.provider.MediaStore.Downloads.PATTERN_DOWNLOADS_FILE;
import static android.provider.MediaStore.Downloads.isDownload;
import static android.provider.MediaStore.getVolumeName;
import static android.system.OsConstants.O_APPEND;
import static android.system.OsConstants.O_CLOEXEC;
import static android.system.OsConstants.O_CREAT;
import static android.system.OsConstants.O_NOFOLLOW;
import static android.system.OsConstants.O_RDONLY;
import static android.system.OsConstants.O_RDWR;
import static android.system.OsConstants.O_TRUNC;
import static android.system.OsConstants.O_WRONLY;
import static android.system.OsConstants.S_IRWXG;
import static android.system.OsConstants.S_IRWXU;
import static com.android.providers.media.LocalCallingIdentity.PERMISSION_IS_LEGACY;
import static com.android.providers.media.LocalCallingIdentity.PERMISSION_IS_REDACTION_NEEDED;
import static com.android.providers.media.LocalCallingIdentity.PERMISSION_IS_SYSTEM;
import static com.android.providers.media.LocalCallingIdentity.PERMISSION_READ_AUDIO;
import static com.android.providers.media.LocalCallingIdentity.PERMISSION_READ_IMAGES;
import static com.android.providers.media.LocalCallingIdentity.PERMISSION_READ_VIDEO;
import static com.android.providers.media.LocalCallingIdentity.PERMISSION_WRITE_AUDIO;
import static com.android.providers.media.LocalCallingIdentity.PERMISSION_WRITE_IMAGES;
import static com.android.providers.media.LocalCallingIdentity.PERMISSION_WRITE_VIDEO;
import android.annotation.BytesLong;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.AppGlobals;
import android.app.AppOpsManager;
import android.app.AppOpsManager.OnOpActiveChangedListener;
import android.app.PendingIntent;
import android.app.RecoverableSecurityException;
import android.app.RemoteAction;
import android.content.BroadcastReceiver;
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.UriMatcher;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionGroupInfo;
import android.content.res.AssetFileDescriptor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.AbstractCursor;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Icon;
import android.media.ExifInterface;
import android.media.MediaFile;
import android.media.ThumbnailUtils;
import android.mtp.MtpConstants;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Environment;
import android.os.FileUtils;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.ParcelFileDescriptor.OnCloseListener;
import android.os.RedactingFileDescriptor;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.Trace;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.storage.StorageEventListener;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.os.storage.VolumeInfo;
import android.os.storage.VolumeRecord;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.provider.Column;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.Audio.Playlists;
import android.provider.MediaStore.Downloads;
import android.provider.MediaStore.Files;
import android.provider.MediaStore.Files.FileColumns;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.ImageColumns;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Video;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import android.system.StructStat;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.LongArray;
import android.util.LongSparseArray;
import android.util.Pair;
import android.util.Size;
import android.util.SparseArray;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.os.BackgroundThread;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.IndentingPrintWriter;
import com.android.providers.media.scan.MediaScanner;
import com.android.providers.media.scan.ModernMediaScanner;
import com.android.providers.media.util.CachedSupplier;
import com.android.providers.media.util.IsoInterface;
import com.android.providers.media.util.XmpInterface;
import libcore.io.IoUtils;
import libcore.util.EmptyArray;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Media content provider. See {@link android.provider.MediaStore} for details.
* Separate databases are kept for each external storage card we see (using the
* card's ID as an index). The content visible at content://media/external/...
* changes with the card.
*/
public class MediaProvider extends ContentProvider {
public static final boolean ENABLE_MODERN_SCANNER = SystemProperties
.getBoolean("persist.sys.modern_scanner", true);
/**
* Regex that matches paths in all well-known package-specific directories,
* and which captures the package name as the first group.
*/
private static final Pattern PATTERN_OWNED_PATH = Pattern.compile(
"(?i)^/storage/[^/]+/(?:[0-9]+/)?Android/(?:data|media|obb|sandbox)/([^/]+)/.*");
/**
* Regex that matches paths under well-known storage paths.
*/
private static final Pattern PATTERN_STORAGE_PATH = Pattern.compile(
"(?i)^/storage/[^/]+/(?:[0-9]+/)?");
/**
* Regex that matches paths for {@link MediaColumns#RELATIVE_PATH}; it
* captures both top-level paths and sandboxed paths.
*/
private static final Pattern PATTERN_RELATIVE_PATH = Pattern.compile(
"(?i)^/storage/[^/]+/(?:[0-9]+/)?(Android/sandbox/([^/]+)/)?");
/**
* Regex that matches paths under well-known storage paths.
*/
private static final Pattern PATTERN_VOLUME_NAME = Pattern.compile(
"(?i)^/storage/([^/]+)");
/**
* Regex of a selection string that matches a specific ID.
*/
private static final Pattern PATTERN_SELECTION_ID = Pattern.compile(
"(?:image_id|video_id)\\s*=\\s*(\\d+)");
/**
* Set of {@link Cursor} columns that refer to raw filesystem paths.
*/
private static final ArrayMap<String, Object> sDataColumns = new ArrayMap<>();
{
sDataColumns.put(MediaStore.MediaColumns.DATA, null);
sDataColumns.put(MediaStore.Images.Thumbnails.DATA, null);
sDataColumns.put(MediaStore.Video.Thumbnails.DATA, null);
sDataColumns.put(MediaStore.Audio.PlaylistsColumns.DATA, null);
sDataColumns.put(MediaStore.Audio.AlbumColumns.ALBUM_ART, null);
}
private static final Object sCacheLock = new Object();
@GuardedBy("sCacheLock")
private static final List<VolumeInfo> sCachedVolumes = new ArrayList<>();
@GuardedBy("sCacheLock")
private static final Set<String> sCachedExternalVolumeNames = new ArraySet<>();
@GuardedBy("sCacheLock")
private static final Map<String, Collection<File>> sCachedVolumeScanPaths = new ArrayMap<>();
private void updateVolumes() {
synchronized (sCacheLock) {
sCachedVolumes.clear();
sCachedVolumes.addAll(mStorageManager.getVolumes());
sCachedExternalVolumeNames.clear();
sCachedExternalVolumeNames.addAll(MediaStore.getExternalVolumeNames(getContext()));
sCachedVolumeScanPaths.clear();
try {
sCachedVolumeScanPaths.put(MediaStore.VOLUME_INTERNAL,
MediaStore.getVolumeScanPaths(MediaStore.VOLUME_INTERNAL));
for (String volumeName : sCachedExternalVolumeNames) {
sCachedVolumeScanPaths.put(volumeName,
MediaStore.getVolumeScanPaths(volumeName));
}
} catch (FileNotFoundException e) {
throw new IllegalStateException(e.getMessage());
}
}
}
public static File getVolumePath(String volumeName) throws FileNotFoundException {
synchronized (sCacheLock) {
return MediaStore.getVolumePath(sCachedVolumes, volumeName);
}
}
public static Set<String> getExternalVolumeNames() {
synchronized (sCacheLock) {
return new ArraySet<>(sCachedExternalVolumeNames);
}
}
public static Collection<File> getVolumeScanPaths(String volumeName) {
synchronized (sCacheLock) {
return new ArrayList<>(sCachedVolumeScanPaths.get(volumeName));
}
}
private StorageManager mStorageManager;
private AppOpsManager mAppOpsManager;
private PackageManager mPackageManager;
private Size mThumbSize;
/**
* Map from UID to cached {@link LocalCallingIdentity}. Values are only
* maintained in this map while the UID is actively working with a
* performance-critical component, such as camera.
*/
@GuardedBy("mCachedCallingIdentity")
private final SparseArray<LocalCallingIdentity> mCachedCallingIdentity = new SparseArray<>();
private static volatile long sBackgroundDelay = 0;
private final OnOpActiveChangedListener mActiveListener = (code, uid, packageName, active) -> {
synchronized (mCachedCallingIdentity) {
if (active) {
mCachedCallingIdentity.put(uid,
LocalCallingIdentity.fromExternal(uid, packageName));
} else {
mCachedCallingIdentity.remove(uid);
}
if (mCachedCallingIdentity.size() > 0) {
sBackgroundDelay = 10 * DateUtils.SECOND_IN_MILLIS;
} else {
sBackgroundDelay = 0;
}
}
};
/**
* Calling identity state about on the current thread. Populated on demand,
* and invalidated by {@link #onCallingPackageChanged()} when each remote
* call is finished.
*/
private final ThreadLocal<LocalCallingIdentity> mCallingIdentity = ThreadLocal
.withInitial(() -> {
synchronized (mCachedCallingIdentity) {
final LocalCallingIdentity cached = mCachedCallingIdentity
.get(Binder.getCallingUid());
return (cached != null) ? cached : LocalCallingIdentity.fromBinder(this);
}
});
// In memory cache of path<->id mappings, to speed up inserts during media scan
@GuardedBy("mDirectoryCache")
private final ArrayMap<String, Long> mDirectoryCache = new ArrayMap<>();
private static final String[] sMediaTableColumns = new String[] {
FileColumns._ID,
FileColumns.MEDIA_TYPE,
};
private static final String[] sIdOnlyColumn = new String[] {
FileColumns._ID
};
private static final String[] sDataOnlyColumn = new String[] {
FileColumns.DATA
};
private static final String[] sPlaylistIdPlayOrder = new String[] {
Playlists.Members.PLAYLIST_ID,
Playlists.Members.PLAY_ORDER
};
private static final String ID_NOT_PARENT_CLAUSE =
"_id NOT IN (SELECT parent FROM files)";
private static final String CANONICAL = "canonical";
private BroadcastReceiver mMediaReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final StorageVolume sv = intent.getParcelableExtra(StorageVolume.EXTRA_STORAGE_VOLUME);
if (sv != null) {
final String volumeName;
if (sv.isPrimary()) {
volumeName = MediaStore.VOLUME_EXTERNAL_PRIMARY;
} else {
try {
volumeName = MediaStore.checkArgumentVolumeName(sv.getNormalizedUuid());
} catch (IllegalArgumentException ignored) {
return;
}
}
switch (intent.getAction()) {
case Intent.ACTION_MEDIA_MOUNTED:
attachVolume(volumeName);
break;
case Intent.ACTION_MEDIA_UNMOUNTED:
case Intent.ACTION_MEDIA_EJECT:
case Intent.ACTION_MEDIA_REMOVED:
case Intent.ACTION_MEDIA_BAD_REMOVAL:
detachVolume(volumeName);
break;
}
}
}
};
private final SQLiteDatabase.CustomFunction mObjectRemovedCallback =
new SQLiteDatabase.CustomFunction() {
@Override
public void callback(String[] args) {
// We could remove only the deleted entry from the cache, but that
// requires the path, which we don't have here, so instead we just
// clear the entire cache.
// TODO: include the path in the callback and only remove the affected
// entry from the cache
synchronized (mDirectoryCache) {
mDirectoryCache.clear();
}
}
};
/**
* Wrapper class for a specific database (associated with one particular
* external card, or with internal storage). Can open the actual database
* on demand, create and upgrade the schema, etc.
*/
static class DatabaseHelper extends SQLiteOpenHelper implements AutoCloseable {
final Context mContext;
final String mName;
final int mVersion;
final boolean mInternal; // True if this is the internal database
final boolean mEarlyUpgrade;
final SQLiteDatabase.CustomFunction mObjectRemovedCallback;
long mScanStartTime;
long mScanStopTime;
// In memory caches of artist and album data.
ArrayMap<String, Long> mArtistCache = new ArrayMap<String, Long>();
ArrayMap<String, Long> mAlbumCache = new ArrayMap<String, Long>();
public DatabaseHelper(Context context, String name, boolean internal,
boolean earlyUpgrade, SQLiteDatabase.CustomFunction objectRemovedCallback) {
this(context, name, getDatabaseVersion(context), internal, earlyUpgrade,
objectRemovedCallback);
}
public DatabaseHelper(Context context, String name, int version, boolean internal,
boolean earlyUpgrade, SQLiteDatabase.CustomFunction objectRemovedCallback) {
super(context, name, null, version);
mContext = context;
mName = name;
mVersion = version;
mInternal = internal;
mEarlyUpgrade = earlyUpgrade;
mObjectRemovedCallback = objectRemovedCallback;
setWriteAheadLoggingEnabled(true);
setIdleConnectionTimeout(IDLE_CONNECTION_TIMEOUT_MS);
}
@Override
public void onCreate(final SQLiteDatabase db) {
Log.v(TAG, "onCreate() for " + mName);
updateDatabase(mContext, db, mInternal, 0, mVersion);
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldV, final int newV) {
Log.v(TAG, "onUpgrade() for " + mName + " from " + oldV + " to " + newV);
updateDatabase(mContext, db, mInternal, oldV, newV);
}
@Override
public void onDowngrade(final SQLiteDatabase db, final int oldV, final int newV) {
Log.v(TAG, "onDowngrade() for " + mName + " from " + oldV + " to " + newV);
downgradeDatabase(mContext, db, mInternal, oldV, newV);
}
/**
* For devices that have removable storage, we support keeping multiple databases
* to allow users to switch between a number of cards.
* On such devices, touch this particular database and garbage collect old databases.
* An LRU cache system is used to clean up databases for old external
* storage volumes.
*/
@Override
public void onOpen(SQLiteDatabase db) {
if (mEarlyUpgrade) return; // Doing early upgrade.
if (mObjectRemovedCallback != null) {
db.addCustomFunction("_OBJECT_REMOVED", 1, mObjectRemovedCallback);
}
if (mInternal) return; // The internal database is kept separately.
// the code below is only needed on devices with removable storage
if (!Environment.isExternalStorageRemovable()) return;
// touch the database file to show it is most recently used
File file = new File(db.getPath());
long now = System.currentTimeMillis();
file.setLastModified(now);
// delete least recently used databases if we are over the limit
String[] databases = mContext.databaseList();
// Don't delete wal auxiliary files(db-shm and db-wal) directly because db file may
// not be deleted, and it will cause Disk I/O error when accessing this database.
List<String> dbList = new ArrayList<String>();
for (String database : databases) {
if (database != null && database.endsWith(".db")) {
dbList.add(database);
}
}
databases = dbList.toArray(new String[0]);
int count = databases.length;
int limit = MAX_EXTERNAL_DATABASES;
// delete external databases that have not been used in the past two months
long twoMonthsAgo = now - OBSOLETE_DATABASE_DB;
for (int i = 0; i < databases.length; i++) {
File other = mContext.getDatabasePath(databases[i]);
if (INTERNAL_DATABASE_NAME.equals(databases[i]) || file.equals(other)) {
databases[i] = null;
count--;
if (file.equals(other)) {
// reduce limit to account for the existence of the database we
// are about to open, which we removed from the list.
limit--;
}
} else {
long time = other.lastModified();
if (time < twoMonthsAgo) {
if (LOCAL_LOGV) Log.v(TAG, "Deleting old database " + databases[i]);
mContext.deleteDatabase(databases[i]);
databases[i] = null;
count--;
}
}
}
// delete least recently used databases until
// we are no longer over the limit
while (count > limit) {
int lruIndex = -1;
long lruTime = 0;
for (int i = 0; i < databases.length; i++) {
if (databases[i] != null) {
long time = mContext.getDatabasePath(databases[i]).lastModified();
if (lruTime == 0 || time < lruTime) {
lruIndex = i;
lruTime = time;
}
}
}
// delete least recently used database
if (lruIndex != -1) {
if (LOCAL_LOGV) Log.v(TAG, "Deleting old database " + databases[lruIndex]);
mContext.deleteDatabase(databases[lruIndex]);
databases[lruIndex] = null;
count--;
}
}
}
/**
* List of {@link Uri} that would have been sent directly via
* {@link ContentResolver#notifyChange}, but are instead being collected
* due to an ongoing transaction.
*/
private final ThreadLocal<List<Uri>> mNotifyChanges = new ThreadLocal<>();
public void beginTransaction() {
getWritableDatabase().beginTransaction();
mNotifyChanges.set(new ArrayList<>());
}
public void setTransactionSuccessful() {
getWritableDatabase().setTransactionSuccessful();
final List<Uri> uris = mNotifyChanges.get();
if (uris != null) {
BackgroundThread.getHandler().postDelayed(() -> {
for (Uri uri : uris) {
notifyChangeInternal(uri);
}
}, sBackgroundDelay);
}
mNotifyChanges.remove();
}
public void endTransaction() {
getWritableDatabase().endTransaction();
}
/**
* Notify that the given {@link Uri} has changed. This enqueues the
* notification if currently inside a transaction, and they'll be
* clustered and sent when the transaction completes.
*/
public void notifyChange(Uri uri) {
if (LOCAL_LOGV) Log.v(TAG, "Notifying " + uri);
final List<Uri> uris = mNotifyChanges.get();
if (uris != null) {
uris.add(uri);
} else {
BackgroundThread.getHandler().postDelayed(() -> {
notifyChangeInternal(uri);
}, sBackgroundDelay);
}
}
private void notifyChangeInternal(Uri uri) {
Trace.traceBegin(TRACE_TAG_DATABASE, "notifyChange");
try {
mContext.getContentResolver().notifyChange(uri, null);
} finally {
Trace.traceEnd(TRACE_TAG_DATABASE);
}
}
}
/**
* Apply {@link Consumer#accept} to the given {@link Uri}.
* <p>
* Since media items can be exposed through multiple collections or views,
* this method expands the single item being accepted to also accept all
* relevant views.
*/
public static void acceptWithExpansion(Consumer<Uri> consumer, Uri uri) {
final int match = matchUri(uri, true);
acceptWithExpansionInternal(consumer, uri, match);
try {
// When targeting a specific volume, we need to expand to also
// notify the top-level view
final String volumeName = getVolumeName(uri);
switch (volumeName) {
case MediaStore.VOLUME_INTERNAL:
case MediaStore.VOLUME_EXTERNAL:
// Already a top-level view, no need to expand
break;
default:
final List<String> segments = new ArrayList<>(uri.getPathSegments());
segments.set(0, MediaStore.VOLUME_EXTERNAL);
final Uri.Builder builder = uri.buildUpon().path(null);
for (String segment : segments) {
builder.appendPath(segment);
}
acceptWithExpansionInternal(consumer, builder.build(), match);
break;
}
} catch (IllegalArgumentException ignored) {
}
}
private static void acceptWithExpansionInternal(Consumer<Uri> consumer, Uri uri, int match) {
// Start by always notifying the base item
consumer.accept(uri);
// Some items can be exposed through multiple collections,
// so we need to notify all possible views of those items
switch (match) {
case AUDIO_MEDIA_ID:
case VIDEO_MEDIA_ID:
case IMAGES_MEDIA_ID: {
final String volumeName = getVolumeName(uri);
final long id = ContentUris.parseId(uri);
consumer.accept(Files.getContentUri(volumeName, id));
consumer.accept(Downloads.getContentUri(volumeName, id));
break;
}
case AUDIO_MEDIA:
case VIDEO_MEDIA:
case IMAGES_MEDIA: {
final String volumeName = getVolumeName(uri);
consumer.accept(Files.getContentUri(volumeName));
consumer.accept(Downloads.getContentUri(volumeName));
break;
}
case FILES_ID:
case DOWNLOADS_ID: {
final String volumeName = getVolumeName(uri);
final long id = ContentUris.parseId(uri);
consumer.accept(Audio.Media.getContentUri(volumeName, id));
consumer.accept(Video.Media.getContentUri(volumeName, id));
consumer.accept(Images.Media.getContentUri(volumeName, id));
break;
}
case FILES:
case DOWNLOADS: {
final String volumeName = getVolumeName(uri);
consumer.accept(Audio.Media.getContentUri(volumeName));
consumer.accept(Video.Media.getContentUri(volumeName));
consumer.accept(Images.Media.getContentUri(volumeName));
break;
}
}
// Any changing audio items mean we probably need to invalidate all
// indexed views built from that media
switch (match) {
case AUDIO_MEDIA:
case AUDIO_MEDIA_ID: {
final String volumeName = getVolumeName(uri);
consumer.accept(Audio.Genres.getContentUri(volumeName));
consumer.accept(Audio.Playlists.getContentUri(volumeName));
consumer.accept(Audio.Artists.getContentUri(volumeName));
consumer.accept(Audio.Albums.getContentUri(volumeName));
break;
}
}
}
private static final String[] sDefaultFolderNames = {
Environment.DIRECTORY_MUSIC,
Environment.DIRECTORY_PODCASTS,
Environment.DIRECTORY_RINGTONES,
Environment.DIRECTORY_ALARMS,
Environment.DIRECTORY_NOTIFICATIONS,
Environment.DIRECTORY_PICTURES,
Environment.DIRECTORY_MOVIES,
Environment.DIRECTORY_DOWNLOADS,
Environment.DIRECTORY_DCIM,
};
/**
* This method cleans up any files created by android.media.MiniThumbFile, removed after P.
* It's triggered during database update only, in order to run only once.
*/
private static void deleteLegacyThumbnailData() {
File directory = new File(Environment.getExternalStorageDirectory(), "/DCIM/.thumbnails");
FilenameFilter filter = (dir, filename) -> filename.startsWith(".thumbdata");
for (File f : ArrayUtils.defeatNullable(directory.listFiles(filter))) {
if (!f.delete()) {
Log.e(TAG, "Failed to delete legacy thumbnail data " + f.getAbsolutePath());
}
}
}
/**
* Ensure that default folders are created on mounted primary storage
* devices. We only do this once per volume so we don't annoy the user if
* deleted manually.
*/
private void ensureDefaultFolders(String volumeName, DatabaseHelper helper, SQLiteDatabase db) {
try {
final File path = getVolumePath(volumeName);
final StorageVolume vol = mStorageManager.getStorageVolume(path);
final String key;
if (VolumeInfo.ID_EMULATED_INTERNAL.equals(vol.getId())) {
key = "created_default_folders";
} else {
key = "created_default_folders_" + vol.getNormalizedUuid();
}
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getContext());
if (prefs.getInt(key, 0) == 0) {
for (String folderName : sDefaultFolderNames) {
final File folder = new File(vol.getPathFile(), folderName);
if (!folder.exists()) {
folder.mkdirs();
insertDirectory(helper, db, folder.getAbsolutePath());
}
}
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(key, 1);
editor.commit();
}
} catch (IOException e) {
Log.w(TAG, "Failed to ensure default folders for " + volumeName, e);
}
}
public static int getDatabaseVersion(Context context) {
try {
return context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
throw new RuntimeException("couldn't get version code for " + context);
}
}
@Override
public boolean onCreate() {
final Context context = getContext();
// Enable verbose transport logging when requested
setTransportLoggingEnabled(LOCAL_LOGV);
// Shift call statistics back to the original caller
Binder.setProxyTransactListener(
new Binder.PropagateWorkSourceTransactListener());
mStorageManager = context.getSystemService(StorageManager.class);
mAppOpsManager = context.getSystemService(AppOpsManager.class);
mPackageManager = context.getPackageManager();
// Reasonable thumbnail size is half of the smallest screen edge width
final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
final int thumbSize = Math.min(metrics.widthPixels, metrics.heightPixels) / 2;
mThumbSize = new Size(thumbSize, thumbSize);
mInternalDatabase = new DatabaseHelper(context, INTERNAL_DATABASE_NAME, true,
false, mObjectRemovedCallback);
mExternalDatabase = new DatabaseHelper(context, EXTERNAL_DATABASE_NAME, false,
false, mObjectRemovedCallback);
final IntentFilter filter = new IntentFilter();
filter.setPriority(10);
filter.addDataScheme("file");
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_EJECT);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
context.registerReceiver(mMediaReceiver, filter);
// Watch for invalidation of cached volumes
mStorageManager.registerListener(new StorageEventListener() {
@Override
public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
updateVolumes();
}
});
updateVolumes();
attachVolume(MediaStore.VOLUME_INTERNAL);
// Attach all currently mounted external volumes
for (String volumeName : getExternalVolumeNames()) {
attachVolume(volumeName);
}
// Watch for performance-sensitive activity
mAppOpsManager.startWatchingActive(new int[] {
AppOpsManager.OP_CAMERA
}, mActiveListener);
return true;
}
@Override
public void onCallingPackageChanged() {
// Identity of the current thread has changed, so invalidate caches
mCallingIdentity.remove();
}
public LocalCallingIdentity clearLocalCallingIdentity() {
final LocalCallingIdentity token = mCallingIdentity.get();
mCallingIdentity.set(LocalCallingIdentity.fromSelf());
return token;
}
public void restoreLocalCallingIdentity(LocalCallingIdentity token) {
mCallingIdentity.set(token);
}
public void onIdleMaintenance(@NonNull CancellationSignal signal) {
final DatabaseHelper helper = mExternalDatabase;
final SQLiteDatabase db = helper.getReadableDatabase();
// Scan all volumes to resolve any staleness
for (String volumeName : getExternalVolumeNames()) {
// Possibly bail before digging into each volume
signal.throwIfCanceled();
try {
final File file = getVolumePath(volumeName);
MediaService.onScanVolume(getContext(), Uri.fromFile(file));
} catch (IOException e) {
Log.w(TAG, e);
}
}
// Delete any stale thumbnails
pruneThumbnails(signal);
// Finished orphaning any content whose package no longer exists
final ArraySet<String> unknownPackages = new ArraySet<>();
try (Cursor c = db.query(true, "files", new String[] { "owner_package_name" },
null, null, null, null, null, null, signal)) {
while (c.moveToNext()) {
final String packageName = c.getString(0);
if (TextUtils.isEmpty(packageName)) continue;
try {
getContext().getPackageManager().getPackageInfo(packageName,
PackageManager.MATCH_UNINSTALLED_PACKAGES);
} catch (NameNotFoundException e) {
unknownPackages.add(packageName);
}
}
}
Log.d(TAG, "Found " + unknownPackages.size() + " unknown packages");
for (String packageName : unknownPackages) {
onPackageOrphaned(packageName);
}
// Delete any expired content; we're paranoid about wildly changing
// clocks, so only delete items within the last week
final long from = ((System.currentTimeMillis() - DateUtils.WEEK_IN_MILLIS) / 1000);
final long to = (System.currentTimeMillis() / 1000);
try (Cursor c = db.query(true, "files", new String[] { "volume_name", "_id" },
FileColumns.DATE_EXPIRES + " BETWEEN " + from + " AND " + to, null,
null, null, null, null, signal)) {
while (c.moveToNext()) {
final String volumeName = c.getString(0);
final long id = c.getLong(1);
delete(Files.getContentUri(volumeName, id), null, null);
}
Log.d(TAG, "Deleted " + c.getCount() + " expired items on " + helper.mName);
}
// Forget any stale volumes
final long lastWeek = System.currentTimeMillis() - DateUtils.WEEK_IN_MILLIS;
for (VolumeRecord rec : mStorageManager.getVolumeRecords()) {
// Skip volumes without valid UUIDs
if (TextUtils.isEmpty(rec.fsUuid)) continue;
// Skip volumes that are currently mounted
final VolumeInfo vol = mStorageManager.findVolumeByUuid(rec.fsUuid);
if (vol != null && vol.isMountedReadable()) continue;
if (rec.lastSeenMillis > 0 && rec.lastSeenMillis < lastWeek) {
final int num = db.delete("files", FileColumns.VOLUME_NAME + "=?",
new String[] { rec.getNormalizedFsUuid() });
Log.d(TAG, "Forgot " + num + " stale items from " + rec.fsUuid);
}
}
}
public void onPackageOrphaned(String packageName) {
final DatabaseHelper helper = mExternalDatabase;
final SQLiteDatabase db = helper.getWritableDatabase();
final ContentValues values = new ContentValues();
values.putNull(FileColumns.OWNER_PACKAGE_NAME);
final int count = db.update("files", values,
"owner_package_name=?", new String[] { packageName });
if (count > 0) {
Log.d(TAG, "Orphaned " + count + " items belonging to "
+ packageName + " on " + helper.mName);
}
}
private void enforceShellRestrictions() {
if (UserHandle.getCallingAppId() == android.os.Process.SHELL_UID
&& getContext().getSystemService(UserManager.class)
.hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER)) {
throw new SecurityException(
"Shell user cannot access files for user " + UserHandle.myUserId());
}
}
@Override
protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
throws SecurityException {
enforceShellRestrictions();
return super.enforceReadPermissionInner(uri, callingPkg, callerToken);
}
@Override
protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
throws SecurityException {
enforceShellRestrictions();
return super.enforceWritePermissionInner(uri, callingPkg, callerToken);
}
@VisibleForTesting
static void makePristineSchema(SQLiteDatabase db) {
// drop all triggers
Cursor c = db.query("sqlite_master", new String[] {"name"}, "type is 'trigger'",
null, null, null, null);
while (c.moveToNext()) {
if (c.getString(0).startsWith("sqlite_")) continue;
db.execSQL("DROP TRIGGER IF EXISTS " + c.getString(0));
}
c.close();
// drop all views
c = db.query("sqlite_master", new String[] {"name"}, "type is 'view'",
null, null, null, null);
while (c.moveToNext()) {
if (c.getString(0).startsWith("sqlite_")) continue;
db.execSQL("DROP VIEW IF EXISTS " + c.getString(0));
}
c.close();
// drop all indexes
c = db.query("sqlite_master", new String[] {"name"}, "type is 'index'",
null, null, null, null);
while (c.moveToNext()) {
if (c.getString(0).startsWith("sqlite_")) continue;
db.execSQL("DROP INDEX IF EXISTS " + c.getString(0));
}
c.close();
// drop all tables
c = db.query("sqlite_master", new String[] {"name"}, "type is 'table'",
null, null, null, null);
while (c.moveToNext()) {
if (c.getString(0).startsWith("sqlite_")) continue;