DocumentsProvider.java revision d3afdeebeb9dcfbb5f24e4afac988e2e96de26de
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.provider;
18
19import static android.provider.DocumentsContract.METHOD_COPY_DOCUMENT;
20import static android.provider.DocumentsContract.METHOD_CREATE_DOCUMENT;
21import static android.provider.DocumentsContract.METHOD_DELETE_DOCUMENT;
22import static android.provider.DocumentsContract.METHOD_IS_CHILD_DOCUMENT;
23import static android.provider.DocumentsContract.METHOD_MOVE_DOCUMENT;
24import static android.provider.DocumentsContract.METHOD_RENAME_DOCUMENT;
25import static android.provider.DocumentsContract.buildDocumentUri;
26import static android.provider.DocumentsContract.buildDocumentUriMaybeUsingTree;
27import static android.provider.DocumentsContract.buildTreeDocumentUri;
28import static android.provider.DocumentsContract.getDocumentId;
29import static android.provider.DocumentsContract.getRootId;
30import static android.provider.DocumentsContract.getSearchDocumentsQuery;
31import static android.provider.DocumentsContract.getTreeDocumentId;
32import static android.provider.DocumentsContract.isTreeUri;
33
34import android.annotation.CallSuper;
35import android.content.ClipDescription;
36import android.content.ContentProvider;
37import android.content.ContentResolver;
38import android.content.ContentValues;
39import android.content.Context;
40import android.content.Intent;
41import android.content.UriMatcher;
42import android.content.pm.PackageManager;
43import android.content.pm.ProviderInfo;
44import android.content.res.AssetFileDescriptor;
45import android.database.Cursor;
46import android.graphics.Point;
47import android.net.Uri;
48import android.os.Bundle;
49import android.os.CancellationSignal;
50import android.os.ParcelFileDescriptor;
51import android.os.ParcelFileDescriptor.OnCloseListener;
52import android.provider.DocumentsContract.Document;
53import android.provider.DocumentsContract.Root;
54import android.util.Log;
55
56import libcore.io.IoUtils;
57
58import java.io.FileNotFoundException;
59import java.util.Objects;
60
61/**
62 * Base class for a document provider. A document provider offers read and write
63 * access to durable files, such as files stored on a local disk, or files in a
64 * cloud storage service. To create a document provider, extend this class,
65 * implement the abstract methods, and add it to your manifest like this:
66 *
67 * <pre class="prettyprint">&lt;manifest&gt;
68 *    ...
69 *    &lt;application&gt;
70 *        ...
71 *        &lt;provider
72 *            android:name="com.example.MyCloudProvider"
73 *            android:authorities="com.example.mycloudprovider"
74 *            android:exported="true"
75 *            android:grantUriPermissions="true"
76 *            android:permission="android.permission.MANAGE_DOCUMENTS"
77 *            android:enabled="@bool/isAtLeastKitKat"&gt;
78 *            &lt;intent-filter&gt;
79 *                &lt;action android:name="android.content.action.DOCUMENTS_PROVIDER" /&gt;
80 *            &lt;/intent-filter&gt;
81 *        &lt;/provider&gt;
82 *        ...
83 *    &lt;/application&gt;
84 *&lt;/manifest&gt;</pre>
85 * <p>
86 * When defining your provider, you must protect it with
87 * {@link android.Manifest.permission#MANAGE_DOCUMENTS}, which is a permission
88 * only the system can obtain. Applications cannot use a documents provider
89 * directly; they must go through {@link Intent#ACTION_OPEN_DOCUMENT} or
90 * {@link Intent#ACTION_CREATE_DOCUMENT} which requires a user to actively
91 * navigate and select documents. When a user selects documents through that UI,
92 * the system issues narrow URI permission grants to the requesting application.
93 * </p>
94 * <h3>Documents</h3>
95 * <p>
96 * A document can be either an openable stream (with a specific MIME type), or a
97 * directory containing additional documents (with the
98 * {@link Document#MIME_TYPE_DIR} MIME type). Each directory represents the top
99 * of a subtree containing zero or more documents, which can recursively contain
100 * even more documents and directories.
101 * </p>
102 * <p>
103 * Each document can have different capabilities, as described by
104 * {@link Document#COLUMN_FLAGS}. For example, if a document can be represented
105 * as a thumbnail, your provider can set
106 * {@link Document#FLAG_SUPPORTS_THUMBNAIL} and implement
107 * {@link #openDocumentThumbnail(String, Point, CancellationSignal)} to return
108 * that thumbnail.
109 * </p>
110 * <p>
111 * Each document under a provider is uniquely referenced by its
112 * {@link Document#COLUMN_DOCUMENT_ID}, which must not change once returned. A
113 * single document can be included in multiple directories when responding to
114 * {@link #queryChildDocuments(String, String[], String)}. For example, a
115 * provider might surface a single photo in multiple locations: once in a
116 * directory of geographic locations, and again in a directory of dates.
117 * </p>
118 * <h3>Roots</h3>
119 * <p>
120 * All documents are surfaced through one or more "roots." Each root represents
121 * the top of a document tree that a user can navigate. For example, a root
122 * could represent an account or a physical storage device. Similar to
123 * documents, each root can have capabilities expressed through
124 * {@link Root#COLUMN_FLAGS}.
125 * </p>
126 *
127 * @see Intent#ACTION_OPEN_DOCUMENT
128 * @see Intent#ACTION_OPEN_DOCUMENT_TREE
129 * @see Intent#ACTION_CREATE_DOCUMENT
130 */
131public abstract class DocumentsProvider extends ContentProvider {
132    private static final String TAG = "DocumentsProvider";
133
134    private static final int MATCH_ROOTS = 1;
135    private static final int MATCH_ROOT = 2;
136    private static final int MATCH_RECENT = 3;
137    private static final int MATCH_SEARCH = 4;
138    private static final int MATCH_DOCUMENT = 5;
139    private static final int MATCH_CHILDREN = 6;
140    private static final int MATCH_DOCUMENT_TREE = 7;
141    private static final int MATCH_CHILDREN_TREE = 8;
142
143    private String mAuthority;
144
145    private UriMatcher mMatcher;
146
147    /**
148     * Implementation is provided by the parent class.
149     */
150    @Override
151    public void attachInfo(Context context, ProviderInfo info) {
152        mAuthority = info.authority;
153
154        mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
155        mMatcher.addURI(mAuthority, "root", MATCH_ROOTS);
156        mMatcher.addURI(mAuthority, "root/*", MATCH_ROOT);
157        mMatcher.addURI(mAuthority, "root/*/recent", MATCH_RECENT);
158        mMatcher.addURI(mAuthority, "root/*/search", MATCH_SEARCH);
159        mMatcher.addURI(mAuthority, "document/*", MATCH_DOCUMENT);
160        mMatcher.addURI(mAuthority, "document/*/children", MATCH_CHILDREN);
161        mMatcher.addURI(mAuthority, "tree/*/document/*", MATCH_DOCUMENT_TREE);
162        mMatcher.addURI(mAuthority, "tree/*/document/*/children", MATCH_CHILDREN_TREE);
163
164        // Sanity check our setup
165        if (!info.exported) {
166            throw new SecurityException("Provider must be exported");
167        }
168        if (!info.grantUriPermissions) {
169            throw new SecurityException("Provider must grantUriPermissions");
170        }
171        if (!android.Manifest.permission.MANAGE_DOCUMENTS.equals(info.readPermission)
172                || !android.Manifest.permission.MANAGE_DOCUMENTS.equals(info.writePermission)) {
173            throw new SecurityException("Provider must be protected by MANAGE_DOCUMENTS");
174        }
175
176        super.attachInfo(context, info);
177    }
178
179    /**
180     * Test if a document is descendant (child, grandchild, etc) from the given
181     * parent. For example, providers must implement this to support
182     * {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. You should avoid making network
183     * requests to keep this request fast.
184     *
185     * @param parentDocumentId parent to verify against.
186     * @param documentId child to verify.
187     * @return if given document is a descendant of the given parent.
188     * @see DocumentsContract.Root#FLAG_SUPPORTS_IS_CHILD
189     */
190    public boolean isChildDocument(String parentDocumentId, String documentId) {
191        return false;
192    }
193
194    /** {@hide} */
195    private void enforceTree(Uri documentUri) {
196        if (isTreeUri(documentUri)) {
197            final String parent = getTreeDocumentId(documentUri);
198            final String child = getDocumentId(documentUri);
199            if (Objects.equals(parent, child)) {
200                return;
201            }
202            if (!isChildDocument(parent, child)) {
203                throw new SecurityException(
204                        "Document " + child + " is not a descendant of " + parent);
205            }
206        }
207    }
208
209    /**
210     * Create a new document and return its newly generated
211     * {@link Document#COLUMN_DOCUMENT_ID}. You must allocate a new
212     * {@link Document#COLUMN_DOCUMENT_ID} to represent the document, which must
213     * not change once returned.
214     *
215     * @param parentDocumentId the parent directory to create the new document
216     *            under.
217     * @param mimeType the concrete MIME type associated with the new document.
218     *            If the MIME type is not supported, the provider must throw.
219     * @param displayName the display name of the new document. The provider may
220     *            alter this name to meet any internal constraints, such as
221     *            avoiding conflicting names.
222     */
223    @SuppressWarnings("unused")
224    public String createDocument(String parentDocumentId, String mimeType, String displayName)
225            throws FileNotFoundException {
226        throw new UnsupportedOperationException("Create not supported");
227    }
228
229    /**
230     * Rename an existing document.
231     * <p>
232     * If a different {@link Document#COLUMN_DOCUMENT_ID} must be used to
233     * represent the renamed document, generate and return it. Any outstanding
234     * URI permission grants will be updated to point at the new document. If
235     * the original {@link Document#COLUMN_DOCUMENT_ID} is still valid after the
236     * rename, return {@code null}.
237     *
238     * @param documentId the document to rename.
239     * @param displayName the updated display name of the document. The provider
240     *            may alter this name to meet any internal constraints, such as
241     *            avoiding conflicting names.
242     */
243    @SuppressWarnings("unused")
244    public String renameDocument(String documentId, String displayName)
245            throws FileNotFoundException {
246        throw new UnsupportedOperationException("Rename not supported");
247    }
248
249    /**
250     * Delete the requested document.
251     * <p>
252     * Upon returning, any URI permission grants for the given document will be
253     * revoked. If additional documents were deleted as a side effect of this
254     * call (such as documents inside a directory) the implementor is
255     * responsible for revoking those permissions using
256     * {@link #revokeDocumentPermission(String)}.
257     *
258     * @param documentId the document to delete.
259     */
260    @SuppressWarnings("unused")
261    public void deleteDocument(String documentId) throws FileNotFoundException {
262        throw new UnsupportedOperationException("Delete not supported");
263    }
264
265    /**
266     * Copy the requested document or a document tree.
267     * <p>
268     * Copies a document including all child documents to another location within
269     * the same document provider. Upon completion returns the document id of
270     * the copied document at the target destination. {@code null} must never
271     * be returned.
272     *
273     * @param sourceDocumentId the document to copy.
274     * @param targetParentDocumentId the target document to be copied into as a child.
275     * @hide
276     */
277    @SuppressWarnings("unused")
278    public String copyDocument(String sourceDocumentId, String targetParentDocumentId)
279            throws FileNotFoundException {
280        throw new UnsupportedOperationException("Copy not supported");
281    }
282
283    /**
284     * Move the requested document or a document tree.
285     * <p>
286     * Moves a document including all child documents to another location within
287     * the same document provider. Upon completion returns the document id of
288     * the copied document at the target destination. {@code null} must never
289     * be returned.
290     *
291     * @param sourceDocumentId the document to move.
292     * @param targetParentDocumentId the target document to be a new parent of the
293     *     source document.
294     * @hide
295     */
296    @SuppressWarnings("unused")
297    public String moveDocument(String sourceDocumentId, String targetParentDocumentId)
298            throws FileNotFoundException {
299        throw new UnsupportedOperationException("Move not supported");
300    }
301    /**
302     * Return all roots currently provided. To display to users, you must define
303     * at least one root. You should avoid making network requests to keep this
304     * request fast.
305     * <p>
306     * Each root is defined by the metadata columns described in {@link Root},
307     * including {@link Root#COLUMN_DOCUMENT_ID} which points to a directory
308     * representing a tree of documents to display under that root.
309     * <p>
310     * If this set of roots changes, you must call {@link ContentResolver#notifyChange(Uri,
311     * android.database.ContentObserver, boolean)} with
312     * {@link DocumentsContract#buildRootsUri(String)} to notify the system.
313     *
314     * @param projection list of {@link Root} columns to put into the cursor. If
315     *            {@code null} all supported columns should be included.
316     */
317    public abstract Cursor queryRoots(String[] projection) throws FileNotFoundException;
318
319    /**
320     * Return recently modified documents under the requested root. This will
321     * only be called for roots that advertise
322     * {@link Root#FLAG_SUPPORTS_RECENTS}. The returned documents should be
323     * sorted by {@link Document#COLUMN_LAST_MODIFIED} in descending order, and
324     * limited to only return the 64 most recently modified documents.
325     * <p>
326     * Recent documents do not support change notifications.
327     *
328     * @param projection list of {@link Document} columns to put into the
329     *            cursor. If {@code null} all supported columns should be
330     *            included.
331     * @see DocumentsContract#EXTRA_LOADING
332     */
333    @SuppressWarnings("unused")
334    public Cursor queryRecentDocuments(String rootId, String[] projection)
335            throws FileNotFoundException {
336        throw new UnsupportedOperationException("Recent not supported");
337    }
338
339    /**
340     * Return metadata for the single requested document. You should avoid
341     * making network requests to keep this request fast.
342     *
343     * @param documentId the document to return.
344     * @param projection list of {@link Document} columns to put into the
345     *            cursor. If {@code null} all supported columns should be
346     *            included.
347     */
348    public abstract Cursor queryDocument(String documentId, String[] projection)
349            throws FileNotFoundException;
350
351    /**
352     * Return the children documents contained in the requested directory. This
353     * must only return immediate descendants, as additional queries will be
354     * issued to recursively explore the tree.
355     * <p>
356     * If your provider is cloud-based, and you have some data cached or pinned
357     * locally, you may return the local data immediately, setting
358     * {@link DocumentsContract#EXTRA_LOADING} on the Cursor to indicate that
359     * you are still fetching additional data. Then, when the network data is
360     * available, you can send a change notification to trigger a requery and
361     * return the complete contents. To return a Cursor with extras, you need to
362     * extend and override {@link Cursor#getExtras()}.
363     * <p>
364     * To support change notifications, you must
365     * {@link Cursor#setNotificationUri(ContentResolver, Uri)} with a relevant
366     * Uri, such as
367     * {@link DocumentsContract#buildChildDocumentsUri(String, String)}. Then
368     * you can call {@link ContentResolver#notifyChange(Uri,
369     * android.database.ContentObserver, boolean)} with that Uri to send change
370     * notifications.
371     *
372     * @param parentDocumentId the directory to return children for.
373     * @param projection list of {@link Document} columns to put into the
374     *            cursor. If {@code null} all supported columns should be
375     *            included.
376     * @param sortOrder how to order the rows, formatted as an SQL
377     *            {@code ORDER BY} clause (excluding the ORDER BY itself).
378     *            Passing {@code null} will use the default sort order, which
379     *            may be unordered. This ordering is a hint that can be used to
380     *            prioritize how data is fetched from the network, but UI may
381     *            always enforce a specific ordering.
382     * @see DocumentsContract#EXTRA_LOADING
383     * @see DocumentsContract#EXTRA_INFO
384     * @see DocumentsContract#EXTRA_ERROR
385     */
386    public abstract Cursor queryChildDocuments(
387            String parentDocumentId, String[] projection, String sortOrder)
388            throws FileNotFoundException;
389
390    /** {@hide} */
391    @SuppressWarnings("unused")
392    public Cursor queryChildDocumentsForManage(
393            String parentDocumentId, String[] projection, String sortOrder)
394            throws FileNotFoundException {
395        throw new UnsupportedOperationException("Manage not supported");
396    }
397
398    /**
399     * Return documents that match the given query under the requested
400     * root. The returned documents should be sorted by relevance in descending
401     * order. How documents are matched against the query string is an
402     * implementation detail left to each provider, but it's suggested that at
403     * least {@link Document#COLUMN_DISPLAY_NAME} be matched in a
404     * case-insensitive fashion.
405     * <p>
406     * Only documents may be returned; directories are not supported in search
407     * results.
408     * <p>
409     * If your provider is cloud-based, and you have some data cached or pinned
410     * locally, you may return the local data immediately, setting
411     * {@link DocumentsContract#EXTRA_LOADING} on the Cursor to indicate that
412     * you are still fetching additional data. Then, when the network data is
413     * available, you can send a change notification to trigger a requery and
414     * return the complete contents.
415     * <p>
416     * To support change notifications, you must
417     * {@link Cursor#setNotificationUri(ContentResolver, Uri)} with a relevant
418     * Uri, such as {@link DocumentsContract#buildSearchDocumentsUri(String,
419     * String, String)}. Then you can call {@link ContentResolver#notifyChange(Uri,
420     * android.database.ContentObserver, boolean)} with that Uri to send change
421     * notifications.
422     *
423     * @param rootId the root to search under.
424     * @param query string to match documents against.
425     * @param projection list of {@link Document} columns to put into the
426     *            cursor. If {@code null} all supported columns should be
427     *            included.
428     * @see DocumentsContract#EXTRA_LOADING
429     * @see DocumentsContract#EXTRA_INFO
430     * @see DocumentsContract#EXTRA_ERROR
431     */
432    @SuppressWarnings("unused")
433    public Cursor querySearchDocuments(String rootId, String query, String[] projection)
434            throws FileNotFoundException {
435        throw new UnsupportedOperationException("Search not supported");
436    }
437
438    /**
439     * Return concrete MIME type of the requested document. Must match the value
440     * of {@link Document#COLUMN_MIME_TYPE} for this document. The default
441     * implementation queries {@link #queryDocument(String, String[])}, so
442     * providers may choose to override this as an optimization.
443     */
444    public String getDocumentType(String documentId) throws FileNotFoundException {
445        final Cursor cursor = queryDocument(documentId, null);
446        try {
447            if (cursor.moveToFirst()) {
448                return cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE));
449            } else {
450                return null;
451            }
452        } finally {
453            IoUtils.closeQuietly(cursor);
454        }
455    }
456
457    /**
458     * Open and return the requested document.
459     * <p>
460     * Your provider should return a reliable {@link ParcelFileDescriptor} to
461     * detect when the remote caller has finished reading or writing the
462     * document. You may return a pipe or socket pair if the mode is exclusively
463     * "r" or "w", but complex modes like "rw" imply a normal file on disk that
464     * supports seeking.
465     * <p>
466     * If you block while downloading content, you should periodically check
467     * {@link CancellationSignal#isCanceled()} to abort abandoned open requests.
468     *
469     * @param documentId the document to return.
470     * @param mode the mode to open with, such as 'r', 'w', or 'rw'.
471     * @param signal used by the caller to signal if the request should be
472     *            cancelled. May be null.
473     * @see ParcelFileDescriptor#open(java.io.File, int, android.os.Handler,
474     *      OnCloseListener)
475     * @see ParcelFileDescriptor#createReliablePipe()
476     * @see ParcelFileDescriptor#createReliableSocketPair()
477     * @see ParcelFileDescriptor#parseMode(String)
478     */
479    public abstract ParcelFileDescriptor openDocument(
480            String documentId, String mode, CancellationSignal signal) throws FileNotFoundException;
481
482    /**
483     * Open and return a thumbnail of the requested document.
484     * <p>
485     * A provider should return a thumbnail closely matching the hinted size,
486     * attempting to serve from a local cache if possible. A provider should
487     * never return images more than double the hinted size.
488     * <p>
489     * If you perform expensive operations to download or generate a thumbnail,
490     * you should periodically check {@link CancellationSignal#isCanceled()} to
491     * abort abandoned thumbnail requests.
492     *
493     * @param documentId the document to return.
494     * @param sizeHint hint of the optimal thumbnail dimensions.
495     * @param signal used by the caller to signal if the request should be
496     *            cancelled. May be null.
497     * @see Document#FLAG_SUPPORTS_THUMBNAIL
498     */
499    @SuppressWarnings("unused")
500    public AssetFileDescriptor openDocumentThumbnail(
501            String documentId, Point sizeHint, CancellationSignal signal)
502            throws FileNotFoundException {
503        throw new UnsupportedOperationException("Thumbnails not supported");
504    }
505
506    /**
507     * Open and return the document in a format matching the specified MIME
508     * type filter.
509     * <p>
510     * A provider may perform a conversion if the documents's MIME type is not
511     * matching the specified MIME type filter.
512     *
513     * @param documentId the document to return.
514     * @param mimeTypeFilter the MIME type filter for the requested format. May
515     *            be *\/*, which matches any MIME type.
516     * @param opts extra options from the client. Specific to the content
517     *            provider.
518     * @param signal used by the caller to signal if the request should be
519     *            cancelled. May be null.
520     * @see Document#FLAG_SUPPORTS_TYPED_DOCUMENT
521     */
522    @SuppressWarnings("unused")
523    public AssetFileDescriptor openTypedDocument(
524            String documentId, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
525            throws FileNotFoundException {
526        throw new UnsupportedOperationException("Typed documents not supported");
527    }
528
529    /**
530     * Implementation is provided by the parent class. Cannot be overriden.
531     *
532     * @see #queryRoots(String[])
533     * @see #queryRecentDocuments(String, String[])
534     * @see #queryDocument(String, String[])
535     * @see #queryChildDocuments(String, String[], String)
536     * @see #querySearchDocuments(String, String, String[])
537     */
538    @Override
539    public final Cursor query(Uri uri, String[] projection, String selection,
540            String[] selectionArgs, String sortOrder) {
541        try {
542            switch (mMatcher.match(uri)) {
543                case MATCH_ROOTS:
544                    return queryRoots(projection);
545                case MATCH_RECENT:
546                    return queryRecentDocuments(getRootId(uri), projection);
547                case MATCH_SEARCH:
548                    return querySearchDocuments(
549                            getRootId(uri), getSearchDocumentsQuery(uri), projection);
550                case MATCH_DOCUMENT:
551                case MATCH_DOCUMENT_TREE:
552                    enforceTree(uri);
553                    return queryDocument(getDocumentId(uri), projection);
554                case MATCH_CHILDREN:
555                case MATCH_CHILDREN_TREE:
556                    enforceTree(uri);
557                    if (DocumentsContract.isManageMode(uri)) {
558                        return queryChildDocumentsForManage(
559                                getDocumentId(uri), projection, sortOrder);
560                    } else {
561                        return queryChildDocuments(getDocumentId(uri), projection, sortOrder);
562                    }
563                default:
564                    throw new UnsupportedOperationException("Unsupported Uri " + uri);
565            }
566        } catch (FileNotFoundException e) {
567            Log.w(TAG, "Failed during query", e);
568            return null;
569        }
570    }
571
572    /**
573     * Implementation is provided by the parent class. Cannot be overriden.
574     *
575     * @see #getDocumentType(String)
576     */
577    @Override
578    public final String getType(Uri uri) {
579        try {
580            switch (mMatcher.match(uri)) {
581                case MATCH_ROOT:
582                    return DocumentsContract.Root.MIME_TYPE_ITEM;
583                case MATCH_DOCUMENT:
584                case MATCH_DOCUMENT_TREE:
585                    enforceTree(uri);
586                    return getDocumentType(getDocumentId(uri));
587                default:
588                    return null;
589            }
590        } catch (FileNotFoundException e) {
591            Log.w(TAG, "Failed during getType", e);
592            return null;
593        }
594    }
595
596    /**
597     * Implementation is provided by the parent class. Can be overridden to
598     * provide additional functionality, but subclasses <em>must</em> always
599     * call the superclass. If the superclass returns {@code null}, the subclass
600     * may implement custom behavior.
601     * <p>
602     * This is typically used to resolve a subtree URI into a concrete document
603     * reference, issuing a narrower single-document URI permission grant along
604     * the way.
605     *
606     * @see DocumentsContract#buildDocumentUriUsingTree(Uri, String)
607     */
608    @CallSuper
609    @Override
610    public Uri canonicalize(Uri uri) {
611        final Context context = getContext();
612        switch (mMatcher.match(uri)) {
613            case MATCH_DOCUMENT_TREE:
614                enforceTree(uri);
615
616                final Uri narrowUri = buildDocumentUri(uri.getAuthority(), getDocumentId(uri));
617
618                // Caller may only have prefix grant, so extend them a grant to
619                // the narrow URI.
620                final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context, uri);
621                context.grantUriPermission(getCallingPackage(), narrowUri, modeFlags);
622                return narrowUri;
623        }
624        return null;
625    }
626
627    private static int getCallingOrSelfUriPermissionModeFlags(Context context, Uri uri) {
628        // TODO: move this to a direct AMS call
629        int modeFlags = 0;
630        if (context.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
631                == PackageManager.PERMISSION_GRANTED) {
632            modeFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION;
633        }
634        if (context.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
635                == PackageManager.PERMISSION_GRANTED) {
636            modeFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
637        }
638        if (context.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION
639                | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
640                == PackageManager.PERMISSION_GRANTED) {
641            modeFlags |= Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
642        }
643        return modeFlags;
644    }
645
646    /**
647     * Implementation is provided by the parent class. Throws by default, and
648     * cannot be overriden.
649     *
650     * @see #createDocument(String, String, String)
651     */
652    @Override
653    public final Uri insert(Uri uri, ContentValues values) {
654        throw new UnsupportedOperationException("Insert not supported");
655    }
656
657    /**
658     * Implementation is provided by the parent class. Throws by default, and
659     * cannot be overriden.
660     *
661     * @see #deleteDocument(String)
662     */
663    @Override
664    public final int delete(Uri uri, String selection, String[] selectionArgs) {
665        throw new UnsupportedOperationException("Delete not supported");
666    }
667
668    /**
669     * Implementation is provided by the parent class. Throws by default, and
670     * cannot be overriden.
671     */
672    @Override
673    public final int update(
674            Uri uri, ContentValues values, String selection, String[] selectionArgs) {
675        throw new UnsupportedOperationException("Update not supported");
676    }
677
678    /**
679     * Implementation is provided by the parent class. Can be overridden to
680     * provide additional functionality, but subclasses <em>must</em> always
681     * call the superclass. If the superclass returns {@code null}, the subclass
682     * may implement custom behavior.
683     */
684    @CallSuper
685    @Override
686    public Bundle call(String method, String arg, Bundle extras) {
687        if (!method.startsWith("android:")) {
688            // Ignore non-platform methods
689            return super.call(method, arg, extras);
690        }
691
692        try {
693            return callUnchecked(method, arg, extras);
694        } catch (FileNotFoundException e) {
695            throw new IllegalStateException("Failed call " + method, e);
696        }
697    }
698
699    private Bundle callUnchecked(String method, String arg, Bundle extras)
700            throws FileNotFoundException {
701
702        final Context context = getContext();
703        final Uri documentUri = extras.getParcelable(DocumentsContract.EXTRA_URI);
704        final String authority = documentUri.getAuthority();
705        final String documentId = DocumentsContract.getDocumentId(documentUri);
706
707        if (!mAuthority.equals(authority)) {
708            throw new SecurityException(
709                    "Requested authority " + authority + " doesn't match provider " + mAuthority);
710        }
711
712        final Bundle out = new Bundle();
713
714        // If the URI is a tree URI performs some validation.
715        enforceTree(documentUri);
716
717        if (METHOD_IS_CHILD_DOCUMENT.equals(method)) {
718            enforceReadPermissionInner(documentUri, getCallingPackage(), null);
719
720            final Uri childUri = extras.getParcelable(DocumentsContract.EXTRA_TARGET_URI);
721            final String childAuthority = childUri.getAuthority();
722            final String childId = DocumentsContract.getDocumentId(childUri);
723
724            out.putBoolean(
725                    DocumentsContract.EXTRA_RESULT,
726                    mAuthority.equals(childAuthority)
727                            && isChildDocument(documentId, childId));
728
729        } else if (METHOD_CREATE_DOCUMENT.equals(method)) {
730            enforceWritePermissionInner(documentUri, getCallingPackage(), null);
731
732            final String mimeType = extras.getString(Document.COLUMN_MIME_TYPE);
733            final String displayName = extras.getString(Document.COLUMN_DISPLAY_NAME);
734            final String newDocumentId = createDocument(documentId, mimeType, displayName);
735
736            // No need to issue new grants here, since caller either has
737            // manage permission or a prefix grant. We might generate a
738            // tree style URI if that's how they called us.
739            final Uri newDocumentUri = buildDocumentUriMaybeUsingTree(documentUri,
740                    newDocumentId);
741            out.putParcelable(DocumentsContract.EXTRA_URI, newDocumentUri);
742
743        } else if (METHOD_RENAME_DOCUMENT.equals(method)) {
744            enforceWritePermissionInner(documentUri, getCallingPackage(), null);
745
746            final String displayName = extras.getString(Document.COLUMN_DISPLAY_NAME);
747            final String newDocumentId = renameDocument(documentId, displayName);
748
749            if (newDocumentId != null) {
750                final Uri newDocumentUri = buildDocumentUriMaybeUsingTree(documentUri,
751                        newDocumentId);
752
753                // If caller came in with a narrow grant, issue them a
754                // narrow grant for the newly renamed document.
755                if (!isTreeUri(newDocumentUri)) {
756                    final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context,
757                            documentUri);
758                    context.grantUriPermission(getCallingPackage(), newDocumentUri, modeFlags);
759                }
760
761                out.putParcelable(DocumentsContract.EXTRA_URI, newDocumentUri);
762
763                // Original document no longer exists, clean up any grants
764                revokeDocumentPermission(documentId);
765            }
766
767        } else if (METHOD_DELETE_DOCUMENT.equals(method)) {
768            enforceWritePermissionInner(documentUri, getCallingPackage(), null);
769            deleteDocument(documentId);
770
771            // Document no longer exists, clean up any grants
772            revokeDocumentPermission(documentId);
773
774        } else if (METHOD_COPY_DOCUMENT.equals(method)) {
775            final Uri targetUri = extras.getParcelable(DocumentsContract.EXTRA_TARGET_URI);
776            final String targetId = DocumentsContract.getDocumentId(targetUri);
777
778            enforceReadPermissionInner(documentUri, getCallingPackage(), null);
779            enforceWritePermissionInner(targetUri, getCallingPackage(), null);
780
781            final String newDocumentId = copyDocument(documentId, targetId);
782
783            if (newDocumentId != null) {
784                final Uri newDocumentUri = buildDocumentUriMaybeUsingTree(documentUri,
785                        newDocumentId);
786
787                if (!isTreeUri(newDocumentUri)) {
788                    final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context,
789                            documentUri);
790                    context.grantUriPermission(getCallingPackage(), newDocumentUri, modeFlags);
791                }
792
793                out.putParcelable(DocumentsContract.EXTRA_URI, newDocumentUri);
794            }
795
796        } else if (METHOD_MOVE_DOCUMENT.equals(method)) {
797            final Uri targetUri = extras.getParcelable(DocumentsContract.EXTRA_TARGET_URI);
798            final String targetId = DocumentsContract.getDocumentId(targetUri);
799
800            enforceReadPermissionInner(documentUri, getCallingPackage(), null);
801            enforceWritePermissionInner(targetUri, getCallingPackage(), null);
802
803            final String newDocumentId = moveDocument(documentId, targetId);
804
805            if (newDocumentId != null) {
806                final Uri newDocumentUri = buildDocumentUriMaybeUsingTree(documentUri,
807                        newDocumentId);
808
809                if (!isTreeUri(newDocumentUri)) {
810                    final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context,
811                            documentUri);
812                    context.grantUriPermission(getCallingPackage(), newDocumentUri, modeFlags);
813                }
814
815                out.putParcelable(DocumentsContract.EXTRA_URI, newDocumentUri);
816            }
817
818            // Original document no longer exists, clean up any grants
819            revokeDocumentPermission(documentId);
820
821        } else {
822            throw new UnsupportedOperationException("Method not supported " + method);
823        }
824
825        return out;
826    }
827
828    /**
829     * Revoke any active permission grants for the given
830     * {@link Document#COLUMN_DOCUMENT_ID}, usually called when a document
831     * becomes invalid. Follows the same semantics as
832     * {@link Context#revokeUriPermission(Uri, int)}.
833     */
834    public final void revokeDocumentPermission(String documentId) {
835        final Context context = getContext();
836        context.revokeUriPermission(buildDocumentUri(mAuthority, documentId), ~0);
837        context.revokeUriPermission(buildTreeDocumentUri(mAuthority, documentId), ~0);
838    }
839
840    /**
841     * Implementation is provided by the parent class. Cannot be overriden.
842     *
843     * @see #openDocument(String, String, CancellationSignal)
844     */
845    @Override
846    public final ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
847        enforceTree(uri);
848        return openDocument(getDocumentId(uri), mode, null);
849    }
850
851    /**
852     * Implementation is provided by the parent class. Cannot be overriden.
853     *
854     * @see #openDocument(String, String, CancellationSignal)
855     */
856    @Override
857    public final ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
858            throws FileNotFoundException {
859        enforceTree(uri);
860        return openDocument(getDocumentId(uri), mode, signal);
861    }
862
863    /**
864     * Implementation is provided by the parent class. Cannot be overriden.
865     *
866     * @see #openDocument(String, String, CancellationSignal)
867     */
868    @Override
869    @SuppressWarnings("resource")
870    public final AssetFileDescriptor openAssetFile(Uri uri, String mode)
871            throws FileNotFoundException {
872        enforceTree(uri);
873        final ParcelFileDescriptor fd = openDocument(getDocumentId(uri), mode, null);
874        return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
875    }
876
877    /**
878     * Implementation is provided by the parent class. Cannot be overriden.
879     *
880     * @see #openDocument(String, String, CancellationSignal)
881     */
882    @Override
883    @SuppressWarnings("resource")
884    public final AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
885            throws FileNotFoundException {
886        enforceTree(uri);
887        final ParcelFileDescriptor fd = openDocument(getDocumentId(uri), mode, signal);
888        return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
889    }
890
891    /**
892     * Implementation is provided by the parent class. Cannot be overriden.
893     *
894     * @see #openDocumentThumbnail(String, Point, CancellationSignal)
895     * @see #openTypedDocument(String, String, Bundle, CancellationSignal)
896     */
897    @Override
898    public final AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
899            throws FileNotFoundException {
900        return openTypedAssetFileImpl(uri, mimeTypeFilter, opts, null);
901    }
902
903    /**
904     * Implementation is provided by the parent class. Cannot be overriden.
905     *
906     * @see #openDocumentThumbnail(String, Point, CancellationSignal)
907     * @see #openTypedDocument(String, String, Bundle, CancellationSignal)
908     */
909    @Override
910    public final AssetFileDescriptor openTypedAssetFile(
911            Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
912            throws FileNotFoundException {
913        return openTypedAssetFileImpl(uri, mimeTypeFilter, opts, signal);
914    }
915
916    /**
917     * @hide
918     */
919    private final AssetFileDescriptor openTypedAssetFileImpl(
920            Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
921            throws FileNotFoundException {
922        enforceTree(uri);
923        final String documentId = getDocumentId(uri);
924        if (opts != null && opts.containsKey(ContentResolver.EXTRA_SIZE)) {
925            final Point sizeHint = opts.getParcelable(ContentResolver.EXTRA_SIZE);
926            return openDocumentThumbnail(documentId, sizeHint, signal);
927        }
928        if ("*/*".equals(mimeTypeFilter)) {
929             // If they can take anything, the untyped open call is good enough.
930             return openAssetFile(uri, "r");
931        }
932        final String baseType = getType(uri);
933        if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
934            // Use old untyped open call if this provider has a type for this
935            // URI and it matches the request.
936            return openAssetFile(uri, "r");
937        }
938        // For any other yet unhandled case, let the provider subclass handle it.
939        return openTypedDocument(documentId, mimeTypeFilter, opts, signal);
940    }
941}
942