-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMediaDocumentsProvider.java
1382 lines (1219 loc) · 58.5 KB
/
MediaDocumentsProvider.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) 2013 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.content.ContentResolver.EXTRA_SIZE;
import android.annotation.Nullable;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.MimeTypeFilter;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MatrixCursor.RowBuilder;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.media.ExifInterface;
import android.media.MediaMetadata;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.BaseColumns;
import android.provider.DocumentsContract;
import android.provider.DocumentsContract.Document;
import android.provider.DocumentsContract.Root;
import android.provider.DocumentsProvider;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Audio.AlbumColumns;
import android.provider.MediaStore.Audio.Albums;
import android.provider.MediaStore.Audio.ArtistColumns;
import android.provider.MediaStore.Audio.Artists;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.Files.FileColumns;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.ImageColumns;
import android.provider.MediaStore.Video;
import android.provider.MediaStore.Video.VideoColumns;
import android.provider.MetadataReader;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.util.Log;
import android.util.Pair;
import com.android.internal.os.BackgroundThread;
import libcore.io.IoUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Presents a {@link DocumentsContract} view of {@link MediaProvider} external
* contents.
*/
public class MediaDocumentsProvider extends DocumentsProvider {
private static final String TAG = "MediaDocumentsProvider";
private static final String AUTHORITY = "com.android.providers.media.documents";
private static final String SUPPORTED_QUERY_ARGS = joinNewline(
DocumentsContract.QUERY_ARG_DISPLAY_NAME,
DocumentsContract.QUERY_ARG_FILE_SIZE_OVER,
DocumentsContract.QUERY_ARG_LAST_MODIFIED_AFTER,
DocumentsContract.QUERY_ARG_MIME_TYPES);
private static final String[] DEFAULT_ROOT_PROJECTION = new String[] {
Root.COLUMN_ROOT_ID, Root.COLUMN_FLAGS, Root.COLUMN_ICON,
Root.COLUMN_TITLE, Root.COLUMN_DOCUMENT_ID, Root.COLUMN_MIME_TYPES,
Root.COLUMN_QUERY_ARGS
};
private static final String[] DEFAULT_DOCUMENT_PROJECTION = new String[] {
Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE, Document.COLUMN_DISPLAY_NAME,
Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE,
};
private static final String IMAGE_MIME_TYPES = joinNewline("image/*");
private static final String VIDEO_MIME_TYPES = joinNewline("video/*");
private static final String AUDIO_MIME_TYPES = joinNewline(
"audio/*", "application/ogg", "application/x-flac");
private static final String TYPE_IMAGES_ROOT = "images_root";
private static final String TYPE_IMAGES_BUCKET = "images_bucket";
private static final String TYPE_IMAGE = "image";
private static final String TYPE_VIDEOS_ROOT = "videos_root";
private static final String TYPE_VIDEOS_BUCKET = "videos_bucket";
private static final String TYPE_VIDEO = "video";
private static final String TYPE_AUDIO_ROOT = "audio_root";
private static final String TYPE_AUDIO = "audio";
private static final String TYPE_ARTIST = "artist";
private static final String TYPE_ALBUM = "album";
private static boolean sReturnedImagesEmpty = false;
private static boolean sReturnedVideosEmpty = false;
private static boolean sReturnedAudioEmpty = false;
private static String joinNewline(String... args) {
return TextUtils.join("\n", args);
}
public static final String METADATA_KEY_AUDIO = "android.media.metadata.audio";
public static final String METADATA_KEY_VIDEO = "android.media.metadata.video";
// Video lat/long are just that. Lat/long. Unlike EXIF where the values are
// in fact some funky string encoding. So we add our own contstant to convey coords.
public static final String METADATA_VIDEO_LATITUDE = "android.media.metadata.video:latitude";
public static final String METADATA_VIDEO_LONGITUTE = "android.media.metadata.video:longitude";
/*
* A mapping between media colums and metadata tag names. These keys of the
* map form the projection for queries against the media store database.
*/
private static final Map<String, String> IMAGE_COLUMN_MAP = new HashMap<>();
private static final Map<String, String> VIDEO_COLUMN_MAP = new HashMap<>();
private static final Map<String, String> AUDIO_COLUMN_MAP = new HashMap<>();
static {
/**
* Note that for images (jpegs at least) we'll first try an alternate
* means of extracting metadata, one that provides more data. But if
* that fails, or if the image type is not JPEG, we fall back to these columns.
*/
IMAGE_COLUMN_MAP.put(ImageColumns.WIDTH, ExifInterface.TAG_IMAGE_WIDTH);
IMAGE_COLUMN_MAP.put(ImageColumns.HEIGHT, ExifInterface.TAG_IMAGE_LENGTH);
IMAGE_COLUMN_MAP.put(ImageColumns.DATE_TAKEN, ExifInterface.TAG_DATETIME);
IMAGE_COLUMN_MAP.put(ImageColumns.LATITUDE, ExifInterface.TAG_GPS_LATITUDE);
IMAGE_COLUMN_MAP.put(ImageColumns.LONGITUDE, ExifInterface.TAG_GPS_LONGITUDE);
VIDEO_COLUMN_MAP.put(VideoColumns.DURATION, MediaMetadata.METADATA_KEY_DURATION);
VIDEO_COLUMN_MAP.put(VideoColumns.HEIGHT, ExifInterface.TAG_IMAGE_LENGTH);
VIDEO_COLUMN_MAP.put(VideoColumns.WIDTH, ExifInterface.TAG_IMAGE_WIDTH);
VIDEO_COLUMN_MAP.put(VideoColumns.LATITUDE, METADATA_VIDEO_LATITUDE);
VIDEO_COLUMN_MAP.put(VideoColumns.LONGITUDE, METADATA_VIDEO_LONGITUTE);
VIDEO_COLUMN_MAP.put(VideoColumns.DATE_TAKEN, MediaMetadata.METADATA_KEY_DATE);
AUDIO_COLUMN_MAP.put(AudioColumns.ARTIST, MediaMetadata.METADATA_KEY_ARTIST);
AUDIO_COLUMN_MAP.put(AudioColumns.COMPOSER, MediaMetadata.METADATA_KEY_COMPOSER);
AUDIO_COLUMN_MAP.put(AudioColumns.ALBUM, MediaMetadata.METADATA_KEY_ALBUM);
AUDIO_COLUMN_MAP.put(AudioColumns.YEAR, MediaMetadata.METADATA_KEY_YEAR);
AUDIO_COLUMN_MAP.put(AudioColumns.DURATION, MediaMetadata.METADATA_KEY_DURATION);
}
private void copyNotificationUri(MatrixCursor result, Cursor cursor) {
result.setNotificationUri(getContext().getContentResolver(), cursor.getNotificationUri());
}
@Override
public boolean onCreate() {
notifyRootsChanged(getContext());
return true;
}
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);
}
private static void notifyRootsChanged(Context context) {
context.getContentResolver()
.notifyChange(DocumentsContract.buildRootsUri(AUTHORITY), null, false);
}
/**
* When inserting the first item of each type, we need to trigger a roots
* refresh to clear a previously reported {@link Root#FLAG_EMPTY}.
*/
static void onMediaStoreInsert(Context context, String volumeName, int type, long id) {
BackgroundThread.getExecutor().execute(() -> {
if (!"external".equals(volumeName)) return;
if (type == FileColumns.MEDIA_TYPE_IMAGE && sReturnedImagesEmpty) {
sReturnedImagesEmpty = false;
notifyRootsChanged(context);
} else if (type == FileColumns.MEDIA_TYPE_VIDEO && sReturnedVideosEmpty) {
sReturnedVideosEmpty = false;
notifyRootsChanged(context);
} else if (type == FileColumns.MEDIA_TYPE_AUDIO && sReturnedAudioEmpty) {
sReturnedAudioEmpty = false;
notifyRootsChanged(context);
}
});
}
/**
* When deleting an item, we need to revoke any outstanding Uri grants.
*/
static void onMediaStoreDelete(Context context, String volumeName, int type, long id) {
BackgroundThread.getExecutor().execute(() -> {
if (!"external".equals(volumeName)) return;
if (type == FileColumns.MEDIA_TYPE_IMAGE) {
final Uri uri = DocumentsContract.buildDocumentUri(
AUTHORITY, getDocIdForIdent(TYPE_IMAGE, id));
context.revokeUriPermission(uri, ~0);
notifyRootsChanged(context);
} else if (type == FileColumns.MEDIA_TYPE_VIDEO) {
final Uri uri = DocumentsContract.buildDocumentUri(
AUTHORITY, getDocIdForIdent(TYPE_VIDEO, id));
context.revokeUriPermission(uri, ~0);
notifyRootsChanged(context);
} else if (type == FileColumns.MEDIA_TYPE_AUDIO) {
final Uri uri = DocumentsContract.buildDocumentUri(
AUTHORITY, getDocIdForIdent(TYPE_AUDIO, id));
context.revokeUriPermission(uri, ~0);
notifyRootsChanged(context);
}
});
}
static void revokeAllUriGrants(Context context) {
context.revokeUriPermission(DocumentsContract.buildBaseDocumentUri(AUTHORITY),
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
private static class Ident {
public String type;
public long id;
}
private static Ident getIdentForDocId(String docId) {
final Ident ident = new Ident();
final int split = docId.indexOf(':');
if (split == -1) {
ident.type = docId;
ident.id = -1;
} else {
ident.type = docId.substring(0, split);
ident.id = Long.parseLong(docId.substring(split + 1));
}
return ident;
}
private static String getDocIdForIdent(String type, long id) {
return type + ":" + id;
}
private static String[] resolveRootProjection(String[] projection) {
return projection != null ? projection : DEFAULT_ROOT_PROJECTION;
}
private static String[] resolveDocumentProjection(String[] projection) {
return projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION;
}
private static Pair<String, String[]> buildSearchSelection(String displayName,
String[] mimeTypes, long lastModifiedAfter, long fileSizeOver, String columnDisplayName,
String columnMimeType, String columnLastModified, String columnFileSize) {
StringBuilder selection = new StringBuilder();
final ArrayList<String> selectionArgs = new ArrayList<>();
if (!displayName.isEmpty()) {
selection.append(columnDisplayName + " LIKE ?");
selectionArgs.add("%" + displayName + "%");
}
if (lastModifiedAfter != -1) {
if (selection.length() > 0) {
selection.append(" AND ");
}
// The units of DATE_MODIFIED are seconds since 1970.
// The units of lastModified are milliseconds since 1970.
selection.append(columnLastModified + " > " + lastModifiedAfter / 1000);
}
if (fileSizeOver != -1) {
if (selection.length() > 0) {
selection.append(" AND ");
}
selection.append(columnFileSize + " > " + fileSizeOver);
}
if (mimeTypes != null && mimeTypes.length > 0) {
for (int i = 0; i < mimeTypes.length; i++) {
final String type = mimeTypes[i];
if (i == 0) {
if (selection.length() > 0) {
selection.append(" AND ");
}
selection.append(columnMimeType + " IN ( ?");
} else {
selection.append(", ?");
}
selectionArgs.add(type);
}
selection.append(" )");
}
return new Pair<>(selection.toString(), selectionArgs.toArray(new String[0]));
}
/**
* Check whether filter mime type and get the matched mime types.
* If we don't need to filter mime type, the matchedMimeTypes will be empty.
*
* @param mimeTypes the mime types to test
* @param filter the filter. It is "image/*" or "video/*" or "audio/*".
* @param matchedMimeTypes the matched mime types will add into this.
* @return true, should do mime type filter. false, no need.
*/
private static boolean shouldFilterMimeType(String[] mimeTypes, String filter,
List<String> matchedMimeTypes) {
matchedMimeTypes.clear();
boolean shouldQueryMimeType = true;
if (mimeTypes != null) {
for (int i = 0; i < mimeTypes.length; i++) {
// If the mime type is "*/*" or "image/*" or "video/*" or "audio/*",
// we don't need to filter mime type.
if (TextUtils.equals(mimeTypes[i], "*/*") ||
TextUtils.equals(mimeTypes[i], filter)) {
matchedMimeTypes.clear();
shouldQueryMimeType = false;
break;
}
if (MimeTypeFilter.matches(mimeTypes[i], filter)) {
matchedMimeTypes.add(mimeTypes[i]);
}
}
} else {
shouldQueryMimeType = false;
}
return shouldQueryMimeType;
}
private Uri getUriForDocumentId(String docId) {
final Ident ident = getIdentForDocId(docId);
if (TYPE_IMAGE.equals(ident.type) && ident.id != -1) {
return ContentUris.withAppendedId(
Images.Media.EXTERNAL_CONTENT_URI, ident.id);
} else if (TYPE_VIDEO.equals(ident.type) && ident.id != -1) {
return ContentUris.withAppendedId(
Video.Media.EXTERNAL_CONTENT_URI, ident.id);
} else if (TYPE_AUDIO.equals(ident.type) && ident.id != -1) {
return ContentUris.withAppendedId(
Audio.Media.EXTERNAL_CONTENT_URI, ident.id);
} else {
throw new UnsupportedOperationException("Unsupported document " + docId);
}
}
@Override
public void deleteDocument(String docId) throws FileNotFoundException {
final Uri target = getUriForDocumentId(docId);
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
getContext().getContentResolver().delete(target, null, null);
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public @Nullable Bundle getDocumentMetadata(String docId) throws FileNotFoundException {
String mimeType = getDocumentType(docId);
if (MetadataReader.isSupportedMimeType(mimeType)) {
return getDocumentMetadataFromStream(docId, mimeType);
} else {
return getDocumentMetadataFromIndex(docId);
}
}
private @Nullable Bundle getDocumentMetadataFromStream(String docId, String mimeType) {
assert MetadataReader.isSupportedMimeType(mimeType);
InputStream stream = null;
try {
stream = new ParcelFileDescriptor.AutoCloseInputStream(
openDocument(docId, "r", null));
Bundle metadata = new Bundle();
MetadataReader.getMetadata(metadata, stream, mimeType, null);
return metadata;
} catch (IOException io) {
return null;
} finally {
IoUtils.closeQuietly(stream);
}
}
public @Nullable Bundle getDocumentMetadataFromIndex(String docId)
throws FileNotFoundException {
final Ident ident = getIdentForDocId(docId);
Map<String, String> columnMap = null;
String tagType;
Uri query;
switch (ident.type) {
case TYPE_IMAGE:
columnMap = IMAGE_COLUMN_MAP;
tagType = DocumentsContract.METADATA_EXIF;
query = Images.Media.EXTERNAL_CONTENT_URI;
break;
case TYPE_VIDEO:
columnMap = VIDEO_COLUMN_MAP;
tagType = METADATA_KEY_VIDEO;
query = Video.Media.EXTERNAL_CONTENT_URI;
break;
case TYPE_AUDIO:
columnMap = AUDIO_COLUMN_MAP;
tagType = METADATA_KEY_AUDIO;
query = Audio.Media.EXTERNAL_CONTENT_URI;
break;
default:
// Unsupported file type.
throw new FileNotFoundException(
"Metadata request for unsupported file type: " + ident.type);
}
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
Bundle result = null;
final ContentResolver resolver = getContext().getContentResolver();
Collection<String> columns = columnMap.keySet();
String[] projection = columns.toArray(new String[columns.size()]);
try {
cursor = resolver.query(
query,
projection,
BaseColumns._ID + "=?",
new String[]{Long.toString(ident.id)},
null);
if (!cursor.moveToFirst()) {
throw new FileNotFoundException("Can't find document id: " + docId);
}
final Bundle metadata = extractMetadataFromCursor(cursor, columnMap);
result = new Bundle();
result.putBundle(tagType, metadata);
result.putStringArray(
DocumentsContract.METADATA_TYPES,
new String[]{tagType});
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
private static Bundle extractMetadataFromCursor(Cursor cursor, Map<String, String> columns) {
assert (cursor.getCount() == 1);
final Bundle metadata = new Bundle();
for (String col : columns.keySet()) {
int index = cursor.getColumnIndex(col);
String bundleTag = columns.get(col);
// Special case to be able to pull longs out of a cursor, as long is not a supported
// field of getType.
if (ExifInterface.TAG_DATETIME.equals(bundleTag)) {
// formate string to be consistent with how EXIF interface formats the date.
long date = cursor.getLong(index);
String format = DateFormat.getBestDateTimePattern(Locale.getDefault(),
"MMM dd, yyyy, hh:mm");
metadata.putString(bundleTag, DateFormat.format(format, date).toString());
continue;
}
switch (cursor.getType(index)) {
case Cursor.FIELD_TYPE_INTEGER:
metadata.putInt(bundleTag, cursor.getInt(index));
break;
case Cursor.FIELD_TYPE_FLOAT:
//Errors on the side of greater precision since interface doesnt support doubles
metadata.putFloat(bundleTag, cursor.getFloat(index));
break;
case Cursor.FIELD_TYPE_STRING:
metadata.putString(bundleTag, cursor.getString(index));
break;
case Cursor.FIELD_TYPE_BLOB:
Log.d(TAG, "Unsupported type, blob, for col: " + bundleTag);
break;
case Cursor.FIELD_TYPE_NULL:
Log.d(TAG, "Unsupported type, null, for col: " + bundleTag);
break;
default:
throw new RuntimeException("Data type not supported");
}
}
return metadata;
}
@Override
public Cursor queryRoots(String[] projection) throws FileNotFoundException {
final MatrixCursor result = new MatrixCursor(resolveRootProjection(projection));
includeImagesRoot(result);
includeVideosRoot(result);
includeAudioRoot(result);
return result;
}
@Override
public Cursor queryDocument(String docId, String[] projection) throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
final Ident ident = getIdentForDocId(docId);
final String[] queryArgs = new String[] { Long.toString(ident.id) } ;
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
if (TYPE_IMAGES_ROOT.equals(ident.type)) {
// single root
includeImagesRootDocument(result);
} else if (TYPE_IMAGES_BUCKET.equals(ident.type)) {
// single bucket
cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
ImagesBucketQuery.PROJECTION, ImageColumns.BUCKET_ID + "=?",
queryArgs, ImagesBucketQuery.SORT_ORDER);
copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeImagesBucket(result, cursor);
}
} else if (TYPE_IMAGE.equals(ident.type)) {
// single image
cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
ImageQuery.PROJECTION, BaseColumns._ID + "=?", queryArgs,
null);
copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeImage(result, cursor);
}
} else if (TYPE_VIDEOS_ROOT.equals(ident.type)) {
// single root
includeVideosRootDocument(result);
} else if (TYPE_VIDEOS_BUCKET.equals(ident.type)) {
// single bucket
cursor = resolver.query(Video.Media.EXTERNAL_CONTENT_URI,
VideosBucketQuery.PROJECTION, VideoColumns.BUCKET_ID + "=?",
queryArgs, VideosBucketQuery.SORT_ORDER);
copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeVideosBucket(result, cursor);
}
} else if (TYPE_VIDEO.equals(ident.type)) {
// single video
cursor = resolver.query(Video.Media.EXTERNAL_CONTENT_URI,
VideoQuery.PROJECTION, BaseColumns._ID + "=?", queryArgs,
null);
copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeVideo(result, cursor);
}
} else if (TYPE_AUDIO_ROOT.equals(ident.type)) {
// single root
includeAudioRootDocument(result);
} else if (TYPE_ARTIST.equals(ident.type)) {
// single artist
cursor = resolver.query(Artists.EXTERNAL_CONTENT_URI,
ArtistQuery.PROJECTION, BaseColumns._ID + "=?", queryArgs,
null);
copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeArtist(result, cursor);
}
} else if (TYPE_ALBUM.equals(ident.type)) {
// single album
cursor = resolver.query(Albums.EXTERNAL_CONTENT_URI,
AlbumQuery.PROJECTION, BaseColumns._ID + "=?", queryArgs,
null);
copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeAlbum(result, cursor);
}
} else if (TYPE_AUDIO.equals(ident.type)) {
// single song
cursor = resolver.query(Audio.Media.EXTERNAL_CONTENT_URI,
SongQuery.PROJECTION, BaseColumns._ID + "=?", queryArgs,
null);
copyNotificationUri(result, cursor);
if (cursor.moveToFirst()) {
includeAudio(result, cursor);
}
} else {
throw new UnsupportedOperationException("Unsupported document " + docId);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
@Override
public Cursor queryChildDocuments(String docId, String[] projection, String sortOrder)
throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
final Ident ident = getIdentForDocId(docId);
final String[] queryArgs = new String[] { Long.toString(ident.id) } ;
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
if (TYPE_IMAGES_ROOT.equals(ident.type)) {
// include all unique buckets
cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
ImagesBucketQuery.PROJECTION, null, null, ImagesBucketQuery.SORT_ORDER);
// multiple orders
copyNotificationUri(result, cursor);
long lastId = Long.MIN_VALUE;
while (cursor.moveToNext()) {
final long id = cursor.getLong(ImagesBucketQuery.BUCKET_ID);
if (lastId != id) {
includeImagesBucket(result, cursor);
lastId = id;
}
}
} else if (TYPE_IMAGES_BUCKET.equals(ident.type)) {
// include images under bucket
cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
ImageQuery.PROJECTION, ImageColumns.BUCKET_ID + "=?",
queryArgs, null);
copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeImage(result, cursor);
}
} else if (TYPE_VIDEOS_ROOT.equals(ident.type)) {
// include all unique buckets
cursor = resolver.query(Video.Media.EXTERNAL_CONTENT_URI,
VideosBucketQuery.PROJECTION, null, null, VideosBucketQuery.SORT_ORDER);
copyNotificationUri(result, cursor);
long lastId = Long.MIN_VALUE;
while (cursor.moveToNext()) {
final long id = cursor.getLong(VideosBucketQuery.BUCKET_ID);
if (lastId != id) {
includeVideosBucket(result, cursor);
lastId = id;
}
}
} else if (TYPE_VIDEOS_BUCKET.equals(ident.type)) {
// include videos under bucket
cursor = resolver.query(Video.Media.EXTERNAL_CONTENT_URI,
VideoQuery.PROJECTION, VideoColumns.BUCKET_ID + "=?",
queryArgs, null);
copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeVideo(result, cursor);
}
} else if (TYPE_AUDIO_ROOT.equals(ident.type)) {
// include all artists
cursor = resolver.query(Audio.Artists.EXTERNAL_CONTENT_URI,
ArtistQuery.PROJECTION, null, null, null);
copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeArtist(result, cursor);
}
} else if (TYPE_ARTIST.equals(ident.type)) {
// include all albums under artist
cursor = resolver.query(Artists.Albums.getContentUri("external", ident.id),
AlbumQuery.PROJECTION, null, null, null);
copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeAlbum(result, cursor);
}
} else if (TYPE_ALBUM.equals(ident.type)) {
// include all songs under album
cursor = resolver.query(Audio.Media.EXTERNAL_CONTENT_URI,
SongQuery.PROJECTION, AudioColumns.ALBUM_ID + "=?",
queryArgs, null);
copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeAudio(result, cursor);
}
} else {
throw new UnsupportedOperationException("Unsupported document " + docId);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
@Override
public Cursor queryRecentDocuments(
String rootId, String[] projection, @Nullable Bundle queryArgs,
@Nullable CancellationSignal signal)
throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
final long token = Binder.clearCallingIdentity();
int limit = -1;
if (queryArgs != null) {
limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, -1);
}
if (limit < 0) {
// Use default value, and no QUERY_ARG* is honored.
limit = 64;
} else {
// We are honoring the QUERY_ARG_LIMIT.
Bundle extras = new Bundle();
result.setExtras(extras);
extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[]{
ContentResolver.QUERY_ARG_LIMIT
});
}
Cursor cursor = null;
try {
if (TYPE_IMAGES_ROOT.equals(rootId)) {
// include all unique buckets
cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
ImageQuery.PROJECTION, null, null, ImageColumns.DATE_MODIFIED + " DESC");
copyNotificationUri(result, cursor);
while (cursor.moveToNext() && result.getCount() < limit) {
includeImage(result, cursor);
}
} else if (TYPE_VIDEOS_ROOT.equals(rootId)) {
// include all unique buckets
cursor = resolver.query(Video.Media.EXTERNAL_CONTENT_URI,
VideoQuery.PROJECTION, null, null, VideoColumns.DATE_MODIFIED + " DESC");
copyNotificationUri(result, cursor);
while (cursor.moveToNext() && result.getCount() < limit) {
includeVideo(result, cursor);
}
} else {
throw new UnsupportedOperationException("Unsupported root " + rootId);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
@Override
public Cursor querySearchDocuments(String rootId, String[] projection, Bundle queryArgs)
throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
final long token = Binder.clearCallingIdentity();
final String displayName = queryArgs.getString(DocumentsContract.QUERY_ARG_DISPLAY_NAME,
"" /* defaultValue */);
final long lastModifiedAfter = queryArgs.getLong(
DocumentsContract.QUERY_ARG_LAST_MODIFIED_AFTER, -1 /* defaultValue */);
final long fileSizeOver = queryArgs.getLong(DocumentsContract.QUERY_ARG_FILE_SIZE_OVER,
-1 /* defaultValue */);
final String[] mimeTypes = queryArgs.getStringArray(DocumentsContract.QUERY_ARG_MIME_TYPES);
final ArrayList<String> matchedMimeTypes = new ArrayList<>();
Cursor cursor = null;
try {
if (TYPE_IMAGES_ROOT.equals(rootId)) {
final boolean shouldFilterMimeType = shouldFilterMimeType(mimeTypes, "image/*",
matchedMimeTypes);
// If the queried mime types didn't match the root, we don't need to
// query the provider. Ex: the queried mime type is "video/*", but the root
// is images root.
if (mimeTypes == null || !shouldFilterMimeType || matchedMimeTypes.size() > 0) {
final Pair<String, String[]> selectionPair = buildSearchSelection(displayName,
matchedMimeTypes.toArray(new String[0]), lastModifiedAfter,
fileSizeOver, ImageColumns.DISPLAY_NAME, ImageColumns.MIME_TYPE,
ImageColumns.DATE_MODIFIED, ImageColumns.SIZE);
cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
ImageQuery.PROJECTION,
selectionPair.first, selectionPair.second,
ImageColumns.DATE_MODIFIED + " DESC");
copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeImage(result, cursor);
}
}
} else if (TYPE_VIDEOS_ROOT.equals(rootId)) {
final boolean shouldFilterMimeType = shouldFilterMimeType(mimeTypes, "video/*",
matchedMimeTypes);
// If the queried mime types didn't match the root, we don't need to
// query the provider.
if (mimeTypes == null || !shouldFilterMimeType || matchedMimeTypes.size() > 0) {
final Pair<String, String[]> selectionPair = buildSearchSelection(displayName,
matchedMimeTypes.toArray(new String[0]), lastModifiedAfter,
fileSizeOver, VideoColumns.DISPLAY_NAME, VideoColumns.MIME_TYPE,
VideoColumns.DATE_MODIFIED, VideoColumns.SIZE);
cursor = resolver.query(Video.Media.EXTERNAL_CONTENT_URI, VideoQuery.PROJECTION,
selectionPair.first, selectionPair.second,
VideoColumns.DATE_MODIFIED + " DESC");
copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeVideo(result, cursor);
}
}
} else if (TYPE_AUDIO_ROOT.equals(rootId)) {
final boolean shouldFilterMimeType = shouldFilterMimeType(mimeTypes, "audio/*",
matchedMimeTypes);
// If the queried mime types didn't match the root, we don't need to
// query the provider.
if (mimeTypes == null || !shouldFilterMimeType || matchedMimeTypes.size() > 0) {
final Pair<String, String[]> selectionPair = buildSearchSelection(displayName,
matchedMimeTypes.toArray(new String[0]), lastModifiedAfter,
fileSizeOver, AudioColumns.TITLE, AudioColumns.MIME_TYPE,
AudioColumns.DATE_MODIFIED, AudioColumns.SIZE);
cursor = resolver.query(Audio.Media.EXTERNAL_CONTENT_URI, SongQuery.PROJECTION,
selectionPair.first, selectionPair.second,
AudioColumns.DATE_MODIFIED + " DESC");
copyNotificationUri(result, cursor);
while (cursor.moveToNext()) {
includeAudio(result, cursor);
}
}
} else {
throw new UnsupportedOperationException("Unsupported root " + rootId);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
final String[] handledQueryArgs = DocumentsContract.getHandledQueryArguments(queryArgs);
if (handledQueryArgs.length > 0) {
final Bundle extras = new Bundle();
extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, handledQueryArgs);
result.setExtras(extras);
}
return result;
}
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
throws FileNotFoundException {
final Uri target = getUriForDocumentId(docId);
if (!"r".equals(mode)) {
throw new IllegalArgumentException("Media is read-only");
}
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
return getContext().getContentResolver().openFileDescriptor(target, mode);
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public AssetFileDescriptor openDocumentThumbnail(
String docId, Point sizeHint, CancellationSignal signal) throws FileNotFoundException {
final Ident ident = getIdentForDocId(docId);
final long token = Binder.clearCallingIdentity();
try {
if (TYPE_IMAGES_BUCKET.equals(ident.type)) {
final long id = getImageForBucketCleared(ident.id);
return openOrCreateImageThumbnailCleared(id, sizeHint, signal);
} else if (TYPE_IMAGE.equals(ident.type)) {
return openOrCreateImageThumbnailCleared(ident.id, sizeHint, signal);
} else if (TYPE_VIDEOS_BUCKET.equals(ident.type)) {
final long id = getVideoForBucketCleared(ident.id);
return openOrCreateVideoThumbnailCleared(id, sizeHint, signal);
} else if (TYPE_VIDEO.equals(ident.type)) {
return openOrCreateVideoThumbnailCleared(ident.id, sizeHint, signal);
} else {
throw new UnsupportedOperationException("Unsupported document " + docId);
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
private boolean isEmpty(Uri uri) {
final ContentResolver resolver = getContext().getContentResolver();
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
cursor = resolver.query(uri, new String[] {
BaseColumns._ID }, null, null, null);
return (cursor == null) || (cursor.getCount() == 0);
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
}
private void includeImagesRoot(MatrixCursor result) {
int flags = Root.FLAG_LOCAL_ONLY | Root.FLAG_SUPPORTS_RECENTS | Root.FLAG_SUPPORTS_SEARCH;
if (isEmpty(Images.Media.EXTERNAL_CONTENT_URI)) {
flags |= Root.FLAG_EMPTY;
sReturnedImagesEmpty = true;
}
final RowBuilder row = result.newRow();
row.add(Root.COLUMN_ROOT_ID, TYPE_IMAGES_ROOT);
row.add(Root.COLUMN_FLAGS, flags);
row.add(Root.COLUMN_TITLE, getContext().getString(R.string.root_images));
row.add(Root.COLUMN_DOCUMENT_ID, TYPE_IMAGES_ROOT);
row.add(Root.COLUMN_MIME_TYPES, IMAGE_MIME_TYPES);
row.add(Root.COLUMN_QUERY_ARGS, SUPPORTED_QUERY_ARGS);
}
private void includeVideosRoot(MatrixCursor result) {
int flags = Root.FLAG_LOCAL_ONLY | Root.FLAG_SUPPORTS_RECENTS | Root.FLAG_SUPPORTS_SEARCH;
if (isEmpty(Video.Media.EXTERNAL_CONTENT_URI)) {
flags |= Root.FLAG_EMPTY;
sReturnedVideosEmpty = true;
}
final RowBuilder row = result.newRow();
row.add(Root.COLUMN_ROOT_ID, TYPE_VIDEOS_ROOT);
row.add(Root.COLUMN_FLAGS, flags);
row.add(Root.COLUMN_TITLE, getContext().getString(R.string.root_videos));
row.add(Root.COLUMN_DOCUMENT_ID, TYPE_VIDEOS_ROOT);
row.add(Root.COLUMN_MIME_TYPES, VIDEO_MIME_TYPES);
row.add(Root.COLUMN_QUERY_ARGS, SUPPORTED_QUERY_ARGS);
}
private void includeAudioRoot(MatrixCursor result) {
int flags = Root.FLAG_LOCAL_ONLY | Root.FLAG_SUPPORTS_SEARCH;
if (isEmpty(Audio.Media.EXTERNAL_CONTENT_URI)) {
flags |= Root.FLAG_EMPTY;
sReturnedAudioEmpty = true;
}
final RowBuilder row = result.newRow();
row.add(Root.COLUMN_ROOT_ID, TYPE_AUDIO_ROOT);
row.add(Root.COLUMN_FLAGS, flags);
row.add(Root.COLUMN_TITLE, getContext().getString(R.string.root_audio));
row.add(Root.COLUMN_DOCUMENT_ID, TYPE_AUDIO_ROOT);
row.add(Root.COLUMN_MIME_TYPES, AUDIO_MIME_TYPES);
row.add(Root.COLUMN_QUERY_ARGS, SUPPORTED_QUERY_ARGS);
}
private void includeImagesRootDocument(MatrixCursor result) {
final RowBuilder row = result.newRow();
row.add(Document.COLUMN_DOCUMENT_ID, TYPE_IMAGES_ROOT);
row.add(Document.COLUMN_DISPLAY_NAME, getContext().getString(R.string.root_images));
row.add(Document.COLUMN_FLAGS,
Document.FLAG_DIR_PREFERS_GRID | Document.FLAG_DIR_PREFERS_LAST_MODIFIED);
row.add(Document.COLUMN_MIME_TYPE, Document.MIME_TYPE_DIR);