DocumentsProvider.java revision 75395651c272b3df746e0e5fede0a8fedd81e44b
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"><manifest> 68 * ... 69 * <application> 70 * ... 71 * <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"> 78 * <intent-filter> 79 * <action android:name="android.content.action.DOCUMENTS_PROVIDER" /> 80 * </intent-filter> 81 * </provider> 82 * ... 83 * </application> 84 *</manifest></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 */ 521 @SuppressWarnings("unused") 522 public AssetFileDescriptor openTypedDocument( 523 String documentId, String mimeTypeFilter, Bundle opts, CancellationSignal signal) 524 throws FileNotFoundException { 525 throw new FileNotFoundException("The requested MIME type is not supported."); 526 } 527 528 /** 529 * Implementation is provided by the parent class. Cannot be overriden. 530 * 531 * @see #queryRoots(String[]) 532 * @see #queryRecentDocuments(String, String[]) 533 * @see #queryDocument(String, String[]) 534 * @see #queryChildDocuments(String, String[], String) 535 * @see #querySearchDocuments(String, String, String[]) 536 */ 537 @Override 538 public final Cursor query(Uri uri, String[] projection, String selection, 539 String[] selectionArgs, String sortOrder) { 540 try { 541 switch (mMatcher.match(uri)) { 542 case MATCH_ROOTS: 543 return queryRoots(projection); 544 case MATCH_RECENT: 545 return queryRecentDocuments(getRootId(uri), projection); 546 case MATCH_SEARCH: 547 return querySearchDocuments( 548 getRootId(uri), getSearchDocumentsQuery(uri), projection); 549 case MATCH_DOCUMENT: 550 case MATCH_DOCUMENT_TREE: 551 enforceTree(uri); 552 return queryDocument(getDocumentId(uri), projection); 553 case MATCH_CHILDREN: 554 case MATCH_CHILDREN_TREE: 555 enforceTree(uri); 556 if (DocumentsContract.isManageMode(uri)) { 557 return queryChildDocumentsForManage( 558 getDocumentId(uri), projection, sortOrder); 559 } else { 560 return queryChildDocuments(getDocumentId(uri), projection, sortOrder); 561 } 562 default: 563 throw new UnsupportedOperationException("Unsupported Uri " + uri); 564 } 565 } catch (FileNotFoundException e) { 566 Log.w(TAG, "Failed during query", e); 567 return null; 568 } 569 } 570 571 /** 572 * Implementation is provided by the parent class. Cannot be overriden. 573 * 574 * @see #getDocumentType(String) 575 */ 576 @Override 577 public final String getType(Uri uri) { 578 try { 579 switch (mMatcher.match(uri)) { 580 case MATCH_ROOT: 581 return DocumentsContract.Root.MIME_TYPE_ITEM; 582 case MATCH_DOCUMENT: 583 case MATCH_DOCUMENT_TREE: 584 enforceTree(uri); 585 return getDocumentType(getDocumentId(uri)); 586 default: 587 return null; 588 } 589 } catch (FileNotFoundException e) { 590 Log.w(TAG, "Failed during getType", e); 591 return null; 592 } 593 } 594 595 /** 596 * Implementation is provided by the parent class. Can be overridden to 597 * provide additional functionality, but subclasses <em>must</em> always 598 * call the superclass. If the superclass returns {@code null}, the subclass 599 * may implement custom behavior. 600 * <p> 601 * This is typically used to resolve a subtree URI into a concrete document 602 * reference, issuing a narrower single-document URI permission grant along 603 * the way. 604 * 605 * @see DocumentsContract#buildDocumentUriUsingTree(Uri, String) 606 */ 607 @CallSuper 608 @Override 609 public Uri canonicalize(Uri uri) { 610 final Context context = getContext(); 611 switch (mMatcher.match(uri)) { 612 case MATCH_DOCUMENT_TREE: 613 enforceTree(uri); 614 615 final Uri narrowUri = buildDocumentUri(uri.getAuthority(), getDocumentId(uri)); 616 617 // Caller may only have prefix grant, so extend them a grant to 618 // the narrow URI. 619 final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context, uri); 620 context.grantUriPermission(getCallingPackage(), narrowUri, modeFlags); 621 return narrowUri; 622 } 623 return null; 624 } 625 626 private static int getCallingOrSelfUriPermissionModeFlags(Context context, Uri uri) { 627 // TODO: move this to a direct AMS call 628 int modeFlags = 0; 629 if (context.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) 630 == PackageManager.PERMISSION_GRANTED) { 631 modeFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION; 632 } 633 if (context.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION) 634 == PackageManager.PERMISSION_GRANTED) { 635 modeFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 636 } 637 if (context.checkCallingOrSelfUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION 638 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) 639 == PackageManager.PERMISSION_GRANTED) { 640 modeFlags |= Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 641 } 642 return modeFlags; 643 } 644 645 /** 646 * Implementation is provided by the parent class. Throws by default, and 647 * cannot be overriden. 648 * 649 * @see #createDocument(String, String, String) 650 */ 651 @Override 652 public final Uri insert(Uri uri, ContentValues values) { 653 throw new UnsupportedOperationException("Insert not supported"); 654 } 655 656 /** 657 * Implementation is provided by the parent class. Throws by default, and 658 * cannot be overriden. 659 * 660 * @see #deleteDocument(String) 661 */ 662 @Override 663 public final int delete(Uri uri, String selection, String[] selectionArgs) { 664 throw new UnsupportedOperationException("Delete not supported"); 665 } 666 667 /** 668 * Implementation is provided by the parent class. Throws by default, and 669 * cannot be overriden. 670 */ 671 @Override 672 public final int update( 673 Uri uri, ContentValues values, String selection, String[] selectionArgs) { 674 throw new UnsupportedOperationException("Update not supported"); 675 } 676 677 /** 678 * Implementation is provided by the parent class. Can be overridden to 679 * provide additional functionality, but subclasses <em>must</em> always 680 * call the superclass. If the superclass returns {@code null}, the subclass 681 * may implement custom behavior. 682 */ 683 @CallSuper 684 @Override 685 public Bundle call(String method, String arg, Bundle extras) { 686 if (!method.startsWith("android:")) { 687 // Ignore non-platform methods 688 return super.call(method, arg, extras); 689 } 690 691 try { 692 return callUnchecked(method, arg, extras); 693 } catch (FileNotFoundException e) { 694 throw new IllegalStateException("Failed call " + method, e); 695 } 696 } 697 698 private Bundle callUnchecked(String method, String arg, Bundle extras) 699 throws FileNotFoundException { 700 701 final Context context = getContext(); 702 final Uri documentUri = extras.getParcelable(DocumentsContract.EXTRA_URI); 703 final String authority = documentUri.getAuthority(); 704 final String documentId = DocumentsContract.getDocumentId(documentUri); 705 706 if (!mAuthority.equals(authority)) { 707 throw new SecurityException( 708 "Requested authority " + authority + " doesn't match provider " + mAuthority); 709 } 710 711 final Bundle out = new Bundle(); 712 713 // If the URI is a tree URI performs some validation. 714 enforceTree(documentUri); 715 716 if (METHOD_IS_CHILD_DOCUMENT.equals(method)) { 717 enforceReadPermissionInner(documentUri, getCallingPackage(), null); 718 719 final Uri childUri = extras.getParcelable(DocumentsContract.EXTRA_TARGET_URI); 720 final String childAuthority = childUri.getAuthority(); 721 final String childId = DocumentsContract.getDocumentId(childUri); 722 723 out.putBoolean( 724 DocumentsContract.EXTRA_RESULT, 725 mAuthority.equals(childAuthority) 726 && isChildDocument(documentId, childId)); 727 728 } else if (METHOD_CREATE_DOCUMENT.equals(method)) { 729 enforceWritePermissionInner(documentUri, getCallingPackage(), null); 730 731 final String mimeType = extras.getString(Document.COLUMN_MIME_TYPE); 732 final String displayName = extras.getString(Document.COLUMN_DISPLAY_NAME); 733 final String newDocumentId = createDocument(documentId, mimeType, displayName); 734 735 // No need to issue new grants here, since caller either has 736 // manage permission or a prefix grant. We might generate a 737 // tree style URI if that's how they called us. 738 final Uri newDocumentUri = buildDocumentUriMaybeUsingTree(documentUri, 739 newDocumentId); 740 out.putParcelable(DocumentsContract.EXTRA_URI, newDocumentUri); 741 742 } else if (METHOD_RENAME_DOCUMENT.equals(method)) { 743 enforceWritePermissionInner(documentUri, getCallingPackage(), null); 744 745 final String displayName = extras.getString(Document.COLUMN_DISPLAY_NAME); 746 final String newDocumentId = renameDocument(documentId, displayName); 747 748 if (newDocumentId != null) { 749 final Uri newDocumentUri = buildDocumentUriMaybeUsingTree(documentUri, 750 newDocumentId); 751 752 // If caller came in with a narrow grant, issue them a 753 // narrow grant for the newly renamed document. 754 if (!isTreeUri(newDocumentUri)) { 755 final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context, 756 documentUri); 757 context.grantUriPermission(getCallingPackage(), newDocumentUri, modeFlags); 758 } 759 760 out.putParcelable(DocumentsContract.EXTRA_URI, newDocumentUri); 761 762 // Original document no longer exists, clean up any grants 763 revokeDocumentPermission(documentId); 764 } 765 766 } else if (METHOD_DELETE_DOCUMENT.equals(method)) { 767 enforceWritePermissionInner(documentUri, getCallingPackage(), null); 768 deleteDocument(documentId); 769 770 // Document no longer exists, clean up any grants 771 revokeDocumentPermission(documentId); 772 773 } else if (METHOD_COPY_DOCUMENT.equals(method)) { 774 final Uri targetUri = extras.getParcelable(DocumentsContract.EXTRA_TARGET_URI); 775 final String targetId = DocumentsContract.getDocumentId(targetUri); 776 777 enforceReadPermissionInner(documentUri, getCallingPackage(), null); 778 enforceWritePermissionInner(targetUri, getCallingPackage(), null); 779 780 final String newDocumentId = copyDocument(documentId, targetId); 781 782 if (newDocumentId != null) { 783 final Uri newDocumentUri = buildDocumentUriMaybeUsingTree(documentUri, 784 newDocumentId); 785 786 if (!isTreeUri(newDocumentUri)) { 787 final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context, 788 documentUri); 789 context.grantUriPermission(getCallingPackage(), newDocumentUri, modeFlags); 790 } 791 792 out.putParcelable(DocumentsContract.EXTRA_URI, newDocumentUri); 793 } 794 795 } else if (METHOD_MOVE_DOCUMENT.equals(method)) { 796 final Uri targetUri = extras.getParcelable(DocumentsContract.EXTRA_TARGET_URI); 797 final String targetId = DocumentsContract.getDocumentId(targetUri); 798 799 enforceReadPermissionInner(documentUri, getCallingPackage(), null); 800 enforceWritePermissionInner(targetUri, getCallingPackage(), null); 801 802 final String newDocumentId = moveDocument(documentId, targetId); 803 804 if (newDocumentId != null) { 805 final Uri newDocumentUri = buildDocumentUriMaybeUsingTree(documentUri, 806 newDocumentId); 807 808 if (!isTreeUri(newDocumentUri)) { 809 final int modeFlags = getCallingOrSelfUriPermissionModeFlags(context, 810 documentUri); 811 context.grantUriPermission(getCallingPackage(), newDocumentUri, modeFlags); 812 } 813 814 out.putParcelable(DocumentsContract.EXTRA_URI, newDocumentUri); 815 } 816 817 // Original document no longer exists, clean up any grants 818 revokeDocumentPermission(documentId); 819 820 } else { 821 throw new UnsupportedOperationException("Method not supported " + method); 822 } 823 824 return out; 825 } 826 827 /** 828 * Revoke any active permission grants for the given 829 * {@link Document#COLUMN_DOCUMENT_ID}, usually called when a document 830 * becomes invalid. Follows the same semantics as 831 * {@link Context#revokeUriPermission(Uri, int)}. 832 */ 833 public final void revokeDocumentPermission(String documentId) { 834 final Context context = getContext(); 835 context.revokeUriPermission(buildDocumentUri(mAuthority, documentId), ~0); 836 context.revokeUriPermission(buildTreeDocumentUri(mAuthority, documentId), ~0); 837 } 838 839 /** 840 * Implementation is provided by the parent class. Cannot be overriden. 841 * 842 * @see #openDocument(String, String, CancellationSignal) 843 */ 844 @Override 845 public final ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { 846 enforceTree(uri); 847 return openDocument(getDocumentId(uri), mode, null); 848 } 849 850 /** 851 * Implementation is provided by the parent class. Cannot be overriden. 852 * 853 * @see #openDocument(String, String, CancellationSignal) 854 */ 855 @Override 856 public final ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal) 857 throws FileNotFoundException { 858 enforceTree(uri); 859 return openDocument(getDocumentId(uri), mode, signal); 860 } 861 862 /** 863 * Implementation is provided by the parent class. Cannot be overriden. 864 * 865 * @see #openDocument(String, String, CancellationSignal) 866 */ 867 @Override 868 @SuppressWarnings("resource") 869 public final AssetFileDescriptor openAssetFile(Uri uri, String mode) 870 throws FileNotFoundException { 871 enforceTree(uri); 872 final ParcelFileDescriptor fd = openDocument(getDocumentId(uri), mode, null); 873 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null; 874 } 875 876 /** 877 * Implementation is provided by the parent class. Cannot be overriden. 878 * 879 * @see #openDocument(String, String, CancellationSignal) 880 */ 881 @Override 882 @SuppressWarnings("resource") 883 public final AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal) 884 throws FileNotFoundException { 885 enforceTree(uri); 886 final ParcelFileDescriptor fd = openDocument(getDocumentId(uri), mode, signal); 887 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null; 888 } 889 890 /** 891 * Implementation is provided by the parent class. Cannot be overriden. 892 * 893 * @see #openDocumentThumbnail(String, Point, CancellationSignal) 894 * @see #openTypedDocument(String, String, Bundle, CancellationSignal) 895 */ 896 @Override 897 public final AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts) 898 throws FileNotFoundException { 899 return openTypedAssetFileImpl(uri, mimeTypeFilter, opts, null); 900 } 901 902 /** 903 * Implementation is provided by the parent class. Cannot be overriden. 904 * 905 * @see #openDocumentThumbnail(String, Point, CancellationSignal) 906 * @see #openTypedDocument(String, String, Bundle, CancellationSignal) 907 */ 908 @Override 909 public final AssetFileDescriptor openTypedAssetFile( 910 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal) 911 throws FileNotFoundException { 912 return openTypedAssetFileImpl(uri, mimeTypeFilter, opts, signal); 913 } 914 915 /** 916 * @hide 917 */ 918 private final AssetFileDescriptor openTypedAssetFileImpl( 919 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal) 920 throws FileNotFoundException { 921 enforceTree(uri); 922 final String documentId = getDocumentId(uri); 923 if (opts != null && opts.containsKey(ContentResolver.EXTRA_SIZE)) { 924 final Point sizeHint = opts.getParcelable(ContentResolver.EXTRA_SIZE); 925 return openDocumentThumbnail(documentId, sizeHint, signal); 926 } 927 if ("*/*".equals(mimeTypeFilter)) { 928 // If they can take anything, the untyped open call is good enough. 929 return openAssetFile(uri, "r"); 930 } 931 final String baseType = getType(uri); 932 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) { 933 // Use old untyped open call if this provider has a type for this 934 // URI and it matches the request. 935 return openAssetFile(uri, "r"); 936 } 937 // For any other yet unhandled case, let the provider subclass handle it. 938 return openTypedDocument(documentId, mimeTypeFilter, opts, signal); 939 } 940} 941