Debian Codegraph @

core/java/com/android/internal/content/FileSystemProvider.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2017 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
17 package com.android.internal.content;
18
19 import android.annotation.CallSuper;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.content.ContentResolver;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.res.AssetFileDescriptor;
26 import android.database.Cursor;
27 import android.database.MatrixCursor;
28 import android.database.MatrixCursor.RowBuilder;
29 import android.graphics.Point;
30 import android.net.Uri;
31 import android.os.Binder;
32 import android.os.Bundle;
33 import android.os.CancellationSignal;
34 import android.os.FileObserver;
35 import android.os.FileUtils;
36 import android.os.Handler;
37 import android.os.ParcelFileDescriptor;
38 import android.provider.DocumentsContract;
39 import android.provider.DocumentsContract.Document;
40 import android.provider.DocumentsProvider;
41 import android.provider.MediaStore;
42 import android.provider.MetadataReader;
43 import android.system.Int64Ref;
44 import android.text.TextUtils;
45 import android.util.ArrayMap;
46 import android.util.Log;
47 import android.webkit.MimeTypeMap;
48
49 import com.android.internal.annotations.GuardedBy;
50 import com.android.internal.util.ArrayUtils;
51
52 import libcore.io.IoUtils;
53
54 import java.io.File;
55 import java.io.FileInputStream;
56 import java.io.FileNotFoundException;
57 import java.io.IOException;
58 import java.io.InputStream;
59 import java.nio.file.FileSystems;
60 import java.nio.file.FileVisitResult;
61 import java.nio.file.FileVisitor;
62 import java.nio.file.Files;
63 import java.nio.file.Path;
64 import java.nio.file.attribute.BasicFileAttributes;
65 import java.util.Arrays;
66 import java.util.LinkedList;
67 import java.util.List;
68 import java.util.Locale;
69 import java.util.Set;
70 import java.util.concurrent.CopyOnWriteArrayList;
71 import java.util.function.Predicate;
72 import java.util.regex.Pattern;
73
74 /**
75 * A helper class for {@link android.provider.DocumentsProvider} to perform file operations on local
76 * files.
77 */
78 public abstract class FileSystemProvider extends DocumentsProvider {
79
80 private static final String TAG = "FileSystemProvider";
81
82 private static final boolean LOG_INOTIFY = false;
83
84 protected static final String SUPPORTED_QUERY_ARGS = joinNewline(
85 DocumentsContract.QUERY_ARG_DISPLAY_NAME,
86 DocumentsContract.QUERY_ARG_FILE_SIZE_OVER,
87 DocumentsContract.QUERY_ARG_LAST_MODIFIED_AFTER,
88 DocumentsContract.QUERY_ARG_MIME_TYPES);
89
90 private static String joinNewline(String... args) {
91 return TextUtils.join("\n", args);
92 }
93
94 private String[] mDefaultProjection;
95
96 @GuardedBy("mObservers")
97 private final ArrayMap<File, DirectoryObserver> mObservers = new ArrayMap<>();
98
99 private Handler mHandler;
100
101 protected abstract File getFileForDocId(String docId, boolean visible)
102 throws FileNotFoundException;
103
104 protected abstract String getDocIdForFile(File file) throws FileNotFoundException;
105
106 protected abstract Uri buildNotificationUri(String docId);
107
108 /**
109 * Callback indicating that the given document has been modified. This gives
110 * the provider a hook to invalidate cached data, such as {@code sdcardfs}.
111 */
112 protected void onDocIdChanged(String docId) {
113 // Default is no-op
114 }
115
116 /**
117 * Callback indicating that the given document has been deleted or moved. This gives
118 * the provider a hook to revoke the uri permissions.
119 */
120 protected void onDocIdDeleted(String docId) {
121 // Default is no-op
122 }
123
124 @Override
125 public boolean onCreate() {
126 throw new UnsupportedOperationException(
127 "Subclass should override this and call onCreate(defaultDocumentProjection)");
128 }
129
130 @CallSuper
131 protected void onCreate(String[] defaultProjection) {
132 mHandler = new Handler();
133 mDefaultProjection = defaultProjection;
134 }
135
136 @Override
137 public boolean isChildDocument(String parentDocId, String docId) {
138 try {
139 final File parent = getFileForDocId(parentDocId).getCanonicalFile();
140 final File doc = getFileForDocId(docId).getCanonicalFile();
141 return FileUtils.contains(parent, doc);
142 } catch (IOException e) {
143 throw new IllegalArgumentException(
144 "Failed to determine if " + docId + " is child of " + parentDocId + ": " + e);
145 }
146 }
147
148 @Override
149 public @Nullable Bundle getDocumentMetadata(String documentId)
150 throws FileNotFoundException {
151 File file = getFileForDocId(documentId);
152
153 if (!file.exists()) {
154 throw new FileNotFoundException("Can't find the file for documentId: " + documentId);
155 }
156
157 final String mimeType = getDocumentType(documentId);
158 if (Document.MIME_TYPE_DIR.equals(mimeType)) {
159 final Int64Ref treeCount = new Int64Ref(0);
160 final Int64Ref treeSize = new Int64Ref(0);
161 try {
162 final Path path = FileSystems.getDefault().getPath(file.getAbsolutePath());
163 Files.walkFileTree(path, new FileVisitor<Path>() {
164 @Override
165 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
166 return FileVisitResult.CONTINUE;
167 }
168
169 @Override
170 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
171 treeCount.value += 1;
172 treeSize.value += attrs.size();
173 return FileVisitResult.CONTINUE;
174 }
175
176 @Override
177 public FileVisitResult visitFileFailed(Path file, IOException exc) {
178 return FileVisitResult.CONTINUE;
179 }
180
181 @Override
182 public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
183 return FileVisitResult.CONTINUE;
184 }
185 });
186 } catch (IOException e) {
187 Log.e(TAG, "An error occurred retrieving the metadata", e);
188 return null;
189 }
190
191 final Bundle res = new Bundle();
192 res.putLong(DocumentsContract.METADATA_TREE_COUNT, treeCount.value);
193 res.putLong(DocumentsContract.METADATA_TREE_SIZE, treeSize.value);
194 return res;
195 }
196
197 if (!file.isFile()) {
198 Log.w(TAG, "Can't stream non-regular file. Returning empty metadata.");
199 return null;
200 }
201 if (!file.canRead()) {
202 Log.w(TAG, "Can't stream non-readable file. Returning empty metadata.");
203 return null;
204 }
205 if (!MetadataReader.isSupportedMimeType(mimeType)) {
206 Log.w(TAG, "Unsupported type " + mimeType + ". Returning empty metadata.");
207 return null;
208 }
209
210 InputStream stream = null;
211 try {
212 Bundle metadata = new Bundle();
213 stream = new FileInputStream(file.getAbsolutePath());
214 MetadataReader.getMetadata(metadata, stream, mimeType, null);
215 return metadata;
216 } catch (IOException e) {
217 Log.e(TAG, "An error occurred retrieving the metadata", e);
218 return null;
219 } finally {
220 IoUtils.closeQuietly(stream);
221 }
222 }
223
224 protected final List<String> findDocumentPath(File parent, File doc)
225 throws FileNotFoundException {
226
227 if (!doc.exists()) {
228 throw new FileNotFoundException(doc + " is not found.");
229 }
230
231 if (!FileUtils.contains(parent, doc)) {
232 throw new FileNotFoundException(doc + " is not found under " + parent);
233 }
234
235 LinkedList<String> path = new LinkedList<>();
236 while (doc != null && FileUtils.contains(parent, doc)) {
237 path.addFirst(getDocIdForFile(doc));
238
239 doc = doc.getParentFile();
240 }
241
242 return path;
243 }
244
245 @Override
246 public String createDocument(String docId, String mimeType, String displayName)
247 throws FileNotFoundException {
248 displayName = FileUtils.buildValidFatFilename(displayName);
249
250 final File parent = getFileForDocId(docId);
251 if (!parent.isDirectory()) {
252 throw new IllegalArgumentException("Parent document isn't a directory");
253 }
254
255 final File file = FileUtils.buildUniqueFile(parent, mimeType, displayName);
256 final String childId;
257 if (Document.MIME_TYPE_DIR.equals(mimeType)) {
258 if (!file.mkdir()) {
259 throw new IllegalStateException("Failed to mkdir " + file);
260 }
261 childId = getDocIdForFile(file);
262 onDocIdChanged(childId);
263 } else {
264 try {
265 if (!file.createNewFile()) {
266 throw new IllegalStateException("Failed to touch " + file);
267 }
268 childId = getDocIdForFile(file);
269 onDocIdChanged(childId);
270 } catch (IOException e) {
271 throw new IllegalStateException("Failed to touch " + file + ": " + e);
272 }
273 }
274 updateMediaStore(getContext(), file);
275 return childId;
276 }
277
278 @Override
279 public String renameDocument(String docId, String displayName) throws FileNotFoundException {
280 // Since this provider treats renames as generating a completely new
281 // docId, we're okay with letting the MIME type change.
282 displayName = FileUtils.buildValidFatFilename(displayName);
283
284 final File before = getFileForDocId(docId);
285 final File beforeVisibleFile = getFileForDocId(docId, true);
286 final File after = FileUtils.buildUniqueFile(before.getParentFile(), displayName);
287 if (!before.renameTo(after)) {
288 throw new IllegalStateException("Failed to rename to " + after);
289 }
290
291 final String afterDocId = getDocIdForFile(after);
292 onDocIdChanged(docId);
293 onDocIdDeleted(docId);
294 onDocIdChanged(afterDocId);
295
296 final File afterVisibleFile = getFileForDocId(afterDocId, true);
297
298 updateMediaStore(getContext(), beforeVisibleFile);
299 updateMediaStore(getContext(), afterVisibleFile);
300
301 if (!TextUtils.equals(docId, afterDocId)) {
302 return afterDocId;
303 } else {
304 return null;
305 }
306 }
307
308 @Override
309 public String moveDocument(String sourceDocumentId, String sourceParentDocumentId,
310 String targetParentDocumentId)
311 throws FileNotFoundException {
312 final File before = getFileForDocId(sourceDocumentId);
313 final File after = new File(getFileForDocId(targetParentDocumentId), before.getName());
314 final File visibleFileBefore = getFileForDocId(sourceDocumentId, true);
315
316 if (after.exists()) {
317 throw new IllegalStateException("Already exists " + after);
318 }
319 if (!before.renameTo(after)) {
320 throw new IllegalStateException("Failed to move to " + after);
321 }
322
323 final String docId = getDocIdForFile(after);
324 onDocIdChanged(sourceDocumentId);
325 onDocIdDeleted(sourceDocumentId);
326 onDocIdChanged(docId);
327 // update the database
328 updateMediaStore(getContext(), visibleFileBefore);
329 updateMediaStore(getContext(), getFileForDocId(docId, true));
330 return docId;
331 }
332
333 private static void updateMediaStore(@NonNull Context context, File file) {
334 if (file != null) {
335 final ContentResolver resolver = context.getContentResolver();
336 final String noMedia = ".nomedia";
337 // For file, check whether the file name is .nomedia or not.
338 // If yes, scan the parent directory to update all files in the directory.
339 if (!file.isDirectory() && file.getName().toLowerCase(Locale.ROOT).endsWith(noMedia)) {
340 MediaStore.scanFile(resolver, file.getParentFile());
341 } else {
342 MediaStore.scanFile(resolver, file);
343 }
344 }
345 }
346
347 @Override
348 public void deleteDocument(String docId) throws FileNotFoundException {
349 final File file = getFileForDocId(docId);
350 final File visibleFile = getFileForDocId(docId, true);
351
352 final boolean isDirectory = file.isDirectory();
353 if (isDirectory) {
354 FileUtils.deleteContents(file);
355 }
356 // We could be deleting pending media which doesn't have any content yet, so only throw
357 // if the file exists and we fail to delete it.
358 if (file.exists() && !file.delete()) {
359 throw new IllegalStateException("Failed to delete " + file);
360 }
361
362 onDocIdChanged(docId);
363 onDocIdDeleted(docId);
364 updateMediaStore(getContext(), visibleFile);
365 }
366
367 @Override
368 public Cursor queryDocument(String documentId, String[] projection)
369 throws FileNotFoundException {
370 final MatrixCursor result = new MatrixCursor(resolveProjection(projection));
371 includeFile(result, documentId, null);
372 return result;
373 }
374
375 /**
376 * This method is similar to
377 * {@link DocumentsProvider#queryChildDocuments(String, String[], String)}. This method returns
378 * all children documents including hidden directories/files.
379 *
380 * <p>
381 * In a scoped storage world, access to "Android/data" style directories are hidden for privacy
382 * reasons. This method may show privacy sensitive data, so its usage should only be in
383 * restricted modes.
384 *
385 * @param parentDocumentId the directory to return children for.
386 * @param projection list of {@link Document} columns to put into the
387 * cursor. If {@code null} all supported columns should be
388 * included.
389 * @param sortOrder how to order the rows, formatted as an SQL
390 * {@code ORDER BY} clause (excluding the ORDER BY itself).
391 * Passing {@code null} will use the default sort order, which
392 * may be unordered. This ordering is a hint that can be used to
393 * prioritize how data is fetched from the network, but UI may
394 * always enforce a specific ordering
395 * @throws FileNotFoundException when parent document doesn't exist or query fails
396 */
397 protected Cursor queryChildDocumentsShowAll(
398 String parentDocumentId, String[] projection, String sortOrder)
399 throws FileNotFoundException {
400 return queryChildDocuments(parentDocumentId, projection, sortOrder, File -> true);
401 }
402
403 @Override
404 public Cursor queryChildDocuments(
405 String parentDocumentId, String[] projection, String sortOrder)
406 throws FileNotFoundException {
407 // Access to some directories is hidden for privacy reasons.
408 return queryChildDocuments(parentDocumentId, projection, sortOrder, this::shouldShow);
409 }
410
411 private Cursor queryChildDocuments(
412 String parentDocumentId, String[] projection, String sortOrder,
413 @NonNull Predicate<File> filter) throws FileNotFoundException {
414 final File parent = getFileForDocId(parentDocumentId);
415 final MatrixCursor result = new DirectoryCursor(
416 resolveProjection(projection), parentDocumentId, parent);
417
418 if (!filter.test(parent)) {
419 Log.w(TAG, "No permission to access parentDocumentId: " + parentDocumentId);
420 return result;
421 }
422
423 if (parent.isDirectory()) {
424 for (File file : FileUtils.listFilesOrEmpty(parent)) {
425 if (filter.test(file)) {
426 includeFile(result, null, file);
427 }
428 }
429 } else {
430 Log.w(TAG, "parentDocumentId '" + parentDocumentId + "' is not Directory");
431 }
432 return result;
433 }
434
435 /**
436 * Searches documents under the given folder.
437 *
438 * To avoid runtime explosion only returns the at most 23 items.
439 *
440 * @param folder the root folder where recursive search begins
441 * @param query the search condition used to match file names
442 * @param projection projection of the returned cursor
443 * @param exclusion absolute file paths to exclude from result
444 * @param queryArgs the query arguments for search
445 * @return cursor containing search result. Include
446 * {@link ContentResolver#EXTRA_HONORED_ARGS} in {@link Cursor}
447 * extras {@link Bundle} when any QUERY_ARG_* value was honored
448 * during the preparation of the results.
449 * @throws FileNotFoundException when root folder doesn't exist or search fails
450 *
451 * @see ContentResolver#EXTRA_HONORED_ARGS
452 */
453 protected final Cursor querySearchDocuments(
454 File folder, String[] projection, Set<String> exclusion, Bundle queryArgs)
455 throws FileNotFoundException {
456 final MatrixCursor result = new MatrixCursor(resolveProjection(projection));
457 final LinkedList<File> pending = new LinkedList<>();
458 pending.add(folder);
459 while (!pending.isEmpty() && result.getCount() < 24) {
460 final File file = pending.removeFirst();
461 if (shouldHide(file)) continue;
462
463 if (file.isDirectory()) {
464 for (File child : FileUtils.listFilesOrEmpty(file)) {
465 pending.add(child);
466 }
467 }
468 if (!exclusion.contains(file.getAbsolutePath()) && matchSearchQueryArguments(file,
469 queryArgs)) {
470 includeFile(result, null, file);
471 }
472 }
473
474 final String[] handledQueryArgs = DocumentsContract.getHandledQueryArguments(queryArgs);
475 if (handledQueryArgs.length > 0) {
476 final Bundle extras = new Bundle();
477 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, handledQueryArgs);
478 result.setExtras(extras);
479 }
480 return result;
481 }
482
483 @Override
484 public String getDocumentType(String documentId) throws FileNotFoundException {
485 return getDocumentType(documentId, getFileForDocId(documentId));
486 }
487
488 private String getDocumentType(final String documentId, final File file)
489 throws FileNotFoundException {
490 if (file.isDirectory()) {
491 return Document.MIME_TYPE_DIR;
492 } else {
493 final int lastDot = documentId.lastIndexOf('.');
494 if (lastDot >= 0) {
495 final String extension = documentId.substring(lastDot + 1).toLowerCase();
496 final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
497 if (mime != null) {
498 return mime;
499 }
500 }
501 return ContentResolver.MIME_TYPE_DEFAULT;
502 }
503 }
504
505 @Override
506 public ParcelFileDescriptor openDocument(
507 String documentId, String mode, CancellationSignal signal)
508 throws FileNotFoundException {
509 final File file = getFileForDocId(documentId);
510 final File visibleFile = getFileForDocId(documentId, true);
511
512 final int pfdMode = ParcelFileDescriptor.parseMode(mode);
513 if (visibleFile == null) {
514 return ParcelFileDescriptor.open(file, pfdMode);
515 } else if (pfdMode == ParcelFileDescriptor.MODE_READ_ONLY) {
516 return openFileForRead(visibleFile);
517 } else {
518 try {
519 // When finished writing, kick off media scanner
520 return ParcelFileDescriptor.open(
521 file, pfdMode, mHandler, (IOException e) -> {
522 onDocIdChanged(documentId);
523 scanFile(visibleFile);
524 });
525 } catch (IOException e) {
526 throw new FileNotFoundException("Failed to open for writing: " + e);
527 }
528 }
529 }
530
531 private ParcelFileDescriptor openFileForRead(final File target) throws FileNotFoundException {
532 final Uri uri = MediaStore.scanFile(getContext().getContentResolver(), target);
533 if (uri == null) {
534 Log.w(TAG, "Failed to retrieve media store URI for: " + target);
535 return ParcelFileDescriptor.open(target, ParcelFileDescriptor.MODE_READ_ONLY);
536 }
537
538 // Passing the calling uid via EXTRA_MEDIA_CAPABILITIES_UID, so that the decision to
539 // transcode or not transcode can be made based upon the calling app's uid, and not based
540 // upon the Provider's uid.
541 final Bundle opts = new Bundle();
542 opts.putInt(MediaStore.EXTRA_MEDIA_CAPABILITIES_UID, Binder.getCallingUid());
543
544 final AssetFileDescriptor afd =
545 getContext().getContentResolver().openTypedAssetFileDescriptor(uri, "*/*", opts);
546 if (afd == null) {
547 Log.w(TAG, "Failed to open with media_capabilities uid for URI: " + uri);
548 return ParcelFileDescriptor.open(target, ParcelFileDescriptor.MODE_READ_ONLY);
549 }
550
551 return afd.getParcelFileDescriptor();
552 }
553
554 /**
555 * Test if the file matches the query arguments.
556 *
557 * @param file the file to test
558 * @param queryArgs the query arguments
559 */
560 private boolean matchSearchQueryArguments(File file, Bundle queryArgs) {
561 if (file == null) {
562 return false;
563 }
564
565 final String fileMimeType;
566 final String fileName = file.getName();
567
568 if (file.isDirectory()) {
569 fileMimeType = DocumentsContract.Document.MIME_TYPE_DIR;
570 } else {
571 int dotPos = fileName.lastIndexOf('.');
572 if (dotPos < 0) {
573 return false;
574 }
575 final String extension = fileName.substring(dotPos + 1);
576 fileMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
577 }
578 return DocumentsContract.matchSearchQueryArguments(queryArgs, fileName, fileMimeType,
579 file.lastModified(), file.length());
580 }
581
582 private void scanFile(File visibleFile) {
583 final Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
584 intent.setData(Uri.fromFile(visibleFile));
585 getContext().sendBroadcast(intent);
586 }
587
588 @Override
589 public AssetFileDescriptor openDocumentThumbnail(
590 String documentId, Point sizeHint, CancellationSignal signal)
591 throws FileNotFoundException {
592 final File file = getFileForDocId(documentId);
593 return DocumentsContract.openImageThumbnail(file);
594 }
595
596 protected RowBuilder includeFile(final MatrixCursor result, String docId, File file)
597 throws FileNotFoundException {
598 final String[] columns = result.getColumnNames();
599 final RowBuilder row = result.newRow();
600
601 if (docId == null) {
602 docId = getDocIdForFile(file);
603 } else {
604 file = getFileForDocId(docId);
605 }
606
607 final String mimeType = getDocumentType(docId, file);
608 row.add(Document.COLUMN_DOCUMENT_ID, docId);
609 row.add(Document.COLUMN_MIME_TYPE, mimeType);
610
611 final int flagIndex = ArrayUtils.indexOf(columns, Document.COLUMN_FLAGS);
612 if (flagIndex != -1) {
613 int flags = 0;
614 if (file.canWrite()) {
615 if (mimeType.equals(Document.MIME_TYPE_DIR)) {
616 flags |= Document.FLAG_DIR_SUPPORTS_CREATE;
617 flags |= Document.FLAG_SUPPORTS_DELETE;
618 flags |= Document.FLAG_SUPPORTS_RENAME;
619 flags |= Document.FLAG_SUPPORTS_MOVE;
620
621 if (shouldBlockFromTree(docId)) {
622 flags |= Document.FLAG_DIR_BLOCKS_OPEN_DOCUMENT_TREE;
623 }
624
625 } else {
626 flags |= Document.FLAG_SUPPORTS_WRITE;
627 flags |= Document.FLAG_SUPPORTS_DELETE;
628 flags |= Document.FLAG_SUPPORTS_RENAME;
629 flags |= Document.FLAG_SUPPORTS_MOVE;
630 }
631 }
632
633 if (mimeType.startsWith("image/")) {
634 flags |= Document.FLAG_SUPPORTS_THUMBNAIL;
635 }
636
637 if (typeSupportsMetadata(mimeType)) {
638 flags |= Document.FLAG_SUPPORTS_METADATA;
639 }
640 row.add(flagIndex, flags);
641 }
642
643 final int displayNameIndex = ArrayUtils.indexOf(columns, Document.COLUMN_DISPLAY_NAME);
644 if (displayNameIndex != -1) {
645 row.add(displayNameIndex, file.getName());
646 }
647
648 final int lastModifiedIndex = ArrayUtils.indexOf(columns, Document.COLUMN_LAST_MODIFIED);
649 if (lastModifiedIndex != -1) {
650 final long lastModified = file.lastModified();
651 // Only publish dates reasonably after epoch
652 if (lastModified > 31536000000L) {
653 row.add(lastModifiedIndex, lastModified);
654 }
655 }
656 final int sizeIndex = ArrayUtils.indexOf(columns, Document.COLUMN_SIZE);
657 if (sizeIndex != -1) {
658 row.add(sizeIndex, file.length());
659 }
660
661 // Return the row builder just in case any subclass want to add more stuff to it.
662 return row;
663 }
664
665 private static final Pattern PATTERN_HIDDEN_PATH = Pattern.compile(
666 "(?i)^/storage/[^/]+/(?:[0-9]+/)?Android/(?:data|obb|sandbox)$");
667
668 /**
669 * In a scoped storage world, access to "Android/data" style directories are
670 * hidden for privacy reasons.
671 */
672 protected boolean shouldHide(@NonNull File file) {
673 return (PATTERN_HIDDEN_PATH.matcher(file.getAbsolutePath()).matches());
674 }
675
676 private boolean shouldShow(@NonNull File file) {
677 return !shouldHide(file);
678 }
679
680 protected boolean shouldBlockFromTree(@NonNull String docId) {
681 return false;
682 }
683
684 protected boolean typeSupportsMetadata(String mimeType) {
685 return MetadataReader.isSupportedMimeType(mimeType)
686 || Document.MIME_TYPE_DIR.equals(mimeType);
687 }
688
689 protected final File getFileForDocId(String docId) throws FileNotFoundException {
690 return getFileForDocId(docId, false);
691 }
692
693 private String[] resolveProjection(String[] projection) {
694 return projection == null ? mDefaultProjection : projection;
695 }
696
697 private void startObserving(File file, Uri notifyUri, DirectoryCursor cursor) {
698 synchronized (mObservers) {
699 DirectoryObserver observer = mObservers.get(file);
700 if (observer == null) {
701 observer =
702 new DirectoryObserver(file, getContext().getContentResolver(), notifyUri);
703 observer.startWatching();
704 mObservers.put(file, observer);
705 }
706 observer.mCursors.add(cursor);
707
708 if (LOG_INOTIFY) Log.d(TAG, "after start: " + observer);
709 }
710 }
711
712 private void stopObserving(File file, DirectoryCursor cursor) {
713 synchronized (mObservers) {
714 DirectoryObserver observer = mObservers.get(file);
715 if (observer == null) return;
716
717 observer.mCursors.remove(cursor);
718 if (observer.mCursors.size() == 0) {
719 mObservers.remove(file);
720 observer.stopWatching();
721 }
722
723 if (LOG_INOTIFY) Log.d(TAG, "after stop: " + observer);
724 }
725 }
726
727 private static class DirectoryObserver extends FileObserver {
728 private static final int NOTIFY_EVENTS = ATTRIB | CLOSE_WRITE | MOVED_FROM | MOVED_TO
729 | CREATE | DELETE | DELETE_SELF | MOVE_SELF;
730
731 private final File mFile;
732 private final ContentResolver mResolver;
733 private final Uri mNotifyUri;
734 private final CopyOnWriteArrayList<DirectoryCursor> mCursors;
735
736 DirectoryObserver(File file, ContentResolver resolver, Uri notifyUri) {
737 super(file.getAbsolutePath(), NOTIFY_EVENTS);
738 mFile = file;
739 mResolver = resolver;
740 mNotifyUri = notifyUri;
741 mCursors = new CopyOnWriteArrayList<>();
742 }
743
744 @Override
745 public void onEvent(int event, String path) {
746 if ((event & NOTIFY_EVENTS) != 0) {
747 if (LOG_INOTIFY) Log.d(TAG, "onEvent() " + event + " at " + path);
748 for (DirectoryCursor cursor : mCursors) {
749 cursor.notifyChanged();
750 }
751 mResolver.notifyChange(mNotifyUri, null, false);
752 }
753 }
754
755 @Override
756 public String toString() {
757 String filePath = mFile.getAbsolutePath();
758 return "DirectoryObserver{file=" + filePath + ", ref=" + mCursors.size() + "}";
759 }
760 }
761
762 private class DirectoryCursor extends MatrixCursor {
763 private final File mFile;
764
765 public DirectoryCursor(String[] columnNames, String docId, File file) {
766 super(columnNames);
767
768 final Uri notifyUri = buildNotificationUri(docId);
769 boolean registerSelfObserver = false; // Our FileObserver sees all relevant changes.
770 setNotificationUris(getContext().getContentResolver(), Arrays.asList(notifyUri),
771 getContext().getContentResolver().getUserId(), registerSelfObserver);
772
773 mFile = file;
774 startObserving(mFile, notifyUri, this);
775 }
776
777 public void notifyChanged() {
778 onChange(false);
779 }
780
781 @Override
782 public void close() {
783 super.close();
784 stopObserving(mFile, this);
785 }
786 }
787 }