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 
17 package android.provider;
18 
19 import static android.net.TrafficStats.KB_IN_BYTES;
20 import static android.system.OsConstants.SEEK_SET;
21 import static com.android.internal.util.Preconditions.checkArgument;
22 import static com.android.internal.util.Preconditions.checkCollectionElementsNotNull;
23 import static com.android.internal.util.Preconditions.checkCollectionNotEmpty;
24 
25 import android.annotation.Nullable;
26 import android.content.ContentProviderClient;
27 import android.content.ContentResolver;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.content.IntentSender;
31 import android.content.pm.PackageManager;
32 import android.content.pm.ResolveInfo;
33 import android.content.res.AssetFileDescriptor;
34 import android.database.Cursor;
35 import android.graphics.Bitmap;
36 import android.graphics.BitmapFactory;
37 import android.graphics.Matrix;
38 import android.graphics.Point;
39 import android.media.ExifInterface;
40 import android.net.Uri;
41 import android.os.Build;
42 import android.os.Bundle;
43 import android.os.CancellationSignal;
44 import android.os.OperationCanceledException;
45 import android.os.Parcel;
46 import android.os.ParcelFileDescriptor;
47 import android.os.ParcelFileDescriptor.OnCloseListener;
48 import android.os.Parcelable;
49 import android.os.ParcelableException;
50 import android.os.RemoteException;
51 import android.os.storage.StorageVolume;
52 import android.system.ErrnoException;
53 import android.system.Os;
54 import android.util.Log;
55 
56 import libcore.io.IoUtils;
57 
58 import java.io.BufferedInputStream;
59 import java.io.File;
60 import java.io.FileDescriptor;
61 import java.io.FileInputStream;
62 import java.io.FileNotFoundException;
63 import java.io.IOException;
64 import java.util.List;
65 import java.util.Objects;
66 
67 /**
68  * Defines the contract between a documents provider and the platform.
69  * <p>
70  * To create a document provider, extend {@link DocumentsProvider}, which
71  * provides a foundational implementation of this contract.
72  * <p>
73  * All client apps must hold a valid URI permission grant to access documents,
74  * typically issued when a user makes a selection through
75  * {@link Intent#ACTION_OPEN_DOCUMENT}, {@link Intent#ACTION_CREATE_DOCUMENT},
76  * {@link Intent#ACTION_OPEN_DOCUMENT_TREE}, or
77  * {@link StorageVolume#createAccessIntent(String) StorageVolume.createAccessIntent}.
78  *
79  * @see DocumentsProvider
80  */
81 public final class DocumentsContract {
82     private static final String TAG = "DocumentsContract";
83 
84     // content://com.example/root/
85     // content://com.example/root/sdcard/
86     // content://com.example/root/sdcard/recent/
87     // content://com.example/root/sdcard/search/?query=pony
88     // content://com.example/document/12/
89     // content://com.example/document/12/children/
90     // content://com.example/tree/12/document/24/
91     // content://com.example/tree/12/document/24/children/
92 
DocumentsContract()93     private DocumentsContract() {
94     }
95 
96     /**
97      * Intent action used to identify {@link DocumentsProvider} instances. This
98      * is used in the {@code <intent-filter>} of a {@code <provider>}.
99      */
100     public static final String PROVIDER_INTERFACE = "android.content.action.DOCUMENTS_PROVIDER";
101 
102     /** {@hide} */
103     public static final String EXTRA_PACKAGE_NAME = "android.content.extra.PACKAGE_NAME";
104 
105     /** {@hide} */
106     public static final String EXTRA_SHOW_ADVANCED = "android.content.extra.SHOW_ADVANCED";
107 
108     /** {@hide} */
109     public static final String EXTRA_TARGET_URI = "android.content.extra.TARGET_URI";
110 
111     /**
112      * Sets the desired initial location visible to user when file chooser is shown.
113      *
114      * <p>Applicable to {@link Intent} with actions:
115      * <ul>
116      *      <li>{@link Intent#ACTION_OPEN_DOCUMENT}</li>
117      *      <li>{@link Intent#ACTION_CREATE_DOCUMENT}</li>
118      *      <li>{@link Intent#ACTION_OPEN_DOCUMENT_TREE}</li>
119      * </ul>
120      *
121      * <p>Location should specify a document URI or a tree URI with document ID. If
122      * this URI identifies a non-directory, document navigator will attempt to use the parent
123      * of the document as the initial location.
124      *
125      * <p>The initial location is system specific if this extra is missing or document navigator
126      * failed to locate the desired initial location.
127      */
128     public static final String EXTRA_INITIAL_URI = "android.provider.extra.INITIAL_URI";
129 
130     /**
131      * Set this in a DocumentsUI intent to cause a package's own roots to be
132      * excluded from the roots list.
133      */
134     public static final String EXTRA_EXCLUDE_SELF = "android.provider.extra.EXCLUDE_SELF";
135 
136     /**
137      * Included in {@link AssetFileDescriptor#getExtras()} when returned
138      * thumbnail should be rotated.
139      *
140      * @see MediaStore.Images.ImageColumns#ORIENTATION
141      */
142     public static final String EXTRA_ORIENTATION = "android.provider.extra.ORIENTATION";
143 
144     /**
145      * Overrides the default prompt text in DocumentsUI when set in an intent.
146      */
147     public static final String EXTRA_PROMPT = "android.provider.extra.PROMPT";
148 
149     /**
150      * Action of intent issued by DocumentsUI when user wishes to open/configure/manage a particular
151      * document in the provider application.
152      *
153      * <p>When issued, the intent will include the URI of the document as the intent data.
154      *
155      * <p>A provider wishing to provide support for this action should do two things.
156      * <li>Add an {@code <intent-filter>} matching this action.
157      * <li>When supplying information in {@link DocumentsProvider#queryChildDocuments}, include
158      * {@link Document#FLAG_SUPPORTS_SETTINGS} in the flags for each document that supports
159      * settings.
160      *
161      * @see DocumentsContact#Document#FLAG_SUPPORTS_SETTINGS
162      */
163     public static final String
164             ACTION_DOCUMENT_SETTINGS = "android.provider.action.DOCUMENT_SETTINGS";
165 
166     /** {@hide} */
167     public static final String ACTION_MANAGE_DOCUMENT = "android.provider.action.MANAGE_DOCUMENT";
168 
169     /** {@hide} */
170     public static final String
171             ACTION_DOCUMENT_ROOT_SETTINGS = "android.provider.action.DOCUMENT_ROOT_SETTINGS";
172 
173     /**
174      * Buffer is large enough to rewind past any EXIF headers.
175      */
176     private static final int THUMBNAIL_BUFFER_SIZE = (int) (128 * KB_IN_BYTES);
177 
178     /** {@hide} */
179     public static final String EXTERNAL_STORAGE_PROVIDER_AUTHORITY =
180             "com.android.externalstorage.documents";
181 
182     /** {@hide} */
183     public static final String PACKAGE_DOCUMENTS_UI = "com.android.documentsui";
184 
185     /**
186      * Constants related to a document, including {@link Cursor} column names
187      * and flags.
188      * <p>
189      * A document can be either an openable stream (with a specific MIME type),
190      * or a directory containing additional documents (with the
191      * {@link #MIME_TYPE_DIR} MIME type). A directory represents the top of a
192      * subtree containing zero or more documents, which can recursively contain
193      * even more documents and directories.
194      * <p>
195      * All columns are <em>read-only</em> to client applications.
196      */
197     public final static class Document {
Document()198         private Document() {
199         }
200 
201         /**
202          * Unique ID of a document. This ID is both provided by and interpreted
203          * by a {@link DocumentsProvider}, and should be treated as an opaque
204          * value by client applications. This column is required.
205          * <p>
206          * Each document must have a unique ID within a provider, but that
207          * single document may be included as a child of multiple directories.
208          * <p>
209          * A provider must always return durable IDs, since they will be used to
210          * issue long-term URI permission grants when an application interacts
211          * with {@link Intent#ACTION_OPEN_DOCUMENT} and
212          * {@link Intent#ACTION_CREATE_DOCUMENT}.
213          * <p>
214          * Type: STRING
215          */
216         public static final String COLUMN_DOCUMENT_ID = "document_id";
217 
218         /**
219          * Concrete MIME type of a document. For example, "image/png" or
220          * "application/pdf" for openable files. A document can also be a
221          * directory containing additional documents, which is represented with
222          * the {@link #MIME_TYPE_DIR} MIME type. This column is required.
223          * <p>
224          * Type: STRING
225          *
226          * @see #MIME_TYPE_DIR
227          */
228         public static final String COLUMN_MIME_TYPE = "mime_type";
229 
230         /**
231          * Display name of a document, used as the primary title displayed to a
232          * user. This column is required.
233          * <p>
234          * Type: STRING
235          */
236         public static final String COLUMN_DISPLAY_NAME = OpenableColumns.DISPLAY_NAME;
237 
238         /**
239          * Summary of a document, which may be shown to a user. This column is
240          * optional, and may be {@code null}.
241          * <p>
242          * Type: STRING
243          */
244         public static final String COLUMN_SUMMARY = "summary";
245 
246         /**
247          * Timestamp when a document was last modified, in milliseconds since
248          * January 1, 1970 00:00:00.0 UTC. This column is required, and may be
249          * {@code null} if unknown. A {@link DocumentsProvider} can update this
250          * field using events from {@link OnCloseListener} or other reliable
251          * {@link ParcelFileDescriptor} transports.
252          * <p>
253          * Type: INTEGER (long)
254          *
255          * @see System#currentTimeMillis()
256          */
257         public static final String COLUMN_LAST_MODIFIED = "last_modified";
258 
259         /**
260          * Specific icon resource ID for a document. This column is optional,
261          * and may be {@code null} to use a platform-provided default icon based
262          * on {@link #COLUMN_MIME_TYPE}.
263          * <p>
264          * Type: INTEGER (int)
265          */
266         public static final String COLUMN_ICON = "icon";
267 
268         /**
269          * Flags that apply to a document. This column is required.
270          * <p>
271          * Type: INTEGER (int)
272          *
273          * @see #FLAG_SUPPORTS_WRITE
274          * @see #FLAG_SUPPORTS_DELETE
275          * @see #FLAG_SUPPORTS_THUMBNAIL
276          * @see #FLAG_DIR_PREFERS_GRID
277          * @see #FLAG_DIR_PREFERS_LAST_MODIFIED
278          * @see #FLAG_VIRTUAL_DOCUMENT
279          * @see #FLAG_SUPPORTS_COPY
280          * @see #FLAG_SUPPORTS_MOVE
281          * @see #FLAG_SUPPORTS_REMOVE
282          */
283         public static final String COLUMN_FLAGS = "flags";
284 
285         /**
286          * Size of a document, in bytes, or {@code null} if unknown. This column
287          * is required.
288          * <p>
289          * Type: INTEGER (long)
290          */
291         public static final String COLUMN_SIZE = OpenableColumns.SIZE;
292 
293         /**
294          * MIME type of a document which is a directory that may contain
295          * additional documents.
296          *
297          * @see #COLUMN_MIME_TYPE
298          */
299         public static final String MIME_TYPE_DIR = "vnd.android.document/directory";
300 
301         /**
302          * Flag indicating that a document can be represented as a thumbnail.
303          *
304          * @see #COLUMN_FLAGS
305          * @see DocumentsContract#getDocumentThumbnail(ContentResolver, Uri,
306          *      Point, CancellationSignal)
307          * @see DocumentsProvider#openDocumentThumbnail(String, Point,
308          *      android.os.CancellationSignal)
309          */
310         public static final int FLAG_SUPPORTS_THUMBNAIL = 1;
311 
312         /**
313          * Flag indicating that a document supports writing.
314          * <p>
315          * When a document is opened with {@link Intent#ACTION_OPEN_DOCUMENT},
316          * the calling application is granted both
317          * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
318          * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. However, the actual
319          * writability of a document may change over time, for example due to
320          * remote access changes. This flag indicates that a document client can
321          * expect {@link ContentResolver#openOutputStream(Uri)} to succeed.
322          *
323          * @see #COLUMN_FLAGS
324          */
325         public static final int FLAG_SUPPORTS_WRITE = 1 << 1;
326 
327         /**
328          * Flag indicating that a document is deletable.
329          *
330          * @see #COLUMN_FLAGS
331          * @see DocumentsContract#deleteDocument(ContentResolver, Uri)
332          * @see DocumentsProvider#deleteDocument(String)
333          */
334         public static final int FLAG_SUPPORTS_DELETE = 1 << 2;
335 
336         /**
337          * Flag indicating that a document is a directory that supports creation
338          * of new files within it. Only valid when {@link #COLUMN_MIME_TYPE} is
339          * {@link #MIME_TYPE_DIR}.
340          *
341          * @see #COLUMN_FLAGS
342          * @see DocumentsProvider#createDocument(String, String, String)
343          */
344         public static final int FLAG_DIR_SUPPORTS_CREATE = 1 << 3;
345 
346         /**
347          * Flag indicating that a directory prefers its contents be shown in a
348          * larger format grid. Usually suitable when a directory contains mostly
349          * pictures. Only valid when {@link #COLUMN_MIME_TYPE} is
350          * {@link #MIME_TYPE_DIR}.
351          *
352          * @see #COLUMN_FLAGS
353          */
354         public static final int FLAG_DIR_PREFERS_GRID = 1 << 4;
355 
356         /**
357          * Flag indicating that a directory prefers its contents be sorted by
358          * {@link #COLUMN_LAST_MODIFIED}. Only valid when
359          * {@link #COLUMN_MIME_TYPE} is {@link #MIME_TYPE_DIR}.
360          *
361          * @see #COLUMN_FLAGS
362          */
363         public static final int FLAG_DIR_PREFERS_LAST_MODIFIED = 1 << 5;
364 
365         /**
366          * Flag indicating that a document can be renamed.
367          *
368          * @see #COLUMN_FLAGS
369          * @see DocumentsContract#renameDocument(ContentResolver, Uri,
370          *      String)
371          * @see DocumentsProvider#renameDocument(String, String)
372          */
373         public static final int FLAG_SUPPORTS_RENAME = 1 << 6;
374 
375         /**
376          * Flag indicating that a document can be copied to another location
377          * within the same document provider.
378          *
379          * @see #COLUMN_FLAGS
380          * @see DocumentsContract#copyDocument(ContentResolver, Uri, Uri)
381          * @see DocumentsProvider#copyDocument(String, String)
382          */
383         public static final int FLAG_SUPPORTS_COPY = 1 << 7;
384 
385         /**
386          * Flag indicating that a document can be moved to another location
387          * within the same document provider.
388          *
389          * @see #COLUMN_FLAGS
390          * @see DocumentsContract#moveDocument(ContentResolver, Uri, Uri, Uri)
391          * @see DocumentsProvider#moveDocument(String, String, String)
392          */
393         public static final int FLAG_SUPPORTS_MOVE = 1 << 8;
394 
395         /**
396          * Flag indicating that a document is virtual, and doesn't have byte
397          * representation in the MIME type specified as {@link #COLUMN_MIME_TYPE}.
398          *
399          * <p><em>Virtual documents must have at least one alternative streamable
400          * format via {@link DocumentsProvider#openTypedDocument}</em>
401          *
402          * @see #COLUMN_FLAGS
403          * @see #COLUMN_MIME_TYPE
404          * @see DocumentsProvider#openTypedDocument(String, String, Bundle,
405          *      android.os.CancellationSignal)
406          * @see DocumentsProvider#getDocumentStreamTypes(String, String)
407          */
408         public static final int FLAG_VIRTUAL_DOCUMENT = 1 << 9;
409 
410         /**
411          * Flag indicating that a document can be removed from a parent.
412          *
413          * @see #COLUMN_FLAGS
414          * @see DocumentsContract#removeDocument(ContentResolver, Uri, Uri)
415          * @see DocumentsProvider#removeDocument(String, String)
416          */
417         public static final int FLAG_SUPPORTS_REMOVE = 1 << 10;
418 
419         /**
420          * Flag indicating that a document has settings that can be configured by user.
421          *
422          * @see #COLUMN_FLAGS
423          * @see #ACTION_DOCUMENT_SETTINGS
424          */
425         public static final int FLAG_SUPPORTS_SETTINGS = 1 << 11;
426 
427         /**
428          * Flag indicating that a Web link can be obtained for the document.
429          *
430          * @see #COLUMN_FLAGS
431          * @see DocumentsContract#createWebLinkIntent(PackageManager, Uri, Bundle)
432          */
433         public static final int FLAG_WEB_LINKABLE = 1 << 12;
434 
435         /**
436          * Flag indicating that a document is not complete, likely its
437          * contents are being downloaded. Partial files cannot be opened,
438          * copied, moved in the UI. But they can be deleted and retried
439          * if they represent a failed download.
440          *
441          * @see #COLUMN_FLAGS
442          * @hide
443          */
444         public static final int FLAG_PARTIAL = 1 << 16;
445     }
446 
447     /**
448      * Constants related to a root of documents, including {@link Cursor} column
449      * names and flags. A root is the start of a tree of documents, such as a
450      * physical storage device, or an account. Each root starts at the directory
451      * referenced by {@link Root#COLUMN_DOCUMENT_ID}, which can recursively
452      * contain both documents and directories.
453      * <p>
454      * All columns are <em>read-only</em> to client applications.
455      */
456     public final static class Root {
Root()457         private Root() {
458         }
459 
460         /**
461          * Unique ID of a root. This ID is both provided by and interpreted by a
462          * {@link DocumentsProvider}, and should be treated as an opaque value
463          * by client applications. This column is required.
464          * <p>
465          * Type: STRING
466          */
467         public static final String COLUMN_ROOT_ID = "root_id";
468 
469         /**
470          * Flags that apply to a root. This column is required.
471          * <p>
472          * Type: INTEGER (int)
473          *
474          * @see #FLAG_LOCAL_ONLY
475          * @see #FLAG_SUPPORTS_CREATE
476          * @see #FLAG_SUPPORTS_RECENTS
477          * @see #FLAG_SUPPORTS_SEARCH
478          */
479         public static final String COLUMN_FLAGS = "flags";
480 
481         /**
482          * Icon resource ID for a root. This column is required.
483          * <p>
484          * Type: INTEGER (int)
485          */
486         public static final String COLUMN_ICON = "icon";
487 
488         /**
489          * Title for a root, which will be shown to a user. This column is
490          * required. For a single storage service surfacing multiple accounts as
491          * different roots, this title should be the name of the service.
492          * <p>
493          * Type: STRING
494          */
495         public static final String COLUMN_TITLE = "title";
496 
497         /**
498          * Summary for this root, which may be shown to a user. This column is
499          * optional, and may be {@code null}. For a single storage service
500          * surfacing multiple accounts as different roots, this summary should
501          * be the name of the account.
502          * <p>
503          * Type: STRING
504          */
505         public static final String COLUMN_SUMMARY = "summary";
506 
507         /**
508          * Document which is a directory that represents the top directory of
509          * this root. This column is required.
510          * <p>
511          * Type: STRING
512          *
513          * @see Document#COLUMN_DOCUMENT_ID
514          */
515         public static final String COLUMN_DOCUMENT_ID = "document_id";
516 
517         /**
518          * Number of bytes available in this root. This column is optional, and
519          * may be {@code null} if unknown or unbounded.
520          * <p>
521          * Type: INTEGER (long)
522          */
523         public static final String COLUMN_AVAILABLE_BYTES = "available_bytes";
524 
525         /**
526          * Capacity of a root in bytes. This column is optional, and may be
527          * {@code null} if unknown or unbounded.
528          * <p>
529          * Type: INTEGER (long)
530          */
531         public static final String COLUMN_CAPACITY_BYTES = "capacity_bytes";
532 
533         /**
534          * MIME types supported by this root. This column is optional, and if
535          * {@code null} the root is assumed to support all MIME types. Multiple
536          * MIME types can be separated by a newline. For example, a root
537          * supporting audio might return "audio/*\napplication/x-flac".
538          * <p>
539          * Type: STRING
540          */
541         public static final String COLUMN_MIME_TYPES = "mime_types";
542 
543         /**
544          * MIME type for a root.
545          */
546         public static final String MIME_TYPE_ITEM = "vnd.android.document/root";
547 
548         /**
549          * Flag indicating that at least one directory under this root supports
550          * creating content. Roots with this flag will be shown when an
551          * application interacts with {@link Intent#ACTION_CREATE_DOCUMENT}.
552          *
553          * @see #COLUMN_FLAGS
554          */
555         public static final int FLAG_SUPPORTS_CREATE = 1;
556 
557         /**
558          * Flag indicating that this root offers content that is strictly local
559          * on the device. That is, no network requests are made for the content.
560          *
561          * @see #COLUMN_FLAGS
562          * @see Intent#EXTRA_LOCAL_ONLY
563          */
564         public static final int FLAG_LOCAL_ONLY = 1 << 1;
565 
566         /**
567          * Flag indicating that this root can be queried to provide recently
568          * modified documents.
569          *
570          * @see #COLUMN_FLAGS
571          * @see DocumentsContract#buildRecentDocumentsUri(String, String)
572          * @see DocumentsProvider#queryRecentDocuments(String, String[])
573          */
574         public static final int FLAG_SUPPORTS_RECENTS = 1 << 2;
575 
576         /**
577          * Flag indicating that this root supports search.
578          *
579          * @see #COLUMN_FLAGS
580          * @see DocumentsContract#buildSearchDocumentsUri(String, String,
581          *      String)
582          * @see DocumentsProvider#querySearchDocuments(String, String,
583          *      String[])
584          */
585         public static final int FLAG_SUPPORTS_SEARCH = 1 << 3;
586 
587         /**
588          * Flag indicating that this root supports testing parent child
589          * relationships.
590          *
591          * @see #COLUMN_FLAGS
592          * @see DocumentsProvider#isChildDocument(String, String)
593          */
594         public static final int FLAG_SUPPORTS_IS_CHILD = 1 << 4;
595 
596         /**
597          * Flag indicating that this root can be ejected.
598          *
599          * @see #COLUMN_FLAGS
600          * @see DocumentsContract#ejectRoot(ContentResolver, Uri)
601          * @see DocumentsProvider#ejectRoot(String)
602          */
603         public static final int FLAG_SUPPORTS_EJECT = 1 << 5;
604 
605         /**
606          * Flag indicating that this root is currently empty. This may be used
607          * to hide the root when opening documents, but the root will still be
608          * shown when creating documents and {@link #FLAG_SUPPORTS_CREATE} is
609          * also set. If the value of this flag changes, such as when a root
610          * becomes non-empty, you must send a content changed notification for
611          * {@link DocumentsContract#buildRootsUri(String)}.
612          *
613          * @see #COLUMN_FLAGS
614          * @see ContentResolver#notifyChange(Uri,
615          *      android.database.ContentObserver, boolean)
616          * @hide
617          */
618         public static final int FLAG_EMPTY = 1 << 16;
619 
620         /**
621          * Flag indicating that this root should only be visible to advanced
622          * users.
623          *
624          * @see #COLUMN_FLAGS
625          * @hide
626          */
627         public static final int FLAG_ADVANCED = 1 << 17;
628 
629         /**
630          * Flag indicating that this root has settings.
631          *
632          * @see #COLUMN_FLAGS
633          * @see DocumentsContract#ACTION_DOCUMENT_ROOT_SETTINGS
634          * @hide
635          */
636         public static final int FLAG_HAS_SETTINGS = 1 << 18;
637 
638         /**
639          * Flag indicating that this root is on removable SD card storage.
640          *
641          * @see #COLUMN_FLAGS
642          * @hide
643          */
644         public static final int FLAG_REMOVABLE_SD = 1 << 19;
645 
646         /**
647          * Flag indicating that this root is on removable USB storage.
648          *
649          * @see #COLUMN_FLAGS
650          * @hide
651          */
652         public static final int FLAG_REMOVABLE_USB = 1 << 20;
653     }
654 
655     /**
656      * Optional boolean flag included in a directory {@link Cursor#getExtras()}
657      * indicating that a document provider is still loading data. For example, a
658      * provider has returned some results, but is still waiting on an
659      * outstanding network request. The provider must send a content changed
660      * notification when loading is finished.
661      *
662      * @see ContentResolver#notifyChange(Uri, android.database.ContentObserver,
663      *      boolean)
664      */
665     public static final String EXTRA_LOADING = "loading";
666 
667     /**
668      * Optional string included in a directory {@link Cursor#getExtras()}
669      * providing an informational message that should be shown to a user. For
670      * example, a provider may wish to indicate that not all documents are
671      * available.
672      */
673     public static final String EXTRA_INFO = "info";
674 
675     /**
676      * Optional string included in a directory {@link Cursor#getExtras()}
677      * providing an error message that should be shown to a user. For example, a
678      * provider may wish to indicate that a network error occurred. The user may
679      * choose to retry, resulting in a new query.
680      */
681     public static final String EXTRA_ERROR = "error";
682 
683     /**
684      * Optional result (I'm thinking boolean) answer to a question.
685      * {@hide}
686      */
687     public static final String EXTRA_RESULT = "result";
688 
689     /** {@hide} */
690     public static final String METHOD_CREATE_DOCUMENT = "android:createDocument";
691     /** {@hide} */
692     public static final String METHOD_RENAME_DOCUMENT = "android:renameDocument";
693     /** {@hide} */
694     public static final String METHOD_DELETE_DOCUMENT = "android:deleteDocument";
695     /** {@hide} */
696     public static final String METHOD_COPY_DOCUMENT = "android:copyDocument";
697     /** {@hide} */
698     public static final String METHOD_MOVE_DOCUMENT = "android:moveDocument";
699     /** {@hide} */
700     public static final String METHOD_IS_CHILD_DOCUMENT = "android:isChildDocument";
701     /** {@hide} */
702     public static final String METHOD_REMOVE_DOCUMENT = "android:removeDocument";
703     /** {@hide} */
704     public static final String METHOD_EJECT_ROOT = "android:ejectRoot";
705     /** {@hide} */
706     public static final String METHOD_FIND_DOCUMENT_PATH = "android:findDocumentPath";
707     /** {@hide} */
708     public static final String METHOD_CREATE_WEB_LINK_INTENT = "android:createWebLinkIntent";
709 
710     /** {@hide} */
711     public static final String EXTRA_PARENT_URI = "parentUri";
712     /** {@hide} */
713     public static final String EXTRA_URI = "uri";
714 
715     /**
716      * @see #createWebLinkIntent(ContentResolver, Uri, Bundle)
717      * {@hide}
718      */
719     public static final String EXTRA_OPTIONS = "options";
720 
721     private static final String PATH_ROOT = "root";
722     private static final String PATH_RECENT = "recent";
723     private static final String PATH_DOCUMENT = "document";
724     private static final String PATH_CHILDREN = "children";
725     private static final String PATH_SEARCH = "search";
726     private static final String PATH_TREE = "tree";
727 
728     private static final String PARAM_QUERY = "query";
729     private static final String PARAM_MANAGE = "manage";
730 
731     /**
732      * Build URI representing the roots of a document provider. When queried, a
733      * provider will return one or more rows with columns defined by
734      * {@link Root}.
735      *
736      * @see DocumentsProvider#queryRoots(String[])
737      */
buildRootsUri(String authority)738     public static Uri buildRootsUri(String authority) {
739         return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
740                 .authority(authority).appendPath(PATH_ROOT).build();
741     }
742 
743     /**
744      * Build URI representing the given {@link Root#COLUMN_ROOT_ID} in a
745      * document provider.
746      *
747      * @see #getRootId(Uri)
748      */
buildRootUri(String authority, String rootId)749     public static Uri buildRootUri(String authority, String rootId) {
750         return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
751                 .authority(authority).appendPath(PATH_ROOT).appendPath(rootId).build();
752     }
753 
754     /**
755      * Builds URI for user home directory on external (local) storage.
756      * {@hide}
757      */
buildHomeUri()758     public static Uri buildHomeUri() {
759         // TODO: Avoid this type of interpackage copying. Added here to avoid
760         // direct coupling, but not ideal.
761         return DocumentsContract.buildRootUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, "home");
762     }
763 
764     /**
765      * Build URI representing the recently modified documents of a specific root
766      * in a document provider. When queried, a provider will return zero or more
767      * rows with columns defined by {@link Document}.
768      *
769      * @see DocumentsProvider#queryRecentDocuments(String, String[])
770      * @see #getRootId(Uri)
771      */
buildRecentDocumentsUri(String authority, String rootId)772     public static Uri buildRecentDocumentsUri(String authority, String rootId) {
773         return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
774                 .authority(authority).appendPath(PATH_ROOT).appendPath(rootId)
775                 .appendPath(PATH_RECENT).build();
776     }
777 
778     /**
779      * Build URI representing access to descendant documents of the given
780      * {@link Document#COLUMN_DOCUMENT_ID}.
781      *
782      * @see #getTreeDocumentId(Uri)
783      */
buildTreeDocumentUri(String authority, String documentId)784     public static Uri buildTreeDocumentUri(String authority, String documentId) {
785         return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
786                 .appendPath(PATH_TREE).appendPath(documentId).build();
787     }
788 
789     /**
790      * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in
791      * a document provider. When queried, a provider will return a single row
792      * with columns defined by {@link Document}.
793      *
794      * @see DocumentsProvider#queryDocument(String, String[])
795      * @see #getDocumentId(Uri)
796      */
buildDocumentUri(String authority, String documentId)797     public static Uri buildDocumentUri(String authority, String documentId) {
798         return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
799                 .authority(authority).appendPath(PATH_DOCUMENT).appendPath(documentId).build();
800     }
801 
802     /**
803      * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in
804      * a document provider. When queried, a provider will return a single row
805      * with columns defined by {@link Document}.
806      * <p>
807      * However, instead of directly accessing the target document, the returned
808      * URI will leverage access granted through a subtree URI, typically
809      * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target document
810      * must be a descendant (child, grandchild, etc) of the subtree.
811      * <p>
812      * This is typically used to access documents under a user-selected
813      * directory tree, since it doesn't require the user to separately confirm
814      * each new document access.
815      *
816      * @param treeUri the subtree to leverage to gain access to the target
817      *            document. The target directory must be a descendant of this
818      *            subtree.
819      * @param documentId the target document, which the caller may not have
820      *            direct access to.
821      * @see Intent#ACTION_OPEN_DOCUMENT_TREE
822      * @see DocumentsProvider#isChildDocument(String, String)
823      * @see #buildDocumentUri(String, String)
824      */
buildDocumentUriUsingTree(Uri treeUri, String documentId)825     public static Uri buildDocumentUriUsingTree(Uri treeUri, String documentId) {
826         return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
827                 .authority(treeUri.getAuthority()).appendPath(PATH_TREE)
828                 .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT)
829                 .appendPath(documentId).build();
830     }
831 
832     /** {@hide} */
buildDocumentUriMaybeUsingTree(Uri baseUri, String documentId)833     public static Uri buildDocumentUriMaybeUsingTree(Uri baseUri, String documentId) {
834         if (isTreeUri(baseUri)) {
835             return buildDocumentUriUsingTree(baseUri, documentId);
836         } else {
837             return buildDocumentUri(baseUri.getAuthority(), documentId);
838         }
839     }
840 
841     /**
842      * Build URI representing the children of the target directory in a document
843      * provider. When queried, a provider will return zero or more rows with
844      * columns defined by {@link Document}.
845      *
846      * @param parentDocumentId the document to return children for, which must
847      *            be a directory with MIME type of
848      *            {@link Document#MIME_TYPE_DIR}.
849      * @see DocumentsProvider#queryChildDocuments(String, String[], String)
850      * @see #getDocumentId(Uri)
851      */
buildChildDocumentsUri(String authority, String parentDocumentId)852     public static Uri buildChildDocumentsUri(String authority, String parentDocumentId) {
853         return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
854                 .appendPath(PATH_DOCUMENT).appendPath(parentDocumentId).appendPath(PATH_CHILDREN)
855                 .build();
856     }
857 
858     /**
859      * Build URI representing the children of the target directory in a document
860      * provider. When queried, a provider will return zero or more rows with
861      * columns defined by {@link Document}.
862      * <p>
863      * However, instead of directly accessing the target directory, the returned
864      * URI will leverage access granted through a subtree URI, typically
865      * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target
866      * directory must be a descendant (child, grandchild, etc) of the subtree.
867      * <p>
868      * This is typically used to access documents under a user-selected
869      * directory tree, since it doesn't require the user to separately confirm
870      * each new document access.
871      *
872      * @param treeUri the subtree to leverage to gain access to the target
873      *            document. The target directory must be a descendant of this
874      *            subtree.
875      * @param parentDocumentId the document to return children for, which the
876      *            caller may not have direct access to, and which must be a
877      *            directory with MIME type of {@link Document#MIME_TYPE_DIR}.
878      * @see Intent#ACTION_OPEN_DOCUMENT_TREE
879      * @see DocumentsProvider#isChildDocument(String, String)
880      * @see #buildChildDocumentsUri(String, String)
881      */
buildChildDocumentsUriUsingTree(Uri treeUri, String parentDocumentId)882     public static Uri buildChildDocumentsUriUsingTree(Uri treeUri, String parentDocumentId) {
883         return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
884                 .authority(treeUri.getAuthority()).appendPath(PATH_TREE)
885                 .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT)
886                 .appendPath(parentDocumentId).appendPath(PATH_CHILDREN).build();
887     }
888 
889     /**
890      * Build URI representing a search for matching documents under a specific
891      * root in a document provider. When queried, a provider will return zero or
892      * more rows with columns defined by {@link Document}.
893      *
894      * @see DocumentsProvider#querySearchDocuments(String, String, String[])
895      * @see #getRootId(Uri)
896      * @see #getSearchDocumentsQuery(Uri)
897      */
buildSearchDocumentsUri( String authority, String rootId, String query)898     public static Uri buildSearchDocumentsUri(
899             String authority, String rootId, String query) {
900         return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
901                 .appendPath(PATH_ROOT).appendPath(rootId).appendPath(PATH_SEARCH)
902                 .appendQueryParameter(PARAM_QUERY, query).build();
903     }
904 
905     /**
906      * Test if the given URI represents a {@link Document} backed by a
907      * {@link DocumentsProvider}.
908      *
909      * @see #buildDocumentUri(String, String)
910      * @see #buildDocumentUriUsingTree(Uri, String)
911      */
isDocumentUri(Context context, @Nullable Uri uri)912     public static boolean isDocumentUri(Context context, @Nullable Uri uri) {
913         if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) {
914             final List<String> paths = uri.getPathSegments();
915             if (paths.size() == 2) {
916                 return PATH_DOCUMENT.equals(paths.get(0));
917             } else if (paths.size() == 4) {
918                 return PATH_TREE.equals(paths.get(0)) && PATH_DOCUMENT.equals(paths.get(2));
919             }
920         }
921         return false;
922     }
923 
924     /** {@hide} */
isRootUri(Context context, @Nullable Uri uri)925     public static boolean isRootUri(Context context, @Nullable Uri uri) {
926         if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) {
927             final List<String> paths = uri.getPathSegments();
928             return (paths.size() == 2 && PATH_ROOT.equals(paths.get(0)));
929         }
930         return false;
931     }
932 
933     /** {@hide} */
isContentUri(@ullable Uri uri)934     public static boolean isContentUri(@Nullable Uri uri) {
935         return uri != null && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme());
936     }
937 
938     /**
939      * Test if the given URI represents a {@link Document} tree.
940      *
941      * @see #buildTreeDocumentUri(String, String)
942      * @see #getTreeDocumentId(Uri)
943      */
isTreeUri(Uri uri)944     public static boolean isTreeUri(Uri uri) {
945         final List<String> paths = uri.getPathSegments();
946         return (paths.size() >= 2 && PATH_TREE.equals(paths.get(0)));
947     }
948 
isDocumentsProvider(Context context, String authority)949     private static boolean isDocumentsProvider(Context context, String authority) {
950         final Intent intent = new Intent(PROVIDER_INTERFACE);
951         final List<ResolveInfo> infos = context.getPackageManager()
952                 .queryIntentContentProviders(intent, 0);
953         for (ResolveInfo info : infos) {
954             if (authority.equals(info.providerInfo.authority)) {
955                 return true;
956             }
957         }
958         return false;
959     }
960 
961     /**
962      * Extract the {@link Root#COLUMN_ROOT_ID} from the given URI.
963      */
getRootId(Uri rootUri)964     public static String getRootId(Uri rootUri) {
965         final List<String> paths = rootUri.getPathSegments();
966         if (paths.size() >= 2 && PATH_ROOT.equals(paths.get(0))) {
967             return paths.get(1);
968         }
969         throw new IllegalArgumentException("Invalid URI: " + rootUri);
970     }
971 
972     /**
973      * Extract the {@link Document#COLUMN_DOCUMENT_ID} from the given URI.
974      *
975      * @see #isDocumentUri(Context, Uri)
976      */
getDocumentId(Uri documentUri)977     public static String getDocumentId(Uri documentUri) {
978         final List<String> paths = documentUri.getPathSegments();
979         if (paths.size() >= 2 && PATH_DOCUMENT.equals(paths.get(0))) {
980             return paths.get(1);
981         }
982         if (paths.size() >= 4 && PATH_TREE.equals(paths.get(0))
983                 && PATH_DOCUMENT.equals(paths.get(2))) {
984             return paths.get(3);
985         }
986         throw new IllegalArgumentException("Invalid URI: " + documentUri);
987     }
988 
989     /**
990      * Extract the via {@link Document#COLUMN_DOCUMENT_ID} from the given URI.
991      */
getTreeDocumentId(Uri documentUri)992     public static String getTreeDocumentId(Uri documentUri) {
993         final List<String> paths = documentUri.getPathSegments();
994         if (paths.size() >= 2 && PATH_TREE.equals(paths.get(0))) {
995             return paths.get(1);
996         }
997         throw new IllegalArgumentException("Invalid URI: " + documentUri);
998     }
999 
1000     /**
1001      * Extract the search query from a URI built by
1002      * {@link #buildSearchDocumentsUri(String, String, String)}.
1003      */
getSearchDocumentsQuery(Uri searchDocumentsUri)1004     public static String getSearchDocumentsQuery(Uri searchDocumentsUri) {
1005         return searchDocumentsUri.getQueryParameter(PARAM_QUERY);
1006     }
1007 
1008     /** {@hide} */
setManageMode(Uri uri)1009     public static Uri setManageMode(Uri uri) {
1010         return uri.buildUpon().appendQueryParameter(PARAM_MANAGE, "true").build();
1011     }
1012 
1013     /** {@hide} */
isManageMode(Uri uri)1014     public static boolean isManageMode(Uri uri) {
1015         return uri.getBooleanQueryParameter(PARAM_MANAGE, false);
1016     }
1017 
1018     /**
1019      * Return thumbnail representing the document at the given URI. Callers are
1020      * responsible for their own in-memory caching.
1021      *
1022      * @param documentUri document to return thumbnail for, which must have
1023      *            {@link Document#FLAG_SUPPORTS_THUMBNAIL} set.
1024      * @param size optimal thumbnail size desired. A provider may return a
1025      *            thumbnail of a different size, but never more than double the
1026      *            requested size.
1027      * @param signal signal used to indicate if caller is no longer interested
1028      *            in the thumbnail.
1029      * @return decoded thumbnail, or {@code null} if problem was encountered.
1030      * @see DocumentsProvider#openDocumentThumbnail(String, Point,
1031      *      android.os.CancellationSignal)
1032      */
getDocumentThumbnail( ContentResolver resolver, Uri documentUri, Point size, CancellationSignal signal)1033     public static Bitmap getDocumentThumbnail(
1034             ContentResolver resolver, Uri documentUri, Point size, CancellationSignal signal)
1035             throws FileNotFoundException {
1036         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1037                 documentUri.getAuthority());
1038         try {
1039             return getDocumentThumbnail(client, documentUri, size, signal);
1040         } catch (Exception e) {
1041             if (!(e instanceof OperationCanceledException)) {
1042                 Log.w(TAG, "Failed to load thumbnail for " + documentUri + ": " + e);
1043             }
1044             rethrowIfNecessary(resolver, e);
1045             return null;
1046         } finally {
1047             ContentProviderClient.releaseQuietly(client);
1048         }
1049     }
1050 
1051     /** {@hide} */
getDocumentThumbnail( ContentProviderClient client, Uri documentUri, Point size, CancellationSignal signal)1052     public static Bitmap getDocumentThumbnail(
1053             ContentProviderClient client, Uri documentUri, Point size, CancellationSignal signal)
1054             throws RemoteException, IOException {
1055         final Bundle openOpts = new Bundle();
1056         openOpts.putParcelable(ContentResolver.EXTRA_SIZE, size);
1057 
1058         AssetFileDescriptor afd = null;
1059         Bitmap bitmap = null;
1060         try {
1061             afd = client.openTypedAssetFileDescriptor(documentUri, "image/*", openOpts, signal);
1062 
1063             final FileDescriptor fd = afd.getFileDescriptor();
1064             final long offset = afd.getStartOffset();
1065 
1066             // Try seeking on the returned FD, since it gives us the most
1067             // optimal decode path; otherwise fall back to buffering.
1068             BufferedInputStream is = null;
1069             try {
1070                 Os.lseek(fd, offset, SEEK_SET);
1071             } catch (ErrnoException e) {
1072                 is = new BufferedInputStream(new FileInputStream(fd), THUMBNAIL_BUFFER_SIZE);
1073                 is.mark(THUMBNAIL_BUFFER_SIZE);
1074             }
1075 
1076             // We requested a rough thumbnail size, but the remote size may have
1077             // returned something giant, so defensively scale down as needed.
1078             final BitmapFactory.Options opts = new BitmapFactory.Options();
1079             opts.inJustDecodeBounds = true;
1080             if (is != null) {
1081                 BitmapFactory.decodeStream(is, null, opts);
1082             } else {
1083                 BitmapFactory.decodeFileDescriptor(fd, null, opts);
1084             }
1085 
1086             final int widthSample = opts.outWidth / size.x;
1087             final int heightSample = opts.outHeight / size.y;
1088 
1089             opts.inJustDecodeBounds = false;
1090             opts.inSampleSize = Math.min(widthSample, heightSample);
1091             if (is != null) {
1092                 is.reset();
1093                 bitmap = BitmapFactory.decodeStream(is, null, opts);
1094             } else {
1095                 try {
1096                     Os.lseek(fd, offset, SEEK_SET);
1097                 } catch (ErrnoException e) {
1098                     e.rethrowAsIOException();
1099                 }
1100                 bitmap = BitmapFactory.decodeFileDescriptor(fd, null, opts);
1101             }
1102 
1103             // Transform the bitmap if requested. We use a side-channel to
1104             // communicate the orientation, since EXIF thumbnails don't contain
1105             // the rotation flags of the original image.
1106             final Bundle extras = afd.getExtras();
1107             final int orientation = (extras != null) ? extras.getInt(EXTRA_ORIENTATION, 0) : 0;
1108             if (orientation != 0) {
1109                 final int width = bitmap.getWidth();
1110                 final int height = bitmap.getHeight();
1111 
1112                 final Matrix m = new Matrix();
1113                 m.setRotate(orientation, width / 2, height / 2);
1114                 bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, false);
1115             }
1116         } finally {
1117             IoUtils.closeQuietly(afd);
1118         }
1119 
1120         return bitmap;
1121     }
1122 
1123     /**
1124      * Create a new document with given MIME type and display name.
1125      *
1126      * @param parentDocumentUri directory with {@link Document#FLAG_DIR_SUPPORTS_CREATE}
1127      * @param mimeType MIME type of new document
1128      * @param displayName name of new document
1129      * @return newly created document, or {@code null} if failed
1130      */
createDocument(ContentResolver resolver, Uri parentDocumentUri, String mimeType, String displayName)1131     public static Uri createDocument(ContentResolver resolver, Uri parentDocumentUri,
1132             String mimeType, String displayName) throws FileNotFoundException {
1133         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1134                 parentDocumentUri.getAuthority());
1135         try {
1136             return createDocument(client, parentDocumentUri, mimeType, displayName);
1137         } catch (Exception e) {
1138             Log.w(TAG, "Failed to create document", e);
1139             rethrowIfNecessary(resolver, e);
1140             return null;
1141         } finally {
1142             ContentProviderClient.releaseQuietly(client);
1143         }
1144     }
1145 
1146     /** {@hide} */
createDocument(ContentProviderClient client, Uri parentDocumentUri, String mimeType, String displayName)1147     public static Uri createDocument(ContentProviderClient client, Uri parentDocumentUri,
1148             String mimeType, String displayName) throws RemoteException {
1149         final Bundle in = new Bundle();
1150         in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri);
1151         in.putString(Document.COLUMN_MIME_TYPE, mimeType);
1152         in.putString(Document.COLUMN_DISPLAY_NAME, displayName);
1153 
1154         final Bundle out = client.call(METHOD_CREATE_DOCUMENT, null, in);
1155         return out.getParcelable(DocumentsContract.EXTRA_URI);
1156     }
1157 
1158     /** {@hide} */
isChildDocument(ContentProviderClient client, Uri parentDocumentUri, Uri childDocumentUri)1159     public static boolean isChildDocument(ContentProviderClient client, Uri parentDocumentUri,
1160             Uri childDocumentUri) throws RemoteException {
1161 
1162         final Bundle in = new Bundle();
1163         in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri);
1164         in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, childDocumentUri);
1165 
1166         final Bundle out = client.call(METHOD_IS_CHILD_DOCUMENT, null, in);
1167         if (out == null) {
1168             throw new RemoteException("Failed to get a reponse from isChildDocument query.");
1169         }
1170         if (!out.containsKey(DocumentsContract.EXTRA_RESULT)) {
1171             throw new RemoteException("Response did not include result field..");
1172         }
1173         return out.getBoolean(DocumentsContract.EXTRA_RESULT);
1174     }
1175 
1176     /**
1177      * Change the display name of an existing document.
1178      * <p>
1179      * If the underlying provider needs to create a new
1180      * {@link Document#COLUMN_DOCUMENT_ID} to represent the updated display
1181      * name, that new document is returned and the original document is no
1182      * longer valid. Otherwise, the original document is returned.
1183      *
1184      * @param documentUri document with {@link Document#FLAG_SUPPORTS_RENAME}
1185      * @param displayName updated name for document
1186      * @return the existing or new document after the rename, or {@code null} if
1187      *         failed.
1188      */
renameDocument(ContentResolver resolver, Uri documentUri, String displayName)1189     public static Uri renameDocument(ContentResolver resolver, Uri documentUri,
1190             String displayName) throws FileNotFoundException {
1191         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1192                 documentUri.getAuthority());
1193         try {
1194             return renameDocument(client, documentUri, displayName);
1195         } catch (Exception e) {
1196             Log.w(TAG, "Failed to rename document", e);
1197             rethrowIfNecessary(resolver, e);
1198             return null;
1199         } finally {
1200             ContentProviderClient.releaseQuietly(client);
1201         }
1202     }
1203 
1204     /** {@hide} */
renameDocument(ContentProviderClient client, Uri documentUri, String displayName)1205     public static Uri renameDocument(ContentProviderClient client, Uri documentUri,
1206             String displayName) throws RemoteException {
1207         final Bundle in = new Bundle();
1208         in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
1209         in.putString(Document.COLUMN_DISPLAY_NAME, displayName);
1210 
1211         final Bundle out = client.call(METHOD_RENAME_DOCUMENT, null, in);
1212         final Uri outUri = out.getParcelable(DocumentsContract.EXTRA_URI);
1213         return (outUri != null) ? outUri : documentUri;
1214     }
1215 
1216     /**
1217      * Delete the given document.
1218      *
1219      * @param documentUri document with {@link Document#FLAG_SUPPORTS_DELETE}
1220      * @return if the document was deleted successfully.
1221      */
deleteDocument(ContentResolver resolver, Uri documentUri)1222     public static boolean deleteDocument(ContentResolver resolver, Uri documentUri)
1223             throws FileNotFoundException {
1224         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1225                 documentUri.getAuthority());
1226         try {
1227             deleteDocument(client, documentUri);
1228             return true;
1229         } catch (Exception e) {
1230             Log.w(TAG, "Failed to delete document", e);
1231             rethrowIfNecessary(resolver, e);
1232             return false;
1233         } finally {
1234             ContentProviderClient.releaseQuietly(client);
1235         }
1236     }
1237 
1238     /** {@hide} */
deleteDocument(ContentProviderClient client, Uri documentUri)1239     public static void deleteDocument(ContentProviderClient client, Uri documentUri)
1240             throws RemoteException {
1241         final Bundle in = new Bundle();
1242         in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
1243 
1244         client.call(METHOD_DELETE_DOCUMENT, null, in);
1245     }
1246 
1247     /**
1248      * Copies the given document.
1249      *
1250      * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_COPY}
1251      * @param targetParentDocumentUri document which will become a parent of the source
1252      *         document's copy.
1253      * @return the copied document, or {@code null} if failed.
1254      */
copyDocument(ContentResolver resolver, Uri sourceDocumentUri, Uri targetParentDocumentUri)1255     public static Uri copyDocument(ContentResolver resolver, Uri sourceDocumentUri,
1256             Uri targetParentDocumentUri) throws FileNotFoundException {
1257         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1258                 sourceDocumentUri.getAuthority());
1259         try {
1260             return copyDocument(client, sourceDocumentUri, targetParentDocumentUri);
1261         } catch (Exception e) {
1262             Log.w(TAG, "Failed to copy document", e);
1263             rethrowIfNecessary(resolver, e);
1264             return null;
1265         } finally {
1266             ContentProviderClient.releaseQuietly(client);
1267         }
1268     }
1269 
1270     /** {@hide} */
copyDocument(ContentProviderClient client, Uri sourceDocumentUri, Uri targetParentDocumentUri)1271     public static Uri copyDocument(ContentProviderClient client, Uri sourceDocumentUri,
1272             Uri targetParentDocumentUri) throws RemoteException {
1273         final Bundle in = new Bundle();
1274         in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri);
1275         in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri);
1276 
1277         final Bundle out = client.call(METHOD_COPY_DOCUMENT, null, in);
1278         return out.getParcelable(DocumentsContract.EXTRA_URI);
1279     }
1280 
1281     /**
1282      * Moves the given document under a new parent.
1283      *
1284      * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_MOVE}
1285      * @param sourceParentDocumentUri parent document of the document to move.
1286      * @param targetParentDocumentUri document which will become a new parent of the source
1287      *         document.
1288      * @return the moved document, or {@code null} if failed.
1289      */
moveDocument(ContentResolver resolver, Uri sourceDocumentUri, Uri sourceParentDocumentUri, Uri targetParentDocumentUri)1290     public static Uri moveDocument(ContentResolver resolver, Uri sourceDocumentUri,
1291             Uri sourceParentDocumentUri, Uri targetParentDocumentUri) throws FileNotFoundException {
1292         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1293                 sourceDocumentUri.getAuthority());
1294         try {
1295             return moveDocument(client, sourceDocumentUri, sourceParentDocumentUri,
1296                     targetParentDocumentUri);
1297         } catch (Exception e) {
1298             Log.w(TAG, "Failed to move document", e);
1299             rethrowIfNecessary(resolver, e);
1300             return null;
1301         } finally {
1302             ContentProviderClient.releaseQuietly(client);
1303         }
1304     }
1305 
1306     /** {@hide} */
moveDocument(ContentProviderClient client, Uri sourceDocumentUri, Uri sourceParentDocumentUri, Uri targetParentDocumentUri)1307     public static Uri moveDocument(ContentProviderClient client, Uri sourceDocumentUri,
1308             Uri sourceParentDocumentUri, Uri targetParentDocumentUri) throws RemoteException {
1309         final Bundle in = new Bundle();
1310         in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri);
1311         in.putParcelable(DocumentsContract.EXTRA_PARENT_URI, sourceParentDocumentUri);
1312         in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri);
1313 
1314         final Bundle out = client.call(METHOD_MOVE_DOCUMENT, null, in);
1315         return out.getParcelable(DocumentsContract.EXTRA_URI);
1316     }
1317 
1318     /**
1319      * Removes the given document from a parent directory.
1320      *
1321      * <p>In contrast to {@link #deleteDocument} it requires specifying the parent.
1322      * This method is especially useful if the document can be in multiple parents.
1323      *
1324      * @param documentUri document with {@link Document#FLAG_SUPPORTS_REMOVE}
1325      * @param parentDocumentUri parent document of the document to remove.
1326      * @return true if the document was removed successfully.
1327      */
removeDocument(ContentResolver resolver, Uri documentUri, Uri parentDocumentUri)1328     public static boolean removeDocument(ContentResolver resolver, Uri documentUri,
1329             Uri parentDocumentUri) throws FileNotFoundException {
1330         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1331                 documentUri.getAuthority());
1332         try {
1333             removeDocument(client, documentUri, parentDocumentUri);
1334             return true;
1335         } catch (Exception e) {
1336             Log.w(TAG, "Failed to remove document", e);
1337             rethrowIfNecessary(resolver, e);
1338             return false;
1339         } finally {
1340             ContentProviderClient.releaseQuietly(client);
1341         }
1342     }
1343 
1344     /** {@hide} */
removeDocument(ContentProviderClient client, Uri documentUri, Uri parentDocumentUri)1345     public static void removeDocument(ContentProviderClient client, Uri documentUri,
1346             Uri parentDocumentUri) throws RemoteException {
1347         final Bundle in = new Bundle();
1348         in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
1349         in.putParcelable(DocumentsContract.EXTRA_PARENT_URI, parentDocumentUri);
1350 
1351         client.call(METHOD_REMOVE_DOCUMENT, null, in);
1352     }
1353 
1354     /**
1355      * Ejects the given root. It throws {@link IllegalStateException} when ejection failed.
1356      *
1357      * @param rootUri root with {@link Root#FLAG_SUPPORTS_EJECT} to be ejected
1358      */
ejectRoot(ContentResolver resolver, Uri rootUri)1359     public static void ejectRoot(ContentResolver resolver, Uri rootUri) {
1360         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1361                 rootUri.getAuthority());
1362         try {
1363             ejectRoot(client, rootUri);
1364         } catch (RemoteException e) {
1365             e.rethrowAsRuntimeException();
1366         } finally {
1367             ContentProviderClient.releaseQuietly(client);
1368         }
1369     }
1370 
1371     /** {@hide} */
ejectRoot(ContentProviderClient client, Uri rootUri)1372     public static void ejectRoot(ContentProviderClient client, Uri rootUri)
1373             throws RemoteException {
1374         final Bundle in = new Bundle();
1375         in.putParcelable(DocumentsContract.EXTRA_URI, rootUri);
1376 
1377         client.call(METHOD_EJECT_ROOT, null, in);
1378     }
1379 
1380     /**
1381      * Finds the canonical path from the top of the document tree.
1382      *
1383      * The {@link Path#getPath()} of the return value contains the document ID
1384      * of all documents along the path from the top the document tree to the
1385      * requested document, both inclusive.
1386      *
1387      * The {@link Path#getRootId()} of the return value returns {@code null}.
1388      *
1389      * @param treeUri treeUri of the document which path is requested.
1390      * @return the path of the document, or {@code null} if failed.
1391      * @see DocumentsProvider#findDocumentPath(String, String)
1392      */
findDocumentPath(ContentResolver resolver, Uri treeUri)1393     public static Path findDocumentPath(ContentResolver resolver, Uri treeUri)
1394             throws FileNotFoundException {
1395         checkArgument(isTreeUri(treeUri), treeUri + " is not a tree uri.");
1396 
1397         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1398                 treeUri.getAuthority());
1399         try {
1400             return findDocumentPath(client, treeUri);
1401         } catch (Exception e) {
1402             Log.w(TAG, "Failed to find path", e);
1403             rethrowIfNecessary(resolver, e);
1404             return null;
1405         } finally {
1406             ContentProviderClient.releaseQuietly(client);
1407         }
1408     }
1409 
1410     /**
1411      * Finds the canonical path. If uri is a document uri returns path from a root and
1412      * its associated root id. If uri is a tree uri returns the path from the top of
1413      * the tree. The {@link Path#getPath()} of the return value contains document ID
1414      * starts from the top of the tree or the root document to the requested document,
1415      * both inclusive.
1416      *
1417      * Callers can expect the root ID returned from multiple calls to this method is
1418      * consistent.
1419      *
1420      * @param uri uri of the document which path is requested. It can be either a
1421      *          plain document uri or a tree uri.
1422      * @return the path of the document.
1423      * @see DocumentsProvider#findDocumentPath(String, String)
1424      *
1425      * {@hide}
1426      */
findDocumentPath(ContentProviderClient client, Uri uri)1427     public static Path findDocumentPath(ContentProviderClient client, Uri uri)
1428             throws RemoteException {
1429 
1430         final Bundle in = new Bundle();
1431         in.putParcelable(DocumentsContract.EXTRA_URI, uri);
1432 
1433         final Bundle out = client.call(METHOD_FIND_DOCUMENT_PATH, null, in);
1434 
1435         return out.getParcelable(DocumentsContract.EXTRA_RESULT);
1436     }
1437 
1438     /**
1439      * Creates an intent for obtaining a web link for the specified document.
1440      *
1441      * <p>Note, that due to internal limitations, if there is already a web link
1442      * intent created for the specified document but with different options,
1443      * then it may be overriden.
1444      *
1445      * <p>Providers are required to show confirmation UI for all new permissions granted
1446      * for the linked document.
1447      *
1448      * <p>If list of recipients is known, then it should be passed in options as
1449      * {@link Intent#EXTRA_EMAIL} as a list of email addresses. Note, that
1450      * this is just a hint for the provider, which can ignore the list. In either
1451      * case the provider is required to show a UI for letting the user confirm
1452      * any new permission grants.
1453      *
1454      * <p>Note, that the entire <code>options</code> bundle will be sent to the provider
1455      * backing the passed <code>uri</code>. Make sure that you trust the provider
1456      * before passing any sensitive information.
1457      *
1458      * <p>Since this API may show a UI, it cannot be called from background.
1459      *
1460      * <p>In order to obtain the Web Link use code like this:
1461      * <pre><code>
1462      * void onSomethingHappened() {
1463      *   IntentSender sender = DocumentsContract.createWebLinkIntent(<i>...</i>);
1464      *   if (sender != null) {
1465      *     startIntentSenderForResult(
1466      *         sender,
1467      *         WEB_LINK_REQUEST_CODE,
1468      *         null, 0, 0, 0, null);
1469      *   }
1470      * }
1471      *
1472      * <i>(...)</i>
1473      *
1474      * void onActivityResult(int requestCode, int resultCode, Intent data) {
1475      *   if (requestCode == WEB_LINK_REQUEST_CODE && resultCode == RESULT_OK) {
1476      *     Uri weblinkUri = data.getData();
1477      *     <i>...</i>
1478      *   }
1479      * }
1480      * </code></pre>
1481      *
1482      * @param uri uri for the document to create a link to.
1483      * @param options Extra information for generating the link.
1484      * @return an intent sender to obtain the web link, or null if the document
1485      *      is not linkable, or creating the intent sender failed.
1486      * @see DocumentsProvider#createWebLinkIntent(String, Bundle)
1487      * @see Intent#EXTRA_EMAIL
1488      */
createWebLinkIntent(ContentResolver resolver, Uri uri, Bundle options)1489     public static IntentSender createWebLinkIntent(ContentResolver resolver, Uri uri,
1490             Bundle options) throws FileNotFoundException {
1491         final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1492                 uri.getAuthority());
1493         try {
1494             return createWebLinkIntent(client, uri, options);
1495         } catch (Exception e) {
1496             Log.w(TAG, "Failed to create a web link intent", e);
1497             rethrowIfNecessary(resolver, e);
1498             return null;
1499         } finally {
1500             ContentProviderClient.releaseQuietly(client);
1501         }
1502     }
1503 
1504     /**
1505      * {@hide}
1506      */
createWebLinkIntent(ContentProviderClient client, Uri uri, Bundle options)1507     public static IntentSender createWebLinkIntent(ContentProviderClient client, Uri uri,
1508             Bundle options) throws RemoteException {
1509         final Bundle in = new Bundle();
1510         in.putParcelable(DocumentsContract.EXTRA_URI, uri);
1511 
1512         // Options may be provider specific, so put them in a separate bundle to
1513         // avoid overriding the Uri.
1514         if (options != null) {
1515             in.putBundle(EXTRA_OPTIONS, options);
1516         }
1517 
1518         final Bundle out = client.call(METHOD_CREATE_WEB_LINK_INTENT, null, in);
1519         return out.getParcelable(DocumentsContract.EXTRA_RESULT);
1520     }
1521 
1522     /**
1523      * Open the given image for thumbnail purposes, using any embedded EXIF
1524      * thumbnail if available, and providing orientation hints from the parent
1525      * image.
1526      *
1527      * @hide
1528      */
openImageThumbnail(File file)1529     public static AssetFileDescriptor openImageThumbnail(File file) throws FileNotFoundException {
1530         final ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
1531                 file, ParcelFileDescriptor.MODE_READ_ONLY);
1532         Bundle extras = null;
1533 
1534         try {
1535             final ExifInterface exif = new ExifInterface(file.getAbsolutePath());
1536 
1537             switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)) {
1538                 case ExifInterface.ORIENTATION_ROTATE_90:
1539                     extras = new Bundle(1);
1540                     extras.putInt(EXTRA_ORIENTATION, 90);
1541                     break;
1542                 case ExifInterface.ORIENTATION_ROTATE_180:
1543                     extras = new Bundle(1);
1544                     extras.putInt(EXTRA_ORIENTATION, 180);
1545                     break;
1546                 case ExifInterface.ORIENTATION_ROTATE_270:
1547                     extras = new Bundle(1);
1548                     extras.putInt(EXTRA_ORIENTATION, 270);
1549                     break;
1550             }
1551 
1552             final long[] thumb = exif.getThumbnailRange();
1553             if (thumb != null) {
1554                 return new AssetFileDescriptor(pfd, thumb[0], thumb[1], extras);
1555             }
1556         } catch (IOException e) {
1557         }
1558 
1559         return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH, extras);
1560     }
1561 
rethrowIfNecessary(ContentResolver resolver, Exception e)1562     private static void rethrowIfNecessary(ContentResolver resolver, Exception e)
1563             throws FileNotFoundException {
1564         // We only want to throw applications targetting O and above
1565         if (resolver.getTargetSdkVersion() >= Build.VERSION_CODES.O) {
1566             if (e instanceof ParcelableException) {
1567                 ((ParcelableException) e).maybeRethrow(FileNotFoundException.class);
1568             } else if (e instanceof RemoteException) {
1569                 ((RemoteException) e).rethrowAsRuntimeException();
1570             } else if (e instanceof RuntimeException) {
1571                 throw (RuntimeException) e;
1572             }
1573         }
1574     }
1575 
1576     /**
1577      * Holds a path from a document to a particular document under it. It
1578      * may also contains the root ID where the path resides.
1579      */
1580     public static final class Path implements Parcelable {
1581 
1582         private final @Nullable String mRootId;
1583         private final List<String> mPath;
1584 
1585         /**
1586          * Creates a Path.
1587          *
1588          * @param rootId the ID of the root. May be null.
1589          * @param path the list of document ID from the parent document at
1590          *          position 0 to the child document.
1591          */
Path(@ullable String rootId, List<String> path)1592         public Path(@Nullable String rootId, List<String> path) {
1593             checkCollectionNotEmpty(path, "path");
1594             checkCollectionElementsNotNull(path, "path");
1595 
1596             mRootId = rootId;
1597             mPath = path;
1598         }
1599 
1600         /**
1601          * Returns the root id or null if the calling package doesn't have
1602          * permission to access root information.
1603          */
getRootId()1604         public @Nullable String getRootId() {
1605             return mRootId;
1606         }
1607 
1608         /**
1609          * Returns the path. The path is trimmed to the top of tree if
1610          * calling package doesn't have permission to access those
1611          * documents.
1612          */
getPath()1613         public List<String> getPath() {
1614             return mPath;
1615         }
1616 
1617         @Override
equals(Object o)1618         public boolean equals(Object o) {
1619             if (this == o) {
1620                 return true;
1621             }
1622             if (o == null || !(o instanceof Path)) {
1623                 return false;
1624             }
1625             Path path = (Path) o;
1626             return Objects.equals(mRootId, path.mRootId) &&
1627                     Objects.equals(mPath, path.mPath);
1628         }
1629 
1630         @Override
hashCode()1631         public int hashCode() {
1632             return Objects.hash(mRootId, mPath);
1633         }
1634 
1635         @Override
toString()1636         public String toString() {
1637             return new StringBuilder()
1638                     .append("DocumentsContract.Path{")
1639                     .append("rootId=")
1640                     .append(mRootId)
1641                     .append(", path=")
1642                     .append(mPath)
1643                     .append("}")
1644                     .toString();
1645         }
1646 
1647         @Override
writeToParcel(Parcel dest, int flags)1648         public void writeToParcel(Parcel dest, int flags) {
1649             dest.writeString(mRootId);
1650             dest.writeStringList(mPath);
1651         }
1652 
1653         @Override
describeContents()1654         public int describeContents() {
1655             return 0;
1656         }
1657 
1658         public static final Creator<Path> CREATOR = new Creator<Path>() {
1659             @Override
1660             public Path createFromParcel(Parcel in) {
1661                 final String rootId = in.readString();
1662                 final List<String> path = in.createStringArrayList();
1663                 return new Path(rootId, path);
1664             }
1665 
1666             @Override
1667             public Path[] newArray(int size) {
1668                 return new Path[size];
1669             }
1670         };
1671     }
1672 }
1673