From eaeda874c62a0ebc439894858e110160b7e2a212 Mon Sep 17 00:00:00 2001 From: The Android Open Source Project Date: Tue, 10 Feb 2009 15:44:05 -0800 Subject: auto import from //branches/cupcake/...@130745 --- AndroidManifest.xml | 1 - docs/index.html | 1205 ++++++++++++++++++++ res/values-ko/strings.xml | 31 + res/values-nb/strings.xml | 32 + .../providers/downloads/DownloadProvider.java | 22 +- 5 files changed, 1282 insertions(+), 9 deletions(-) create mode 100644 docs/index.html create mode 100644 res/values-ko/strings.xml create mode 100644 res/values-nb/strings.xml diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 6c6cad1b..a7d424a9 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -35,7 +35,6 @@ - + + + Download Provider + + + +
+

Download Provider

+

+

Contents

+

+

+

+

+


+

+

High-level requirements

+ +

+

Requirements for Android

+

+ + + + + + + + + + + + +
Req# Description Detailed Requirements Status
DLMGR_A_1 The Download Manager MUST satisfy the basic download needs of OTA Updates.   YES done in 1.0
DLMGR_A_2 The Download Manager MUST satisfy the basic download needs of Market.   YES done in 1.0
DLMGR_A_3 The Download Manager MUST satisfy the basic download needs of Gmail.   YES done in 1.0
DLMGR_A_4 The Download Manager MUST satisfy the basic download needs of the Browser.   YES done in 1.0
DLMGR_A_5 Downloads MUST happen and continue in the background, independently of the application in front.   YES done in 1.0
DLMGR_A_6 Downloads MUST be reliable even on unreliable network connections, within the capabilities of the underlying protocol and of the server.   YES done in 1.0
DLMGR_A_7 User-accessible files MUST be stored on the external storage card, and only files that are explicitly supported by an installed application must be downloaded.   YES done in 1.0
DLMGR_A_8 OMA downloads SHOULD be supported.   NO deferred beyond Cupcake (not enough time)
DLMGR_A_9 The Download Manager SHOULD only download when using high-speed (3G/wifi) links, or only when not roaming (if that can be detected).   NO deferred beyond Cupcake (not enough time)
DLMGR_A_10 Downloads SHOULD be user-controllable (if allowed by the initiating application), including pause, resume, and restart of failed downloads. 4001 NO deferred beyond Cupcake (not enough time, need precise specifications)
+

+

Requirements for Cupcake

+

+ + + + + + + + + + + +
Req# Description Detailed Requirements Status
DLMGR_C_1 The Download Manager SHOULD resume downloads where the socket got cleanly closed while the download was incomplete (common behavior on proxies and Google servers) 2005 YES done in Cupcake
DLMGR_C_2 The Download Manager SHOULD retry/resume downloads instead of aborting when the server returns a HTTP code 503 2006 YES done in Cupcake
DLMGR_C_3 The Download Manager SHOULD randomize the retry delay 2007 YES done in Cupcake
DLMGR_C_4 The Download Manager SHOULD use the retry-after header (delta-seconds) for 503 responses 2008 YES done in Cupcake
DLMGR_C_5 The Download Manager MAY hide columns that aren't strictly necessary 1010 YES done in Cupcake
DLMGR_C_6 The Download Manager SHOULD allow the initiating app to pause an ongoing download 1011 YES done in Cupcake
DLMGR_C_7 The Download Manager SHOULD not display multiple notification icons for completed downloads. 4002 NO deferred beyond Cupcake (no precise specifications, need framework support)
DLMGR_C_8 The Download Manager SHOULD delete old files from /cache 3006 NO deferred beyond Cupcake (no precise specifications)
DLMGR_C_9 The Download Manager SHOULD handle redirects 2009 YES done in Cupcake
+

+

Requirements for Donut

+

+ + +
Req# Description Detailed Requirements Status
+

+

Technology Evaluation

+ +

+ALSO See also future directions for possible additional technical changes. +

+

Possible scope for Cupcake

+

+Because there is no testing environment in place in the 1.0 code, and because the schedule between +1.0 and Cupcake doesn't leave enough time to develop a testing environment solid enough to be able +to test the database upgrades from 1.0 database scheme to a new scheme, any work done in Cupcake will +have to work within the existing 1.0 database scheme. +

+

Reducing the number of classes

+

+Each class in the system has a measurable RAM cost (because of the associated Class objects), +and therefore reducing the number of classes when possible or relevant can reduce the memory +requirements. That being said, classes that extend system classes and are necessary for the +operation of the download manager can't be removed. +

+ + + + + + + + + + + + + + + + + + +
Class Comments
com.android.providers.downloads.Constants Only contains constants, can be merged into another class.
com.android.providers.downloads.DownloadFileInfo Should be merged with DownloadInfo.
com.android.providers.downloads.DownloadInfo Once we only store information in RAM about downloads that are explicitly active, can be merged with DownloadThread.
com.android.providers.downloads.DownloadNotification Looks like it could be merged with DownloadProvider or DownloadService.
com.android.providers.downloads.DownloadNotification.NotificationItem Can probably be eliminated by using queries intelligently.
com.android.providers.downloads.DownloadProvider Extends ContentProvider, can't be eliminated.
com.android.providers.downloads.DownloadProvider.DatabaseHelper Can probably be eliminated by re-implementing by hand the logic of SQLiteOpenHelper.
com.android.providers.downloads.DownloadProvider.ReadOnlyCursorWrapper Can be eliminated once Cursor is read-only system-wide.
com.android.providers.downloads.DownloadReceiver Extends BroadcastReceiver, can't be eliminated.
com.android.providers.downloads.DownloadService Extends Service, unlikely that this can be eliminated. TBD.
com.android.providers.downloads.DownloadService.DownloadManagerContentObserver Extends ContentObserver, can be eliminated if the download manager can be re-architected to not depend on ContentObserver any more.
com.android.providers.downloads.DownloadService.MediaScannerConnection Can probably be merged into another class.
com.android.providers.downloads.DownloadService.UpdateThread Can probably be made to implement Runnable instead and merged into another class, can be eliminated if the download manager can be re-architected to not depend on ContentObserver any more.
com.android.providers.downloads.DownloadThread Can probably be made to implement Runnable instead. Unclear whether this can be eliminated as we will probably need one object that represents an ongoing download (unless the entire state can be stored on the stack with primitive types, which is unlikely).
com.android.providers.downloads.Helpers Can't be instantiated, can be merged into another class.
com.android.providers.downloads.Helpers.Lexer Keeps state about an ongoing lex, can probably be merged into another class by making the lexer synchronized, since the operation is short-lived.
+

+

Reducing the list of visible columns

+

+Security in the download provider is primarily enforced with two separate mechanisms: +

+

    +
  • Column restrictions, such that only a small number of the download provider's columns can be read or queried by applications. +
  • +
  • UID restrictions, such that only the application that initiated a download can access information about that download. +
  • +
+

+The first mechanism is expected to be fairly robust (the implementation is quite simple, based on projection maps, which are highly +structured), but the second one relies on arbitrary strings (URIs and SQL fragments) passed by applications and is therefore at a +higher risk of being compromised. Therefore, sensitive information stored in unrestricted columns (for which the first mechanism +doesn't apply) is at a greater risk than other information. +

+Here's the list of columns that can currently be read/queried, with comments: +

+ + + + + + + + + + + + + + +
Column Notes
_ID Needs to be visible so that the app can uniquely identify downloads. No security concern: those numbers are sequential and aren't hard to guess.
_DATA Probably should not be visible to applications. WARNING Security concern: This holds filenames, including those of private files. While file permissions are supposed to kick in and protect the files, hiding private filenames deeper in would probably be a reasonable idea.
MIMETYPE Needs to be visible so that app can display the icon matching the mime type. Intended to be visible by 3rd-party download UIs. TODO Security TBD before we implement support for 3rd-party UIs.
VISIBILITY Needs to be visible in case an app has both visible and invisible downloads. No obvious security concern.
STATUS Needs to be visible (1004). No obvious security concern.
LAST_MODIFICATION Needs to be visible, e.g. so that apps can sort downloads by date of last activity, or discard old downloads. No obvious security concern.
NOTIFICATION_PACKAGE Allows individual apps running under shared UIDs to identify their own downloads. No security concern: can be queried through package manager.
NOTIFICATION_CLASS See NOTIFICATION_PACKAGE.
TOTAL_BYTES Needs to be visible so that the app can display a progress bar. No obvious security concern. Intended to be visible by 3rd-party download UIs.
CURRENT_BYTES See TOTAL_BYTES.
TITLE Intended to be visible by 3rd-party download UIs. TODO Security and Privacy TBD before we implement support for 3rd-party UIs.
DESCRIPTION See TITLE.
+

+

Hiding the URI column

+

+The URI column is visible to the initiating application, which is a mild security risk. It should be hidden, but the OTA update mechanism relies on it to check duplicate downloads and to display the download that's currently ongoing in the settings app. If another string column was exposed to the initiating applications, the OTA update mechanism could use that one, and URI could then be hidden. For Cupcake, without changing the database schema, the ENTITY column could be re-used as it's currently unused. +

+

Handling redirects

+

+There are two important aspects to handle redirects: +

+

    +
  • Storing the intermediate URIs in the provider. +
  • +
  • Protecting against redirect loops. +
  • +
+

+If the URI column gets hidden, it could be used to store the intermediate URIs. After 1.0 the only available integer columns were METHOD and CONTROL. CONTROL was re-exposed to applications and can't be used. METHOD is slated to be re-used for 503 retry-after delays. It could be split into two halves, one for retry-after and one for the redirect count. It would make more sense to count the redirect loop with FAILED_CONNECTIONS, but since there's already quite some code using it it'd take a bit more effort. Ideally handling of redirects would be delayed until a future release, with a cleanup of the database schema (going along with the cleanup of the handling of filenames). +

+Because of the pattern used to read/write DownloadInfo and DownloadProvider, it's impractical to store multiple small integers into a large one. Therefore, since there are no integer columns left in the database, redirects will have to wait beyond Cupcake. +

+

ContentProvider for download UI

+

+In order to allow a UI that can "see" all the relevant downloads, there'll need to be a separate URI (or set of URIs) in the content provider: trying to use the exact same URIs for regular download control and for UI purposes (distinguishing them based on the permissions of the caller) will break down if a same app (or actually a same UID) tries to do both. It'll also break down if the system process tries to do regular download activities, since it has all permissions. +

+Beyond that, there's little technical challenge: there are already mechanisms in place to restrict the list of columns that can be inserted, queried and updated (inserting of course makes no sense through the UI channel), they just need to be duplicated for the case of the UI. The download provider also knows how to check the permissions of its caller, there isn't anything new here. +

+

Getting rid of OTHER_UID

+

+Right now OTHER_UID is used by checkin/update to allow the settings app to display the name of an ongoing OTA update, and by Market to allow the system to install the new apks. It is however a dangerous feature, at least because it touches a part of the code that is critical to the download manager security (separation of applications). +

+Getting rid of OTHER_UID would be beneficial for the download manager, but the existing functionality has to be worked around. At this point, the idea that I consider the most likely would be to have checkin and market implement =ContentProvider= wrappers around their downloads, and expose those content providers to whichever app they want, with whichever security mechanism they wish to have. +

+

Only using SDK APIs.

+

+It'd be good if the download manager could be built against the SDK as much as possible. +

+Here's the list of APIs as of Nov 5 2008 that aren't in the current public API but that are used by the download manager: +

+

+com.google.android.collect.Lists
+android.drm.mobile1.DrmRawContent
+android.media.IMediaScannerService
+android.net.http.AndroidHttpClient
+android.os.FileUtils
+android.provider.DrmStore
+
+

+ + +

+ +

+ + +

+ +

+

Schedule

+

+ +

+

    +
  • No future milestones currently defined +
  • +
+

+

Detailed Requirements

+ +

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Req# History Status Feature Description Notes
1xxx N/A   API    
1001 1.0 YES   Download Manager API The download manager provides an API that allows applications to initiate downloads.  
1002 1.0 YES   Cookies The download manager API allows applications to pass cookies to the download manager.  
1003 1.0 YES   Security The download manager provides a mechanism that prevents arbitrary applications from accessing meta-data about current and past downloads. In 1.0, known holes between apps
1004 1.0 YES   Status to Initiator The download manager allows the application initiating a download to query the status of that download.  
1005 1.0 YES   Cancel by Initiator The download manager allows the application initiating a download to cancel that download.  
1006 1.0 YES   Notify Initiator The download manager notifies the application initiating a download when the download completes (with success or failure)  
1007 1.0 YES   Fire and Forget The download manager does not rely on the initiating application when saving the file to a shared filesystem area  
1008 1.0 YES   Short User-Readable Description The download manager allows the initiating application to optionally provide a user-readable short description of the download  
1009 1.0 YES   Long User-Readable Description The download manager allows the initiating application to optionally provide a user-readable full description of the download  
1010 Cupcake YES Cupcake P3 YES Restrict column access The download provider doesn't allow access to columns that aren't strictly necessary.  
1011 Cupcake YES Cupcake P2 YES Pause downloads The download provider allows the application initiating a download to pause that download.  
2xxx N/A   HTTP    
2001 1.0 YES   HTTP Support The download manager supports all the features of HTTP 1.1 (RFC 2616) that are relevant to file downloads. Codes 3xx weren't considered relevant when those requirements were written
2002 1.0 YES   Resume Downloads The download manager resumes downloads that get interrupted.  
2003 1.0 YES   Flaky Downloads The download manager has mechanism that prevent excessive retries of downloads that consistently fail or get interrupted.  
2004 1.0 YES   Resume after Reboot The download manager resumes downloads across device reboots.  
2005 Cupcake YES Cupcake P2 YES Resume after socket closed The download manager resumes incomplete downloads after the socket gets cleanly closed This is necessary in order to reliably download through GFEs, though it pushes us further away from being able to download from servers that don't implement pipelining.
2006 Cupcake YES Cupcake P2 YES Resume after 503 The download manager resumes or retries downloads when the server returns an HTTP code 503  
2007 Cupcake YES Cupcake P2 YES Random retry delay The download manager uses partial randomness when retrying downloads on an exponential backoff pattern.  
2008 Cupcake YES Cupcake P2 YES Retry-after delta-seconds The download manager uses the retry-after header in a 503 response to decide when to retry the request Handling of absolute dates will be covered by a separate requirement.
2009 Cupcake YES Cupcake P2 YES Redirects The download manager handles common redirects.  
25xx N/A   HTTP/Conditions    
3xxx N/A   Storage    
3001 1.0 YES   File Storage The download manager stores the results of downloads in persistent storage.  
3002 1.0 YES   Max File Size The download manager is able to handle large files (order of magnitude: 50MB)  
3003 1.0 YES   Destination File Permissions The download manager restricts access to the internal storage to applications with the appropriate permissions  
3004 1.0 YES   Initiator File Access The download manager allows the initiating application to access the destination file  
3005 1.0 YES   File Types The download manager does not save files that can't be displayed by any currently installed application  
3006 Cupcake NO Cupcake P3 NO Old Files in /cache The download manager deletes old files in /cache  
35xx N/A   Storage/Filename    
4xxx N/A   UI    
4001 1.0 NO   Download Manager UI The download manager provides a UI that lets user get information about current downloads and control them. Didn't get spec on time to be able to even consider it.
4002 Cupcake NO Cupcake P2 NO Single Notification Icon The download manager displays a single icon in the notification bar regardless of the number of ongoing and completed downloads. No spec in Cupcake timeframe.
5xxx N/A   MIME    
52xx N/A   MIME/DRM    
5201 1.0 YES   DRM The download manager respects the DRM information it receives with the responses  
54xx N/A   MIME/OMA    
60xx N/A   Misc    
65xx N/A   Misc/Browser    
+

+

System Architecture

+ +

+

++----------------------+    +--------------------------------------+    +-------------+
+|                      |    |                                      |    |             |
+|   Download Manager   |    |  Browser / Gmail / Market / Updater  |    |  Viewer App |
+|                      |    |                                      |    |             |
++----------------------+    +--------------------------------------+    +-------------+
+    ^    |    ^                                             ^                ^
+    |    |    |                                             |                |
+    |    |    |                                             |                |
+    |    |    |      +---------------------------+          |                |
+    |    |    |      |                           |          |                |
+    |    |    |      |                           |          |                |
+    |    |    +-------- - - - - - - - - - - - - ------------+                |
+    |    |           |                           |                           |
+    |    |           |                           |                           |
+    |    +------------- - - - - - - - - - - - - -----------------------------+
+    |                |                           |
+    |                |                           |
+    +--------------->|     Android framework     |
+                     |                           |
+                     |                           |
+                     +---------------------------+
+
+

+

+          Application                        Download Manager                         Viewer App
+               |                                     |                                     |
+               |         initiate download           |                                     |
+               |------------------------------------>|                                     |
+               |<------------------------------------|                                     |
+               |        content provider URI         |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |           query download            |                                     |
+               |------------------------------------>|                                     |
+               |<------------------------------------|                                     |
+               |              Cursor                 |                                     |
+               |                                     |                                     |
+               |       register ContentObserver      |                                     |
+               |------------------------------------>|                                     |
+               |                                     |                                     |
+               |     ContentObserver notification    |                                     |
+               |<------------------------------------|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |    intent "notification clicked"    |                                     |
+               |<------------------------------------|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |      intent "download complete"     |                                     |
+               |<------------------------------------|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |            intent "view"            |
+               |                                     |------------------------------------>|
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |           update download           |                                     |
+               |------------------------------------>|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |         open downloaded file        |                                     |
+               |------------------------------------>|                                     |
+               |<------------------------------------|                                     |
+               |         ParcelFileDescriptor        |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |           delete download           |                                     |
+               |------------------------------------>|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               v                                     v                                     v
+
+

+

Internal Product Dependencies

+

+

    +
  • [reverse dependency] GMail depends on the download manager to download attachments. +
  • +
  • [reverse dependency] OTA Update depends on the download manager to download system images. +
  • +
  • [reverse dependency] Vending Machine depends on the download manager to download content. +
  • +
  • [reverse dependency] Browser depends on the download manager to download non-browsable. +
  • +
  • Download Manager depends on a notification system to let the user know when downloads complete or otherwise require attention. +
  • +
  • Download Manager depends on a mechanism to share files with another app (letting apps access its files, or accessing apps' files). +
  • +
  • Download Manager depends on the ability to associate individual downloads with separate applications and to restrict apps to only access their own downloads. +
  • +
  • Download Manager depends on an HTTP stack that predictably processes all relevant kinds of HTTP requests and responses. +
  • +
  • Download Manager depends on a connectivity manager that reports accurate information about the status of the different data connections. +
  • +
+

+

Interface Documentation

+ +

+WARNING Since none of those APIs are public, they are all subject to change. If you're working in the Android source tree, do NOT use the explicit values, ONLY use the symbolic constants, unless you REALLY know what you're doing and are willing to deal with the consequences; you've been warned. +

+The various constants that are meant to be used by applications are all defined in the android.provider.Downloads class. Whenever possible, the constants should be used instead of the explicit values. +

+

Permissions

+

+ + + + + + +
Constant name Permission name Access restrictions Description
Downloads.PERMISSION_ACCESS "android.permission.ACCESS_DOWNLOAD_MANAGER" Signature or System Applications that want to access the Download Manager MUST have this permission.
Downloads.PERMISSION_ACCESS_ADVANCED "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED" Signature or System This permission protects some legacy APIs that new applications SHOULD NOT use.
Downloads.PERMISSION_CACHE "android.permission.ACCESS_CACHE_FILESYSTEM" Signature This permission allows an app to access the /cache filesystem, and is only needed by the Update code. Other applications SHOULD NOT use this permission
Downloads.PERMISSION_SEND_INTENTS "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS" Signature The download manager holds this permission, and the receivers through which applications get intents of completed downloads SHOULD require this permission from the sender
+

+

Content Provider

+

+The primary interface that applications use to communicate with the download manager is exposed as a ContentProvider. +

+

URIs

+

+The URIs for the Content Provider are: +

+ + + + +
Constant name URI Description
Downloads.CONTENT_URI Uri.parse("content://downloads/download") The URI of the whole Content Provider, used to insert new rows, or to query all rows.
N/A ContentUris.withAppendedId(CONTENT_URI, <id>) The URI of an individual download. <id> is the value of the Download._ID column
+

+

Columns

+

+The following columns are available: +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Constant name Column name SQL Type Access Description Notes
Downloads._ID "_id" Integer Read   Inherited from BaseColumns._ID.
Downloads.URI "uri" Text Init   Used to be readable.
Downloads.APP_DATA "entity" Text Init/Read/Modify   Actual column name will change in the future.
Downloads.NO_INTEGRITY "no_integrity" Boolean Init   Used to be readable.
Downloads.FILENAME_HINT "hint" Text Init   Used to be readable.
Downloads._DATA "_data" Text Read   Used to be Downloads.FILENAME and "filename".
Downloads.MIMETYPE "mimetype" Text Init/Read    
Downloads.DESTINATION "destination" Integer Init   See Destination codes for details of legal values. Used to be readable.
Downloads.VISIBILITY "visibility" Integer Init/Read/Modify   See Visibility codes for details of legal values.
Downloads.CONTROL "control" Integer Init/Read/Modify   See Control codes for details of legal values.
Downloads.STATUS "status" Integer Read   See Status codes for details of possible values.
Downloads.LAST_MODIFICATION "lastmod" Bigint Read    
Downloads.NOTIFICATION_PACKAGE "notificationpackage" Text Init/Read    
Downloads.NOTIFICATION_CLASS "notificationclass" Text Init/Read    
Downloads.NOTIFICATION_EXTRAS "notificationextras" Text Init    
Downloads.COOKIE_DATA "cookiedata" Text Init    
Downloads.USER_AGENT "useragent" Text Init    
Downloads.REFERER "referer" Text Init    
Downloads.TOTAL_BYTES "total_bytes" Integer Read   Might gain Init access in the future.
Downloads.CURRENT_BYTES "current_bytes" Integer Read    
Downloads.OTHER_UID "otheruid" Integer Init   Requires the android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED permission. Used to be readable and writable. Might disappear entirely if possible.
Downloads.TITLE "title" String Init/Read/Modify    
Downloads.DESCRIPTION "description" String Init/Read/Modify    
+

+

Destination Values

+

+ + + + + +
Constants name Constant value Description Notes
Downloads.DESTINATION_EXTERNAL 0 Saves the file to the SD card. Default value. Fails is SD card is not present.
Downloads.DESTINATION_CACHE_PARTITION 1 Saves the file to the internal cache partition. Requires the "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED" permission
Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE 2 Saves the file to the internal cache partition. The download can get deleted at any time by the download manager when it needs space.
+

+

Visibility Values

+

+ + + + + +
Constants name Constant value Description Notes
Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED 0 The download is visible in download UIs, and it shows up in the notification area during download and after completion. Default value for external downloads.
Downloads.VISIBILITY_VISIBLE 1 The download is visible in download UIs, and it shows up in the notification area during download but not after completion.  
Downloads.VISIBILITY_HIDDEN 2 The download is hidden from download UIs and doesn't show up in the notification area. Default value for internal downloads.
+

+

Control Values

+

+ + + + +
Constants name Constant value Description Notes
Downloads.CONTROL_RUN 0 The download is allowed to run. Default value.
Downloads.CONTROL_PAUSED 0 The download is paused.  
+

+

Status Values

+

+ + + + + + + + + + + + + + + + + + + + +
Constants name Constant value Description Notes
Downloads.STATUS_PENDING 190 Download hasn't started.  
Downloads.STATUS_PENDING_PAUSED 191 Download hasn't started and can't start immediately (network unavailable, paused by user). Not currently used.
Downloads.STATUS_RUNNING 192 Download has started and is running  
Downloads.STATUS_RUNNING_PAUSED 193 Download has started, but can't run at the moment (network unavailable, paused by user).  
Downloads.STATUS_SUCCESS 200 Download completed successfully.  
Downloads.STATUS_BAD_REQUEST 400 Couldn't initiate the request, or server response 400.  
Downloads.STATUS_NOT_ACCEPTABLE 406 No handler to view the file (external downloads), or server response 406. External downloads are meant to be user-visible, and are aborted if there's no application to handle the relevant MIME type.
Downloads.STATUS_LENGTH_REQUIRED 411 The download manager can't know the length of the download. Because of the unreliability of cell networks, the download manager only performs downloads when it can verify that it has received all the data for a download, except if the initiating app sets the Downloads.NO_INTEGRITY flag.
Downloads.STATUS_PRECONDITION_FAILED 412 The download manager can't resume an interrupted download, because it didn't receive enough information from the server to be able to resume.  
Downloads.STATUS_CANCELED 490 The download was canceled by a cause outside the Download Manager. Formerly known as Downloads.STATUS_CANCELLED. Might be impossible to observe in 1.0.
Downloads.STATUS_UNKNOWN_ERROR 491 The download was aborted because of an unknown error. Formerly known as Downloads.STATUS_ERROR. Typically the result of a runtime exception that is not explicitly handled.
Downloads.STATUS_FILE_ERROR 492 The download was aborted because the data couldn't be saved. Most commonly happens when the filesystem is full.
Downloads.STATUS_UNHANDLED_REDIRECT 493 The download was aborted because the server returned a redirect code 3xx that the download manager doesn't handle. The download manager currently handles 301, 302 and 307.
Downloads.STATUS_TOO_MANY_REDIRECTS 494 The download was aborted because the download manager received too many redirects while trying to find the actual file.  
Downloads.STATUS_UNHANDLED_HTTP_CODE 495 The download was aborted because the server returned a status code that the download manager doesn't handle. Standard codes 3xx, 4xx and 5xx don't trigger this.
Downloads.STATUS_HTTP_DATA_ERROR 496 The download was aborted because of an unrecoverable error trying to get data over the network. Typically this happens when the download manager received several I/O Exceptions in a row while the network is available and without being able to download any data.
  4xx standard HTTP/1.1 4xx codes returned by the server are used as-is. Don't rely on non-standard values being passed through, especially the higher values that would collide with download manager codes.
  5xx standard HTTP/1.1 5xx codes returned by the server are used as-is. Don't rely on non-standard values being passed through.
+

+

Status Helper Functions

+

+ + + + + + + + + +
Function signature Description
public static boolean Downloads.isStatusInformational(int status) Returns whether the status code matches a download that hasn't completed yet.
public static boolean Downloads.isStatusSuspended(int status) Returns whether the download hasn't completed yet but isn't currently making progress.
public static boolean Downloads.isStatusSuccess(int status) Returns whether the download successfully completed.
public static boolean Downloads.isStatusError(int status) Returns whether the download failed.
public static boolean Downloads.isStatusClientError(int status) Returns whether the download failed because of a client error.
public static boolean Downloads.isStatusServerError(int status) Returns whether the download failed because of a server error.
public static boolean Downloads.isStatusCompleted(int status) Returns whether the download completed (with no distinction between success and failure).
+

+

Intents

+

+The download manager sends an intent broadcast Downloads.DOWNLOAD_COMPLETED_ACTION when a download completes. +

+The download manager sends an intent broadcast Downloads.NOTIFICATION_CLICKED_ACTION when the user clicks a download notification that doesn't match a download that can be opened (e.g. because the notification is for several downloads at a time, or because it's for an incomplete download, or because it's for a private download). +

+The download manager starts an activity with Intent.ACTION_VIEW when the user clicks a download notification that matches a download that can be opened. +

+

Differences between 1.0 and Cupcake

+

+WARNING These are the differences for apps built from source in the Android source tree, i.e. they don't cover any of the cases of binary incompatibility. +

+

    +
  • Cursors returned by the content provider are now read-only. +
  • +
  • SQL "where" statements are now verified and must follow a rigid syntax (the most visible aspect being that all parameters much be single-quoted). +
  • +
  • Columns and constants that were unused or ineffective are gone: METHOD, NO_SYSTEM_FILES, DESTINATION_DATA_CACHE, OTA_UPDATE. +
  • +
  • OTHER_UID and DESTINATION_CACHE_PARTITION require android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED. +
  • +
  • The list of columns that can be queried and read is limited: _ID, APP_DATA, _DATA, MIMETYPE, CONTROL, STATUS, LAST_MODIFICATION, NOTIFICATION_PACKAGE, NOTIFICATION_CLASS, TOTAL_BYTES, CURRENT_BYTES, TITLE, DESCRIPTION. +
  • +
  • The list of columns that can be initialized by apps is limited: URI, APP_DATA, NO_INTEGRITY, FILENAME_HINT, MIMETYPE, DESTINATION, VISIBILITY, CONTROL, STATUS, LAST_MODIFICATION, NOTIFICATION_PACKAGE, NOTIFICATION_CLASS, NOTIFICATION_EXTRAS, COOKIE_DATA, USER_AGENT, REFERER, OTHER_UID, TITLE, DESCRIPTION. +
  • +
  • The list of columns that can be updated by apps is limited: APP_DATA, VISIBILITY, CONTROL, TITLE, DESCRIPTION. +
  • +
  • Downloads to the SD card default to have notifications that are visible after completion, internal downloads default to notifications that are always hidden. +
  • +
  • The constant FILENAME was renamed Downloads._DATA. +
  • +
  • Downloads can be paused and resumed by writing to the CONTROL column. Downloads.CONTROL_RUN (Default) makes the download go, Downloads.CONTROL_PAUSED pauses it. +
  • +
  • New column APP_DATA that is untouched by the download manager, used to store app-specific info about the downloads. +
  • +
  • Minor differences unlikely to affect applications: +
      +
    • The notification class/package must now match the UID. +
    • +
    • The backdoor to see the entire provider (which was intended to implement UIs) is gone. +
    • +
    • Private column names were removed from the public API. +
    • +
    +
  • +
+

+

Writing code that works on both the 1.0 and Cupcake versions of the download manager.

+

+If you're not 100% sure that you need to be reading this chapter, don't read it. +

+Basic rule: don't use features that only exist in one of the two implementations (POST, downloads to /data...). +

+Also, don't use columns in 1.0 that are protected or hidden in Cupcake. +

+Unfortunately, that's not always entirely possible. +

+Areas of concern: +

    +
  • Some columns were renamed. FILENAME became Downloads._DATA ("_data"), and ENTITY became APP_DATA ("entity"). +
      +
    • The difference can be used to distinguish between 1.0 and Cupcake, though reflection. +
    • +
    • The difference prevents from using any of the symbolic constants directly in source code: if the same binary wants to run on both 1.0 and Cupcake, it will have to hard-code the values of those constants or use reflection to get to them. +
    • +
    +
  • +
  • URI column accessible in 1.0 but protected in Cupcake. Code that relies on being able to re-read its URI should be using APP_DATA in Cupcake, but that column doesn't exist as such in 1.0. +
      +
    • If the code detects that it's running on Cupcake, write URI to APP_DATA in addition to URI, and query and read from the appropriate column. +
    • +
    • Since the underlying column for APP_DATA exists in both 1.0 and Cupcake even though it has different names, it can actually be used in both cases (see note above about renamed columns). +
    • +
    +
  • +
  • Some of the error codes have been renumbered. STATUS_UNHANDLED_HTTP_CODE and STATUS_HTTP_DATA_ERROR were bumped up from 494 and 495 to 495 and 496. +
  • +
  • Backward compatibility is not guaranteed: the download manager APIs weren't meant to be backward compatible yet. As such it's impossible to guarantee that code that uses the Cupcake download manager will be binary-compatible with future versions. +
      +
    • I intend to eventually change the column name for APP_DATA to "app_data". Because of that, code should use reflection to get to that name instead of hard-coding "entity", so that it always gets the right value for the string. +
    • +
    • I intend to refine the handling of filenames and content URIs, exposing separate columns for situations where a download can be accessed both as a file and through a content URI (e.g. stuff that is recognized by the media scanner). Unfortunately at this point this feature isn't clear in my mind. I'd recommend using reflection to look for the Downloads._DATA column, and if it isn't there to look for the FILENAME column (which has the advantage of also dealing with the difference between 1.0 and Cupcake). +
    • +
    • I intend to renumber the error codes, especially those in the 4xx range, and especially those below 490 (which overlap with standard HTTP error codes but will probably be separated). Reflection would improve the probability to getting to them in the future. Unfortunately, the names of the constants are likely to change in the process, in order to disambiguate codes coming from HTTP from those generated locally. I might try to stick to the following pattern: where a constant is currently named STATUS_XXX, its locally-generated version in the future might be named STATUS_LOCAL_XXX while the current constant name might disappear. Using reflection to try to get to the possible new name instead of using the old name might improve the probability of compatibility in the future. That being said, it is critically important to properly handle the full ranges or error codes, especially the 4xx range, as "expected" errors, and it is far preferable to not try to distinguish between those codes at all: use the functions Downloads.isError and Downloads.isClientError to easily recognize those entire ranges. In order of probability, the 1xx range is the second most likely to be affected. +
    • +
    +
  • +
+

+

Functional Specification

+All the details about what the product does. +

+TODO +

+

Release notes for Cupcake

+

+

    +
  • HTTP codes 301, 302, 303 and 307 (redirects) are now supported +
  • +
  • HTTP code 503 is now handled, with support for retry-after in delay-seconds +
  • +
  • Downloads that were cleanly interrupted are now resumed instead of failing +
  • +
  • Applications can now pause their downloads +
  • +
  • Retry delays are now randomized +
  • +
  • Connectivity is now checked on all interfaces +
  • +
  • Downloads with invalid characters in file name can now be saved +
  • +
  • Various security fixes +
  • +
  • Minor API changes (see API differences between 1.0 and Cupcake) +
  • +
+

+

Product Architecture

+How the tasks are split between the different modules that implement the product/feature. +

+TODO To be completed +

+ + + + + + + + + + + + + + + + + + +
Class
com.android.providers.downloads.Constants
com.android.providers.downloads.DownloadFileInfo
com.android.providers.downloads.DownloadInfo
com.android.providers.downloads.DownloadNotification
com.android.providers.downloads.DownloadNotification.NotificationItem
com.android.providers.downloads.DownloadProvider extends ContentProvider
com.android.providers.downloads.DownloadProvider.DatabaseHelper extends SQLiteOpenHelper
com.android.providers.downloads.DownloadProvider.ReadOnlyCursorWrapper extends CursorWrapper implements CrossProcessCursor
com.android.providers.downloads.DownloadReceiver extends BroadcastReceiver
com.android.providers.downloads.DownloadService extends Service
com.android.providers.downloads.DownloadService.DownloadManagerContentObserver extends ContentObserver
com.android.providers.downloads.DownloadService.MediaScannerConnection implements ServiceConnection
com.android.providers.downloads.DownloadService.UpdateThread extends Thread
com.android.providers.downloads.DownloadThread extends Thread
com.android.providers.downloads.Helpers
com.android.providers.downloads.Helpers.Lexer
+

+The download manager is built primarily around a ContentProvider and a Service. The ContentProvider part is the front end, i.e. applications communicate with the download manager through the provider. The Service part is the back end, which contains the actual download logic, running as a background process. +

+As a first approach, the provider is essentially a canonical provider backed by a SQLite3 database. The biggest difference between the download provider and a "plain" provider is that the download provider aggressively validates its inputs, for security reasons. +

+The service is a background process that performs the actual downloads as requested by the applications. The service doesn't offer any bindable interface, the service object exists strictly so that the system knows how to prioritize the download manager's process against other processes when memory is tight. +

+Communication between the provider and the service is done through public Android APIs, so that the two components are deeply decoupled (they could in fact run in different processes). The download manager starts the service whenever a change is made that can start or restart a download. The service observes and queries the provider for changes, and updates the provider as the download progresses. +

+

+There are a few secondary classes that provide auxiliary functions. +

+A Receiver listens to several broadcasts. Is receives some system broadcasts when the system boots (so that the download manager can resume downloads that were interrupted when the system was turned off) or when the connectivity changes (so that the download manager can restart downloads that were interrupted when connectivity was lost). It also receives intents when the user selects a download notification. +

+

+Finally, some helper classes provide support functions. +

+Most significantly, DownloadThread is responsible for performing the actual downloads as part of the DownloadService's functionality, while UpdateThread is responsible for updating the DownloadInfo whenever the DownloadProvider data changes. +

+DownloadInfo and DownloadFileInfo hold pure data structures, with little or no actual logic. +

+Lexer takes care of validating the snippets of SQL data that are received from applications, to avoid cases of SQL injection. +

+

+

+

+

+

+The service keeps a copy of the provider data in RAM, so that it can determine what changed in the provider when it receives a change notification through the ContentObserver. That data is kept in an array of DownloadInfo structures. +

+Each DownloadThread performs the operations for a single download (or, more precisely, for a single HTTP transaction). Each DownloadThread is backed by a DownloadInfo object. which is in fact on of the objects kept by the DownloadService. While a download is running, the DownloadService can influence the download by writing data into the relevant DownloadInfo object, and the DownloadThread checks that object at appropriate times during the download. +

+Because the DownloadService updates the DownloadInfo objects asynchronously from everything else (it uses a dedicated thread for that purpose), a lot of care has to be taken when upgrading the DownloadInfo object. In fact, only the DownloadService's updateThread function can update that object, and it should be considered read-only to every other bit of code. Even within the updateThread function, some care must be taken to ensure that the DownloadInfos don't get out of sync with the provider. +

+On the other hand, the DownloadService's updateThread function does upgrade the DownloadInfo when it spawns new DownloadThreads (and in a few more circumstances), and when it does that it must also update the DownloadProvider (or risk seeing its DownloadInfo data get overwritten). +

+Because of all that, all code outside of the DowloadService's updateThread must neither read from DownloadProvider nor write to the DownloadInfo objects under any circumstances. The DownloadService's updateFunction is responsible for copying data from the DownloadProvider to the DownloadInfo objects, and must ensure that the DownloadProvider remains in sync with the information it writes into the DownloadInfo objects. +

+

+

+

Implementation Documentation

+How individual modules are implemented. +

+TODO To be completed +

+

Database formats

+

+Android 1.0, format version 31, table downloads: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Column Type
"_id" INTEGER PRIMARY KEY AUTOINCREMENT
"uri" TEXT
"method" INTEGER
"entity" TEXT
"no_integrity" BOOLEAN
"hint" TEXT
"otaupdate" BOOLEAN
"_data" TEXT
"mimetype" TEXT
"destination" INTEGER
"no_system" BOOLEAN
"visibility" INTEGER
"control" INTEGER
"status" INTEGER
"numfailed" INTEGER
"lastmod" BIGINT
"notificationpackage" TEXT
"notificationclass" TEXT
"notificationextras" TEXT
"cookiedata" TEXT
"useragent" TEXT
"referer" TEXT
"total_bytes" INTEGER
"current_bytes" INTEGER
"etag" TEXT
"uid" INTEGER
"otheruid" INTEGER
"title" TEXT
"description" TEXT
"scanned" BOOLEAN
+

+Cupcake, format version 100: Same as format version 31. +

+

Future Directions

+ +

+WARNING This section is for informative purposes only. +

+

API

+

+

    +
  • Expose Download Manager to 3rd party apps - security, robustness . +
  • +
  • Validate application-provided user agent, cookies, etc... to protect against e.g. header injection. +
  • +
  • Allow trust-and-verify MIME type. +
  • +
  • Extract response string from HTTP responses, extract entity from failed responses +
  • +
  • If app fails to be notified, retry later - don't give up because of a single failure. +
  • +
  • Support data: URIs . +
  • +
  • Download files to app-provided content provider . +
  • +
  • Don't pass HTTP codes above about 490 to the initiating app (figure out what the threshold should be). +
  • +
  • Allow initiating app to specify that it wants wifi-only downloads . +
  • +
  • Provide SQL "where" clauses for the different categories of status codes, matching isStatusXXX(). +
  • +
  • There has to be a mechanism by which old downloads are automatically purged from /cache if there's not enough space . +
  • +
  • Clicking the notification for a completed download should go through the initiating app instead of directly opening the file (but what about fire and forget?). +
  • +
  • Clean up the difference between pending_network (waiting for network) and running_paused (user paused the download). +
  • +
  • Allow any app to access the downloaded file (but no other column) of user-downloaded files . +
  • +
  • Provider should return more errors and throw fewer exceptions if possible. +
  • +
  • Add option to auto-dismiss notifications for completed downloads after a given time . +
  • +
  • Delete filename in case of failure - better handle the separation between filename and content URI. +
  • +
  • Allow the initiating application to specify that it wants to restart downloads from scratch if they're interrupted and can't be resumed . +
  • +
  • Save images directly from browser without re-downloading data . +
  • +
  • Give applications the ability to explicitly specify the full target filename (not just a hint). +
  • +
  • Give applications the ability to download multiple files into multiple set locations as if they were a single "package". +
  • +
  • Give applications the ability to download files only if they haven't been already downloaded. +
  • +
  • Give applications the ability to download files that have already been downloaded only if there's a newer version. +
  • +
  • Set-cookie in the response. +
  • +
  • basic auth . +
  • +
  • app-provided prompts for basic auth, ssl, redirects. +
  • +
  • File should be hidden from initiating application when DRM. +
  • +
  • Delay writing of app-visible filename column until file visible (split user-visible vs private files?). +
  • +
  • Separate locally-generated status codes from standard HTTP codes. +
  • +
  • Allow app to specify it doesn't want to resume downloads across reboots (because they might require additional work). +
  • +
  • Allow app to prioritize user-initiated downloads. +
  • +
  • Allow app to specify length of download (full trust, or trust-and-verify). +
  • +
  • Support POST. +
  • +
  • Support PUT. +
  • +
  • Support plugins for additional protocols and download descriptors. +
  • +
  • Rename columns to have an appropriate COLUMN_ prefix. +
  • +
+

+

HTTP Handling

+

+

    +
  • Fail download immediately on authoritative unresolved hostnames . +
  • +
  • The download manager should use the browser's user-agent by default. +
  • +
  • Redirect with HTTP Refresh headers (download current and target content with non-zero refresh). +
  • +
  • Handle content-encoding header. +
  • +
  • Handle transfer-encoding header. +
  • +
  • Find other ways to validate interrupted downloads (signature, last-mod/if-modified-since) . +
  • +
  • Make downloads time out in case of long time with no activity. +
  • +
+

+

File names

+

+

    +
  • Protect against situations where there's already a "downloads" directory on SD card. +
  • +
  • Deal with filenames with invalid characters. +
  • +
  • Refine the logic that builds filenames to better match desktop browsers - drop the query string. +
  • +
  • URI-decode filenames generated from URIs. +
  • +
  • Better deal with filenames that end in '.'. +
  • +
  • Deal with URIs that end in '/' or '?'. +
  • +
  • Investigate how to better deal with filenames that have multiple extensions. +
  • +
+

+

UI

+

+

    +
  • Prompt for redirects across domains or cancel. +
  • +
  • Prompt for redirects from SSL or cancel. +
  • +
  • Prompt for basic auth or cancel. +
  • +
  • Prompt for SSL with untrusted/invalid/expired certificates or cancel. +
  • +
  • Reduce number of icons in the title bar, possibly as low as 1 (animated if there are ongoing downloads, fixed if all downloads have completed) . +
  • +
  • UI to cancel visible downloads. +
  • +
  • UI to pause visible downloads. +
  • +
  • Reorder downloads. +
  • +
  • View SSL certificates. +
  • +
  • Indicate secure downloads. +
  • +
+

+

Handling of specific MIME types

+

+

    +
  • Parse HTML for redirects with meta tag. +
  • +
  • Handle charsets and transcoding of text files. +
  • +
  • Deal with multiparts. +
  • +
  • Support OMA downloads with DD and data in same multipart, i.e. combined delivery. +
  • +
  • Assume application/octet-stream for http responses with no mime type. +
  • +
  • Download anything if an app supports application/octet-stream. +
  • +
  • Download any text/* if an application supports text/plain. +
  • +
  • Should the media scanner be invoked on DRM downloads? +
  • +
  • Refresh header with timer should be followed if content is not downloadable. +
  • +
  • Support OMA downloads. +
  • +
  • Support MIDP-OTA downloads. +
  • +
  • Support Sprint MCD downloads. +
  • +
  • Sniff content when receiving MIME-types known to be inaccurately sent by misconfigured servers. +
  • +
+

+

Management of downloads based on environment

+

+

    +
  • If the device routinely connects over wifi, delay non-interactive downloads by a certain amount of time in case wifi becomes available +
  • +
  • Turn on wifi if possible +
  • +
  • Fall back to cell when wifi is available but download doesn't proceed +
  • +
  • Be smarter about spurious losses (i.e. exceptions while network appears up) when the active network changes (e.g. turn on wifi while downloading over cell). +
  • +
  • Investigate the use of wifi locks, especially when performing non-resumable downloads. +
  • +
  • Poll network state (and maybe even try to connect) even without notifications from the connectivity manager (in case the notifications go AWOL or get inconsistent) . +
  • +
  • Pause when conditions degrade . +
  • +
  • Pause when roaming. +
  • +
  • Throttle or pause when user is active. +
  • +
  • Pause on slow networks (2G). +
  • +
  • Pause when battery is low. +
  • +
  • Throttle to not overwhelm the link. +
  • +
  • Pause when sync is active. +
  • +
  • Deal with situations where the active connection is down but there's another connection available +
  • +
  • Download files at night when the user is not explicitly waiting. +
  • +
+

+

Management of simultaneous downloads

+

+

    +
  • Pipeline requests on limited number of sockets, run downloads sequentially . +
  • +
  • Manage bandwidth to not starve foreground tasks. +
  • +
  • Run unsized downloads on their own (on a per-filesystem basis) to avoid failing multiple of them because of a full filesystem . +
  • +
+

+

Minor functional changes, edge cases

+

+

    +
  • The database could be somewhat checked when it's opened. +
  • +
  • [DownloadProvider.java] When upgrading the database, the numbering of ids should restart where it left off. +
  • +
  • [DownloadProvider.java] Handle errors when failing to start the service. +
  • +
  • [DownloadProvider.java] Explicitly populate all database columns that have documented default values, investigate whether that can be done at the SQL level. +
  • +
  • [DownloadProvider.java] It's possible that the last update time should be updated by the Sevice logic, not by the content provider. +
  • +
  • When relevant, combine logged messages on fewer lines. +
  • +
  • [DownloadService.java] Trim the database in the provider, not in the service. Notify application when trimming. Investigate why the row count seems off by one. Enforce on an ongoing basis. +
  • +
  • [DownloadThread.java] When download is restarted and MIME type wasn't provided by app, don't re-use MIME type. +
  • +
  • [DownloadThread.java] Deal with mistmatched file data sizes (between database and filesystem) when resuming a download, or with missing files that should be here. +
  • +
  • [DownloadThread.java] Validate that the response content-length can be properly parsed (i.e. presence of a string doesn't guarantee correctness). +
  • +
  • [DownloadThread.java] Be finer-grained with the way file permissions are managed in /cache - don't 0644 everything . +
  • +
  • Truncate files before deleting them, in case they're still open cross-process. +
  • +
  • Restart from scratch downloads that had very little progress . +
  • +
  • Deal with situations where /data is full as it prevents the database from growing (DoS) . +
  • +
  • Wait until file scanned to notify that download is completed. +
  • +
  • Missing some detailed logging about IOExceptions. +
  • +
  • Allow to disable LOGD debugging independently from system setting. +
  • +
  • Pulling the battery during a download corrupts files (lots of zeros written) . +
  • +
  • Should keep a bit of "emergency" database storage to initiate the download of an OTA update, in a file that is pre-allocated whenever possible (how to know it's an OTA update?). +
  • +
  • Figure out how to hook up into dumpsys and event log. +
  • +
  • Use the event log to log download progress. +
  • +
  • Use /cache to stage downloads that eventually go to the sd card, to avoid having sd files open too long in case the use pulls the card and to avoid partial files for too long. +
  • +
  • Maintain per-application usage statistics. +
  • +
  • There might be corner cases where the notifications are slightly off because different notifications might be using PendingIntents that can't be distinguished (differing only by their extras). +
  • +
+

+

Architecture and Implementation

+

+

    +
  • The content:// Uri of individual downloads could be cached instead of being re-built whenever it's needed. +
  • +
  • [DownloadProvider.java] Solidify extraction of id from URI +
  • +
  • [DownloadProvider.java] Use ContentURIs.parseId(uri) to extra the id from various functions. +
  • +
  • [DownloadProvider.java] Use StringBuilder to build the various queries. +
  • +
  • [DownloadService.java] Cache interface to the media scanner service more aggressively. +
  • +
  • [DownloadService.java] Investigate why unbinding from the media scanner service sometimes throws an exception +
  • +
  • [DownloadService.java] Handle exceptions in the service's UpdateThread - mark that there's no thread left. +
  • +
  • [DownloadService.java] At the end of UpdateThread, closing the cursor should be done even if there's an exception. Also log the exception, as we'd be in an inconsistent state. +
  • +
  • [DownloadProvider.java] Investigate whether the download provider should aggressively cache the result of getContext() and getContext().getContentResolver() +
  • +
  • Document the database columns that are most likely to stay unchanged throughout versions, to increase the chance being able to perform downgrades. +
  • +
  • [DownloadService.java] Sanity-check the ordering of the local cache when adding/removing rows. +
  • +
  • [DownloadService.java] Factor the code that checks for DRM types into a separate function. +
  • +
  • [DownloadService.java] Factor the code that notifies applications into a separate function (codepath with early 406 failure) +
  • +
  • [DownloadService.java] Check for errors when spawning download threads. +
  • +
  • [DownloadService.java] Potential race condition when a download completes at the same time as it gets deleted through the content provider - see deleteDownload(). +
  • +
  • [DownloadService.java] Catch all exceptions in scanFile - don't trust a remote process to the point where we'd let it crash us. +
  • +
  • [DownloadService.java] Limit number of attempts to scan a file. +
  • +
  • [DownloadService.java] Keep less data in RAM, especially about completed downloads. Investigating cutting unused columns if necessary +
  • +
  • [DownloadThread.java] Don't let exceptions out of run() - that'd kill the service, which'd accomplish no good. +
  • +
  • [DownloadThread.java] Keep track of content-length responses in a long, not in a string that we keep parsing . +
  • +
  • [DownloadThread.java] Use variable-size buffer to avoid thousands of operations on large downloads +
  • +
  • [Helpers.java] Deal with atomicity of checking/creating file. +
  • +
  • [Helpers.java] Handle differences between content-location separators and filesystem separators. +
  • +
  • Optimize database queries: use projections to reduce number of columns and get constant column numbers. +
  • +
  • Index last-mod date in DB, because of ordered searches. Investigate whether other columns need to be indexed (Hidden?) +
  • +
  • Deal with the fact that sqlite INTEGER matches java long (63-bit) . +
  • +
  • Use a single HTTP client for the entire download manager. +
  • +
  • Could use fewer alarms - currently setting new alarm each time database updated . +
  • +
  • Obsolete columns should be removed from the database . +
  • +
  • Assign relevant names to threads. +
  • +
  • Investigate and handle the different subclasses of IOException appropriately . +
  • +
  • There's potentially a race condition around read-modify-write cycles in the database, between the Service's updateFromProvider thread and the worker threads (and possibly more). Those should be synchronized appropriately, and the provider should be hardened to prevent asynchronous changes to sensitive data (or to synchronize when there's no other way, though I'd rather avoid that) . +
  • +
  • Temporary file leaks when downloads are deleted while the service isn't running . +
  • +
  • Increase priority of updaterThread while in the critical section (to avoid issues of priority inheritance with the main thread). +
  • +
  • Explicitly specify which interface to use for a given download (to get better sync with the connection manager). +
  • +
  • Cancel the requests on more kinds of errors instead of trusting the garbage collector. +
  • +
  • Issues with the fact that parseInt can throw exceptions on invalid server headers. +
  • +
+

+

Code style, refactoring

+

+

    +
  • Fix lint warnings +
  • +
  • Make sure that comments fit in 80 columns to match style guide +
  • +
  • Unify code style when dealing with lines longer than 100 characters +
  • +
  • [Constants.java] constants should be organized by logical groups to improve readability. +
  • +
  • Use fewer internal classes (Helpers, Constants...) . +
  • +
+

+

Browser changes

+

+

    +
  • Move download UI outside of browser, so that browser doesn't need to access the provider. +
  • +
  • Make browser sniff zips and jars to see if they're apks. +
  • +
  • Live handoff of browser-initiated downloads (download in browser, browser update download UI, hand over to download manager on retry). +
  • +
+ + diff --git a/res/values-ko/strings.xml b/res/values-ko/strings.xml new file mode 100644 index 00000000..c51b1722 --- /dev/null +++ b/res/values-ko/strings.xml @@ -0,0 +1,31 @@ + + + + "다운로드 관리자 액세스" + "응용 프로그램이 다운로드 관리자에 액세스하여 파일을 다운로드할 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 다운로드를 손상시키고 개인 정보에 액세스할 수 있습니다." + "다운로드 관리자 고급 기능" + "응용프로그램이 다운로드 관리자의 고급 기능에 액세스할 수 있습니다."\n" 악성 응용프로그램은 이 기능을 이용하여 다운로드를 중단시키고"\n" 개인 정보에 액세스할 수 있습니다." + "시스템 캐시 사용" + "응용 프로그램이 시스템 캐시에 직접 액세스, 수정 및 삭제할 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 다운로드와 기타 응용 프로그램을 심하게 손상시키고 개인 데이터에 액세스할 수 있습니다." + "다운로드 알림 보내기" + "응용 프로그램이 완료된 다운로드에 대한 알림을 보낼 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 파일을 다운로드하는 다른 응용 프로그램과 혼동하도록 할 수 있습니다." + "<제목없음>" + "," + "및 %d개 이상" + "다운로드 완료" + "다운로드 실패" + diff --git a/res/values-nb/strings.xml b/res/values-nb/strings.xml new file mode 100644 index 00000000..997578e5 --- /dev/null +++ b/res/values-nb/strings.xml @@ -0,0 +1,32 @@ + + + + "Få tilgang til nedlasteren." + "Gir applikasjonen tilgang til nedlasteren, og å bruke den til å laste ned filer. Ondsinnede programmer kan bruke dette til å forstyrre nedlastinger og få tilgang til privat informasjon." + "Avansert nedlastingsfunksjonalitet." + + + "Bruke systemets hurtigbuffer." + "Gir applikasjonen direkte tilgang til systemets hurtigbuffer, inkludert å redigere og slette den. Ondsinnede applikasjoner kan bruke dette til å forstyrre nedlastinger og andre applikasjoner, og til å få tilgang til privat informasjon." + "Sende nedlastingsvarslinger" + "Lar applikasjonen sende varslinger om ferdige nedlastinger. Ondsinnede applikasjoner kan bruke dette for å forvirre andre applikasjoner som laster ned filer." + "<Uten navn>" + "," + "samt %d til" + "Ferdig nedlasting" + "Mislykket nedlasting" + diff --git a/src/com/android/providers/downloads/DownloadProvider.java b/src/com/android/providers/downloads/DownloadProvider.java index d86fdf97..f7cdd51e 100644 --- a/src/com/android/providers/downloads/DownloadProvider.java +++ b/src/com/android/providers/downloads/DownloadProvider.java @@ -268,21 +268,27 @@ public final class DownloadProvider extends ContentProvider { copyBoolean(Downloads.NO_INTEGRITY, values, filteredValues); copyString(Downloads.FILENAME_HINT, values, filteredValues); copyString(Downloads.MIMETYPE, values, filteredValues); - Integer i = values.getAsInteger(Downloads.DESTINATION); - if (i != null) { + Integer dest = values.getAsInteger(Downloads.DESTINATION); + if (dest != null) { if (getContext().checkCallingPermission(Downloads.PERMISSION_ACCESS_ADVANCED) != PackageManager.PERMISSION_GRANTED - && i != Downloads.DESTINATION_EXTERNAL - && i != Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE) { + && dest != Downloads.DESTINATION_EXTERNAL + && dest != Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE) { throw new SecurityException("unauthorized destination code"); } - filteredValues.put(Downloads.DESTINATION, i); - if (i != Downloads.DESTINATION_EXTERNAL && - values.getAsInteger(Downloads.VISIBILITY) == null) { + filteredValues.put(Downloads.DESTINATION, dest); + } + Integer vis = values.getAsInteger(Downloads.VISIBILITY); + if (vis == null) { + if (dest == Downloads.DESTINATION_EXTERNAL) { + filteredValues.put(Downloads.VISIBILITY, + Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); + } else { filteredValues.put(Downloads.VISIBILITY, Downloads.VISIBILITY_HIDDEN); } + } else { + filteredValues.put(Downloads.VISIBILITY, vis); } - copyInteger(Downloads.VISIBILITY, values, filteredValues); copyInteger(Downloads.CONTROL, values, filteredValues); filteredValues.put(Downloads.STATUS, Downloads.STATUS_PENDING); filteredValues.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis()); -- cgit v1.2.3 From c2fb15f7689a10c7fe3b6c1f1ed0ce1f5a95ba9b Mon Sep 17 00:00:00 2001 From: The Android Open Source Project Date: Thu, 19 Feb 2009 10:57:36 -0800 Subject: auto import from //branches/cupcake/...@132276 --- res/values-ja/strings.xml | 6 +++--- src/com/android/providers/downloads/DownloadService.java | 4 ++-- src/com/android/providers/downloads/Helpers.java | 5 ++--- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index b2ab9c40..d26c191e 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -16,13 +16,13 @@ "ダウンロードマネージャーにアクセスします。" - "アプリケーションでダウンロードマネージャーにアクセスしてファイルをダウンロードできるようにします。悪意のあるアプリケーションではこれを利用して、ダウンロードに深刻な影響を与えたり、個人データにアクセスしたりできます。" + "ダウンロードマネージャーにアクセスしてファイルをダウンロードすることをアプリケーションに許可します。悪意のあるアプリケーションがこれを利用して、ダウンロードに深刻な影響を与えたり、個人データにアクセスしたりする恐れがあり。" "ダウンロードマネージャーの高度な機能です。" "ダウンロードマネージャーの高度な機能にアプリケーションでアクセスできるようにします。"\n" 悪意のあるアプリケーションではこれを利用して、ダウンロードに深刻な影響を与えたり、"\n" 個人情報にアクセスしたりできます。" "システムキャッシュを使用します。" - "アプリケーションでシステムキャッシュを直接アクセス、変更、削除できるようにします。悪意のあるアプリケーションではこれを利用して、ダウンロードや他のアプリケーションに深刻な影響を与えたり、個人データにアクセスしたりできます。" + "システムキャッシュの直接アクセス、変更、削除をアプリケーションに許可します。悪意のあるアプリケーションがダウンロードや他のアプリケーションに深刻な影響を与えたり、個人データにアクセスする恐れがあります。" "ダウンロード通知を送信します。" - "ダウンロード完了の通知をアプリケーションから送信できるようにします。悪意のあるアプリケーションではこの通知を利用して、ファイルをダウンロードする他のアプリケーションの処理を妨害できます。" + "ダウンロード完了の通知の送信をアプリケーションに許可します。悪意のあるアプリケーションがファイルをダウンロードする他のアプリケーションの処理を妨害する恐れがあります。" "<無題>" "、" "他%d件" diff --git a/src/com/android/providers/downloads/DownloadService.java b/src/com/android/providers/downloads/DownloadService.java index d4b5f1e6..0600cfb6 100644 --- a/src/com/android/providers/downloads/DownloadService.java +++ b/src/com/android/providers/downloads/DownloadService.java @@ -623,11 +623,11 @@ public class DownloadService extends Service { // nothing mimetypeIntent.setDataAndType(Uri.fromParts("file", "", null), info.mimetype); - List list = getPackageManager().queryIntentActivities(mimetypeIntent, + ResolveInfo ri = getPackageManager().resolveActivity(mimetypeIntent, PackageManager.MATCH_DEFAULT_ONLY); //Log.i(Constants.TAG, "*** QUERY " + mimetypeIntent + ": " + list); - if (list.size() == 0) { + if (ri == null) { if (Config.LOGD) { Log.d(Constants.TAG, "no application to handle MIME type " + info.mimetype); } diff --git a/src/com/android/providers/downloads/Helpers.java b/src/com/android/providers/downloads/Helpers.java index 89a57313..7c6070f3 100644 --- a/src/com/android/providers/downloads/Helpers.java +++ b/src/com/android/providers/downloads/Helpers.java @@ -115,11 +115,10 @@ public class Helpers { PackageManager pm = context.getPackageManager(); intent.setDataAndType(Uri.fromParts("file", "", null), mimeType); - List list = pm.queryIntentActivities(intent, - PackageManager.MATCH_DEFAULT_ONLY); + ResolveInfo ri = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); //Log.i(Constants.TAG, "*** FILENAME QUERY " + intent + ": " + list); - if (list.size() == 0) { + if (ri == null) { if (Config.LOGD) { Log.d(Constants.TAG, "no handler found for type " + mimeType); } -- cgit v1.2.3 From a3955d09003ab9691bc77a323f292515ab2c0b6b Mon Sep 17 00:00:00 2001 From: The Android Open Source Project Date: Mon, 2 Mar 2009 22:54:45 -0800 Subject: auto import from //depot/cupcake/@137055 --- res/values-cs/strings.xml | 4 ++-- res/values-de/strings.xml | 4 ++-- res/values-es/strings.xml | 4 ++-- res/values-fr/strings.xml | 4 ++-- res/values-it/strings.xml | 4 ++-- res/values-ja/strings.xml | 4 ++-- res/values-ko/strings.xml | 4 ++-- res/values-nb/strings.xml | 4 ++-- res/values-nl/strings.xml | 6 +++--- res/values-pl/strings.xml | 4 ++-- res/values-ru/strings.xml | 4 ++-- res/values-zh-rCN/strings.xml | 4 ++-- res/values-zh-rTW/strings.xml | 4 ++-- 13 files changed, 27 insertions(+), 27 deletions(-) diff --git a/res/values-cs/strings.xml b/res/values-cs/strings.xml index cbac9ac2..96cd35c4 100644 --- a/res/values-cs/strings.xml +++ b/res/values-cs/strings.xml @@ -24,8 +24,8 @@ "Odeslat oznámení o stahování." "Umožní aplikaci odeslat oznámení o dokončení stahování. Škodlivé aplikace mohou pomocí tohoto nastavení zmást jiné aplikace, které stahují soubory." "<Bez názvu>" - "," - "a ještě %d" + ", " + " a ještě %d" "Stahování bylo dokončeno" "Stahování bylo neúspěšné" diff --git a/res/values-de/strings.xml b/res/values-de/strings.xml index 966ab2fc..224245d0 100644 --- a/res/values-de/strings.xml +++ b/res/values-de/strings.xml @@ -24,8 +24,8 @@ "Benachrichtigungen zu Ladevorgängen senden" "Ermöglicht es der Anwendung, Benachrichtigungen zu abgeschlossenen Ladevorgängen zu senden. Diese Funktion kann von bösartigen Anwendungen dazu verwendet werden, den Ladevorgang anderer Anwendungen zu stören." "<Unbenannt>" - "," - "und %d weitere" + ", " + " und %d weitere" "Ladevorgang abgeschlossen" "Fehler beim Ladevorgang" diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index 388b6590..61e0dbf4 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -24,8 +24,8 @@ "Envío de notificaciones de descarga" "Permite que la aplicación envíe notificaciones sobre descargas completadas. Las aplicaciones malintencionadas pueden utilizar este permiso para confundir a otras aplicaciones que descarguen archivos." "<Sin título>" - "," - "y %d más" + ", " + " y %d más" "Descarga completada" "Descarga incorrecta" diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml index d040a3cd..dd1693a3 100644 --- a/res/values-fr/strings.xml +++ b/res/values-fr/strings.xml @@ -24,8 +24,8 @@ "Envoyer des notifications de téléchargement." "Permet à l\'application d\'envoyer des notifications concernant les téléchargements effectués. Les applications malveillantes peuvent s\'en servir pour tromper les autres applications de téléchargement de fichiers." "<Sans_titre>" - "," - "et %d autres" + ", " + " et %d autres" "Téléchargement terminé." "Échec du téléchargement" diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index 0e16675b..38b353c6 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -24,8 +24,8 @@ "Inviare notifiche di download." "Consente l\'invio da parte dell\'applicazione di notifiche relative ai download completati. Le applicazioni dannose possono sfruttare questa possibilità per \"confondere\" altre applicazioni usate per scaricare file." "<Senza nome>" - "," - "e altri %d" + ", " + " e altri %d" "Download completato" "Download non riuscito" diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index d26c191e..ceb551c4 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -24,8 +24,8 @@ "ダウンロード通知を送信します。" "ダウンロード完了の通知の送信をアプリケーションに許可します。悪意のあるアプリケーションがファイルをダウンロードする他のアプリケーションの処理を妨害する恐れがあります。" "<無題>" - "、" - "他%d件" + "、 " + " 他%d件" "ダウンロード完了" "ダウンロードに失敗しました" diff --git a/res/values-ko/strings.xml b/res/values-ko/strings.xml index c51b1722..c37f4bd1 100644 --- a/res/values-ko/strings.xml +++ b/res/values-ko/strings.xml @@ -24,8 +24,8 @@ "다운로드 알림 보내기" "응용 프로그램이 완료된 다운로드에 대한 알림을 보낼 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 파일을 다운로드하는 다른 응용 프로그램과 혼동하도록 할 수 있습니다." "<제목없음>" - "," - "및 %d개 이상" + ", " + " 및 %d개 이상" "다운로드 완료" "다운로드 실패" diff --git a/res/values-nb/strings.xml b/res/values-nb/strings.xml index 997578e5..548d737d 100644 --- a/res/values-nb/strings.xml +++ b/res/values-nb/strings.xml @@ -25,8 +25,8 @@ "Sende nedlastingsvarslinger" "Lar applikasjonen sende varslinger om ferdige nedlastinger. Ondsinnede applikasjoner kan bruke dette for å forvirre andre applikasjoner som laster ned filer." "<Uten navn>" - "," - "samt %d til" + ", " + " samt %d til" "Ferdig nedlasting" "Mislykket nedlasting" diff --git a/res/values-nl/strings.xml b/res/values-nl/strings.xml index 66c30b8b..cdaaf544 100644 --- a/res/values-nl/strings.xml +++ b/res/values-nl/strings.xml @@ -18,14 +18,14 @@ "Downloadbeheer weergeven." "Hiermee kan de toepassing Downloadbeheer gebruiken om bestanden te downloaden. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om downloads te verstoren en om toegang te krijgen tot privégegevens." "Geavanceerde functies van de downloadbeheerder." - "Hiermee krijgt de toepassing toegang tot de geavanceerde functies van de downloadbeheerder."\n" Schadelijke toepassingen kunnen hiermee downloads onderbreken en toegang krijgen tot uw "\n" privégegevens." + "Hiermee krijgt de toepassing toegang tot de geavanceerde functies van de downloadbeheerder."\n" Schadelijke toepassingen kunnen hiermee downloads onderbreken en toegang krijgen tot uw "\n" privégegevens." "Systeemcache gebruiken." "Hiermee kan de toepassing rechtstreeks de systeemcache openen, aanpassen of wissen. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om downloads en andere toepassingen te verstoren en om toegang te krijgen tot privégegevens." "Downloadmeldingen verzenden." "Hiermee ontvangt u een melding zodra een download is voltooid. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om andere toepassingen die bestanden downloaden, in de war te brengen." "<Zonder titel>" - "," - "en nog %d" + ", " + " en nog %d" "Downloaden is voltooid" "Downloaden is mislukt." diff --git a/res/values-pl/strings.xml b/res/values-pl/strings.xml index 7cd3e28e..6e77eafc 100644 --- a/res/values-pl/strings.xml +++ b/res/values-pl/strings.xml @@ -24,8 +24,8 @@ "Wysyłanie powiadomień o pobraniu." "Umożliwia programowi wysyłanie powiadomień o ukończeniu pobierania. Szkodliwe programy mogą korzystać z tego uprawnienia, aby zakłócić działanie innych programów pobierających pliki." "<Bez nazwy>" - "," - "i %d innych" + ", " + " i %d innych" "Pobieranie zakończone." "Pobieranie nie powiodło się" diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index fb2c5c5c..a76850f2 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -24,8 +24,8 @@ "Отправлять уведомления о загрузках." "Разрешает приложениям отправлять уведомления о завершенных загрузках. Вредоносные приложения могут использовать это, чтобы передавать ложную информацию другим приложениям загрузки файлов." "<Без названия>" - "," - "и еще %d" + ", " + " и еще %d" "Загрузка завершена" "Загрузка не удалась" diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml index 642a7e09..7802b9bd 100644 --- a/res/values-zh-rCN/strings.xml +++ b/res/values-zh-rCN/strings.xml @@ -24,8 +24,8 @@ "发送下载通知。" "允许应用程序发送关于已完成下载的通知。恶意应用程序可以使用该功能干扰其他下载文件的应用程序。" "<未命名>" - "、" - "以及另外 %d 个" + "、 " + " 以及另外 %d 个" "下载完成" "下载不成功" diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml index eeb4ea80..0bf222bc 100644 --- a/res/values-zh-rTW/strings.xml +++ b/res/values-zh-rTW/strings.xml @@ -24,8 +24,8 @@ "傳送下載通知。" "下載完成時,允許應用程式送出通知。惡意程式可使用此功能干擾其他正在下載檔案的應用程式。" "(未命名)" - "," - "還有 %d 項下載" + ", " + " 還有 %d 項下載" "下載已完成。" "下載失敗" -- cgit v1.2.3 From 96d15ef26e4ac2d15bb11c327a8a04027032bab7 Mon Sep 17 00:00:00 2001 From: The Android Open Source Project Date: Tue, 3 Mar 2009 14:04:37 -0800 Subject: auto import from //depot/cupcake/@132589 --- res/values-cs/strings.xml | 4 ++-- res/values-de/strings.xml | 4 ++-- res/values-es/strings.xml | 4 ++-- res/values-fr/strings.xml | 4 ++-- res/values-it/strings.xml | 4 ++-- res/values-ja/strings.xml | 4 ++-- res/values-ko/strings.xml | 4 ++-- res/values-nb/strings.xml | 4 ++-- res/values-nl/strings.xml | 6 +++--- res/values-pl/strings.xml | 4 ++-- res/values-ru/strings.xml | 4 ++-- res/values-zh-rCN/strings.xml | 4 ++-- res/values-zh-rTW/strings.xml | 4 ++-- 13 files changed, 27 insertions(+), 27 deletions(-) diff --git a/res/values-cs/strings.xml b/res/values-cs/strings.xml index 96cd35c4..cbac9ac2 100644 --- a/res/values-cs/strings.xml +++ b/res/values-cs/strings.xml @@ -24,8 +24,8 @@ "Odeslat oznámení o stahování." "Umožní aplikaci odeslat oznámení o dokončení stahování. Škodlivé aplikace mohou pomocí tohoto nastavení zmást jiné aplikace, které stahují soubory." "<Bez názvu>" - ", " - " a ještě %d" + "," + "a ještě %d" "Stahování bylo dokončeno" "Stahování bylo neúspěšné" diff --git a/res/values-de/strings.xml b/res/values-de/strings.xml index 224245d0..966ab2fc 100644 --- a/res/values-de/strings.xml +++ b/res/values-de/strings.xml @@ -24,8 +24,8 @@ "Benachrichtigungen zu Ladevorgängen senden" "Ermöglicht es der Anwendung, Benachrichtigungen zu abgeschlossenen Ladevorgängen zu senden. Diese Funktion kann von bösartigen Anwendungen dazu verwendet werden, den Ladevorgang anderer Anwendungen zu stören." "<Unbenannt>" - ", " - " und %d weitere" + "," + "und %d weitere" "Ladevorgang abgeschlossen" "Fehler beim Ladevorgang" diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index 61e0dbf4..388b6590 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -24,8 +24,8 @@ "Envío de notificaciones de descarga" "Permite que la aplicación envíe notificaciones sobre descargas completadas. Las aplicaciones malintencionadas pueden utilizar este permiso para confundir a otras aplicaciones que descarguen archivos." "<Sin título>" - ", " - " y %d más" + "," + "y %d más" "Descarga completada" "Descarga incorrecta" diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml index dd1693a3..d040a3cd 100644 --- a/res/values-fr/strings.xml +++ b/res/values-fr/strings.xml @@ -24,8 +24,8 @@ "Envoyer des notifications de téléchargement." "Permet à l\'application d\'envoyer des notifications concernant les téléchargements effectués. Les applications malveillantes peuvent s\'en servir pour tromper les autres applications de téléchargement de fichiers." "<Sans_titre>" - ", " - " et %d autres" + "," + "et %d autres" "Téléchargement terminé." "Échec du téléchargement" diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index 38b353c6..0e16675b 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -24,8 +24,8 @@ "Inviare notifiche di download." "Consente l\'invio da parte dell\'applicazione di notifiche relative ai download completati. Le applicazioni dannose possono sfruttare questa possibilità per \"confondere\" altre applicazioni usate per scaricare file." "<Senza nome>" - ", " - " e altri %d" + "," + "e altri %d" "Download completato" "Download non riuscito" diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml index ceb551c4..d26c191e 100644 --- a/res/values-ja/strings.xml +++ b/res/values-ja/strings.xml @@ -24,8 +24,8 @@ "ダウンロード通知を送信します。" "ダウンロード完了の通知の送信をアプリケーションに許可します。悪意のあるアプリケーションがファイルをダウンロードする他のアプリケーションの処理を妨害する恐れがあります。" "<無題>" - "、 " - " 他%d件" + "、" + "他%d件" "ダウンロード完了" "ダウンロードに失敗しました" diff --git a/res/values-ko/strings.xml b/res/values-ko/strings.xml index c37f4bd1..c51b1722 100644 --- a/res/values-ko/strings.xml +++ b/res/values-ko/strings.xml @@ -24,8 +24,8 @@ "다운로드 알림 보내기" "응용 프로그램이 완료된 다운로드에 대한 알림을 보낼 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 파일을 다운로드하는 다른 응용 프로그램과 혼동하도록 할 수 있습니다." "<제목없음>" - ", " - " 및 %d개 이상" + "," + "및 %d개 이상" "다운로드 완료" "다운로드 실패" diff --git a/res/values-nb/strings.xml b/res/values-nb/strings.xml index 548d737d..997578e5 100644 --- a/res/values-nb/strings.xml +++ b/res/values-nb/strings.xml @@ -25,8 +25,8 @@ "Sende nedlastingsvarslinger" "Lar applikasjonen sende varslinger om ferdige nedlastinger. Ondsinnede applikasjoner kan bruke dette for å forvirre andre applikasjoner som laster ned filer." "<Uten navn>" - ", " - " samt %d til" + "," + "samt %d til" "Ferdig nedlasting" "Mislykket nedlasting" diff --git a/res/values-nl/strings.xml b/res/values-nl/strings.xml index cdaaf544..66c30b8b 100644 --- a/res/values-nl/strings.xml +++ b/res/values-nl/strings.xml @@ -18,14 +18,14 @@ "Downloadbeheer weergeven." "Hiermee kan de toepassing Downloadbeheer gebruiken om bestanden te downloaden. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om downloads te verstoren en om toegang te krijgen tot privégegevens." "Geavanceerde functies van de downloadbeheerder." - "Hiermee krijgt de toepassing toegang tot de geavanceerde functies van de downloadbeheerder."\n" Schadelijke toepassingen kunnen hiermee downloads onderbreken en toegang krijgen tot uw "\n" privégegevens." + "Hiermee krijgt de toepassing toegang tot de geavanceerde functies van de downloadbeheerder."\n" Schadelijke toepassingen kunnen hiermee downloads onderbreken en toegang krijgen tot uw "\n" privégegevens." "Systeemcache gebruiken." "Hiermee kan de toepassing rechtstreeks de systeemcache openen, aanpassen of wissen. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om downloads en andere toepassingen te verstoren en om toegang te krijgen tot privégegevens." "Downloadmeldingen verzenden." "Hiermee ontvangt u een melding zodra een download is voltooid. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om andere toepassingen die bestanden downloaden, in de war te brengen." "<Zonder titel>" - ", " - " en nog %d" + "," + "en nog %d" "Downloaden is voltooid" "Downloaden is mislukt." diff --git a/res/values-pl/strings.xml b/res/values-pl/strings.xml index 6e77eafc..7cd3e28e 100644 --- a/res/values-pl/strings.xml +++ b/res/values-pl/strings.xml @@ -24,8 +24,8 @@ "Wysyłanie powiadomień o pobraniu." "Umożliwia programowi wysyłanie powiadomień o ukończeniu pobierania. Szkodliwe programy mogą korzystać z tego uprawnienia, aby zakłócić działanie innych programów pobierających pliki." "<Bez nazwy>" - ", " - " i %d innych" + "," + "i %d innych" "Pobieranie zakończone." "Pobieranie nie powiodło się" diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index a76850f2..fb2c5c5c 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -24,8 +24,8 @@ "Отправлять уведомления о загрузках." "Разрешает приложениям отправлять уведомления о завершенных загрузках. Вредоносные приложения могут использовать это, чтобы передавать ложную информацию другим приложениям загрузки файлов." "<Без названия>" - ", " - " и еще %d" + "," + "и еще %d" "Загрузка завершена" "Загрузка не удалась" diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml index 7802b9bd..642a7e09 100644 --- a/res/values-zh-rCN/strings.xml +++ b/res/values-zh-rCN/strings.xml @@ -24,8 +24,8 @@ "发送下载通知。" "允许应用程序发送关于已完成下载的通知。恶意应用程序可以使用该功能干扰其他下载文件的应用程序。" "<未命名>" - "、 " - " 以及另外 %d 个" + "、" + "以及另外 %d 个" "下载完成" "下载不成功" diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml index 0bf222bc..eeb4ea80 100644 --- a/res/values-zh-rTW/strings.xml +++ b/res/values-zh-rTW/strings.xml @@ -24,8 +24,8 @@ "傳送下載通知。" "下載完成時,允許應用程式送出通知。惡意程式可使用此功能干擾其他正在下載檔案的應用程式。" "(未命名)" - ", " - " 還有 %d 項下載" + "," + "還有 %d 項下載" "下載已完成。" "下載失敗" -- cgit v1.2.3 From 1edb39f280d23b3a87db45b63c2f26850d68eafe Mon Sep 17 00:00:00 2001 From: The Android Open Source Project Date: Tue, 3 Mar 2009 18:28:53 -0800 Subject: auto import from //depot/cupcake/@135843 --- Android.mk | 11 - AndroidManifest.xml | 52 - MODULE_LICENSE_APACHE2 | 0 NOTICE | 190 --- docs/index.html | 1205 -------------------- .../status_bar_ongoing_event_progress_bar.xml | 109 -- res/values-cs/strings.xml | 31 - res/values-de/strings.xml | 31 - res/values-es/strings.xml | 31 - res/values-fr/strings.xml | 31 - res/values-it/strings.xml | 31 - res/values-ja/strings.xml | 31 - res/values-ko/strings.xml | 31 - res/values-nb/strings.xml | 32 - res/values-nl/strings.xml | 31 - res/values-pl/strings.xml | 31 - res/values-ru/strings.xml | 31 - res/values-zh-rCN/strings.xml | 31 - res/values-zh-rTW/strings.xml | 31 - res/values/strings.xml | 119 -- src/com/android/providers/downloads/Constants.java | 151 --- .../providers/downloads/DownloadFileInfo.java | 34 - .../android/providers/downloads/DownloadInfo.java | 212 ---- .../providers/downloads/DownloadNotification.java | 300 ----- .../providers/downloads/DownloadProvider.java | 731 ------------ .../providers/downloads/DownloadReceiver.java | 159 --- .../providers/downloads/DownloadService.java | 879 -------------- .../providers/downloads/DownloadThread.java | 710 ------------ src/com/android/providers/downloads/Helpers.java | 793 ------------- 29 files changed, 6059 deletions(-) delete mode 100644 Android.mk delete mode 100644 AndroidManifest.xml delete mode 100644 MODULE_LICENSE_APACHE2 delete mode 100644 NOTICE delete mode 100644 docs/index.html delete mode 100644 res/layout/status_bar_ongoing_event_progress_bar.xml delete mode 100644 res/values-cs/strings.xml delete mode 100644 res/values-de/strings.xml delete mode 100644 res/values-es/strings.xml delete mode 100644 res/values-fr/strings.xml delete mode 100644 res/values-it/strings.xml delete mode 100644 res/values-ja/strings.xml delete mode 100644 res/values-ko/strings.xml delete mode 100644 res/values-nb/strings.xml delete mode 100644 res/values-nl/strings.xml delete mode 100644 res/values-pl/strings.xml delete mode 100644 res/values-ru/strings.xml delete mode 100644 res/values-zh-rCN/strings.xml delete mode 100644 res/values-zh-rTW/strings.xml delete mode 100644 res/values/strings.xml delete mode 100644 src/com/android/providers/downloads/Constants.java delete mode 100644 src/com/android/providers/downloads/DownloadFileInfo.java delete mode 100644 src/com/android/providers/downloads/DownloadInfo.java delete mode 100644 src/com/android/providers/downloads/DownloadNotification.java delete mode 100644 src/com/android/providers/downloads/DownloadProvider.java delete mode 100644 src/com/android/providers/downloads/DownloadReceiver.java delete mode 100644 src/com/android/providers/downloads/DownloadService.java delete mode 100644 src/com/android/providers/downloads/DownloadThread.java delete mode 100644 src/com/android/providers/downloads/Helpers.java diff --git a/Android.mk b/Android.mk deleted file mode 100644 index 82f0d585..00000000 --- a/Android.mk +++ /dev/null @@ -1,11 +0,0 @@ -LOCAL_PATH:= $(call my-dir) -include $(CLEAR_VARS) - -LOCAL_MODULE_TAGS := user development - -LOCAL_SRC_FILES := $(call all-subdir-java-files) - -LOCAL_PACKAGE_NAME := DownloadProvider -LOCAL_CERTIFICATE := media - -include $(BUILD_PACKAGE) diff --git a/AndroidManifest.xml b/AndroidManifest.xml deleted file mode 100644 index a7d424a9..00000000 --- a/AndroidManifest.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2 deleted file mode 100644 index e69de29b..00000000 diff --git a/NOTICE b/NOTICE deleted file mode 100644 index c5b1efa7..00000000 --- a/NOTICE +++ /dev/null @@ -1,190 +0,0 @@ - - Copyright (c) 2005-2008, The Android Open Source Project - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index a073a004..00000000 --- a/docs/index.html +++ /dev/null @@ -1,1205 +0,0 @@ - - - - Download Provider - - - -
-

Download Provider

-

-

Contents

-

-

-

-

-


-

-

High-level requirements

- -

-

Requirements for Android

-

- - - - - - - - - - - - -
Req# Description Detailed Requirements Status
DLMGR_A_1 The Download Manager MUST satisfy the basic download needs of OTA Updates.   YES done in 1.0
DLMGR_A_2 The Download Manager MUST satisfy the basic download needs of Market.   YES done in 1.0
DLMGR_A_3 The Download Manager MUST satisfy the basic download needs of Gmail.   YES done in 1.0
DLMGR_A_4 The Download Manager MUST satisfy the basic download needs of the Browser.   YES done in 1.0
DLMGR_A_5 Downloads MUST happen and continue in the background, independently of the application in front.   YES done in 1.0
DLMGR_A_6 Downloads MUST be reliable even on unreliable network connections, within the capabilities of the underlying protocol and of the server.   YES done in 1.0
DLMGR_A_7 User-accessible files MUST be stored on the external storage card, and only files that are explicitly supported by an installed application must be downloaded.   YES done in 1.0
DLMGR_A_8 OMA downloads SHOULD be supported.   NO deferred beyond Cupcake (not enough time)
DLMGR_A_9 The Download Manager SHOULD only download when using high-speed (3G/wifi) links, or only when not roaming (if that can be detected).   NO deferred beyond Cupcake (not enough time)
DLMGR_A_10 Downloads SHOULD be user-controllable (if allowed by the initiating application), including pause, resume, and restart of failed downloads. 4001 NO deferred beyond Cupcake (not enough time, need precise specifications)
-

-

Requirements for Cupcake

-

- - - - - - - - - - - -
Req# Description Detailed Requirements Status
DLMGR_C_1 The Download Manager SHOULD resume downloads where the socket got cleanly closed while the download was incomplete (common behavior on proxies and Google servers) 2005 YES done in Cupcake
DLMGR_C_2 The Download Manager SHOULD retry/resume downloads instead of aborting when the server returns a HTTP code 503 2006 YES done in Cupcake
DLMGR_C_3 The Download Manager SHOULD randomize the retry delay 2007 YES done in Cupcake
DLMGR_C_4 The Download Manager SHOULD use the retry-after header (delta-seconds) for 503 responses 2008 YES done in Cupcake
DLMGR_C_5 The Download Manager MAY hide columns that aren't strictly necessary 1010 YES done in Cupcake
DLMGR_C_6 The Download Manager SHOULD allow the initiating app to pause an ongoing download 1011 YES done in Cupcake
DLMGR_C_7 The Download Manager SHOULD not display multiple notification icons for completed downloads. 4002 NO deferred beyond Cupcake (no precise specifications, need framework support)
DLMGR_C_8 The Download Manager SHOULD delete old files from /cache 3006 NO deferred beyond Cupcake (no precise specifications)
DLMGR_C_9 The Download Manager SHOULD handle redirects 2009 YES done in Cupcake
-

-

Requirements for Donut

-

- - -
Req# Description Detailed Requirements Status
-

-

Technology Evaluation

- -

-ALSO See also future directions for possible additional technical changes. -

-

Possible scope for Cupcake

-

-Because there is no testing environment in place in the 1.0 code, and because the schedule between -1.0 and Cupcake doesn't leave enough time to develop a testing environment solid enough to be able -to test the database upgrades from 1.0 database scheme to a new scheme, any work done in Cupcake will -have to work within the existing 1.0 database scheme. -

-

Reducing the number of classes

-

-Each class in the system has a measurable RAM cost (because of the associated Class objects), -and therefore reducing the number of classes when possible or relevant can reduce the memory -requirements. That being said, classes that extend system classes and are necessary for the -operation of the download manager can't be removed. -

- - - - - - - - - - - - - - - - - - -
Class Comments
com.android.providers.downloads.Constants Only contains constants, can be merged into another class.
com.android.providers.downloads.DownloadFileInfo Should be merged with DownloadInfo.
com.android.providers.downloads.DownloadInfo Once we only store information in RAM about downloads that are explicitly active, can be merged with DownloadThread.
com.android.providers.downloads.DownloadNotification Looks like it could be merged with DownloadProvider or DownloadService.
com.android.providers.downloads.DownloadNotification.NotificationItem Can probably be eliminated by using queries intelligently.
com.android.providers.downloads.DownloadProvider Extends ContentProvider, can't be eliminated.
com.android.providers.downloads.DownloadProvider.DatabaseHelper Can probably be eliminated by re-implementing by hand the logic of SQLiteOpenHelper.
com.android.providers.downloads.DownloadProvider.ReadOnlyCursorWrapper Can be eliminated once Cursor is read-only system-wide.
com.android.providers.downloads.DownloadReceiver Extends BroadcastReceiver, can't be eliminated.
com.android.providers.downloads.DownloadService Extends Service, unlikely that this can be eliminated. TBD.
com.android.providers.downloads.DownloadService.DownloadManagerContentObserver Extends ContentObserver, can be eliminated if the download manager can be re-architected to not depend on ContentObserver any more.
com.android.providers.downloads.DownloadService.MediaScannerConnection Can probably be merged into another class.
com.android.providers.downloads.DownloadService.UpdateThread Can probably be made to implement Runnable instead and merged into another class, can be eliminated if the download manager can be re-architected to not depend on ContentObserver any more.
com.android.providers.downloads.DownloadThread Can probably be made to implement Runnable instead. Unclear whether this can be eliminated as we will probably need one object that represents an ongoing download (unless the entire state can be stored on the stack with primitive types, which is unlikely).
com.android.providers.downloads.Helpers Can't be instantiated, can be merged into another class.
com.android.providers.downloads.Helpers.Lexer Keeps state about an ongoing lex, can probably be merged into another class by making the lexer synchronized, since the operation is short-lived.
-

-

Reducing the list of visible columns

-

-Security in the download provider is primarily enforced with two separate mechanisms: -

-

    -
  • Column restrictions, such that only a small number of the download provider's columns can be read or queried by applications. -
  • -
  • UID restrictions, such that only the application that initiated a download can access information about that download. -
  • -
-

-The first mechanism is expected to be fairly robust (the implementation is quite simple, based on projection maps, which are highly -structured), but the second one relies on arbitrary strings (URIs and SQL fragments) passed by applications and is therefore at a -higher risk of being compromised. Therefore, sensitive information stored in unrestricted columns (for which the first mechanism -doesn't apply) is at a greater risk than other information. -

-Here's the list of columns that can currently be read/queried, with comments: -

- - - - - - - - - - - - - - -
Column Notes
_ID Needs to be visible so that the app can uniquely identify downloads. No security concern: those numbers are sequential and aren't hard to guess.
_DATA Probably should not be visible to applications. WARNING Security concern: This holds filenames, including those of private files. While file permissions are supposed to kick in and protect the files, hiding private filenames deeper in would probably be a reasonable idea.
MIMETYPE Needs to be visible so that app can display the icon matching the mime type. Intended to be visible by 3rd-party download UIs. TODO Security TBD before we implement support for 3rd-party UIs.
VISIBILITY Needs to be visible in case an app has both visible and invisible downloads. No obvious security concern.
STATUS Needs to be visible (1004). No obvious security concern.
LAST_MODIFICATION Needs to be visible, e.g. so that apps can sort downloads by date of last activity, or discard old downloads. No obvious security concern.
NOTIFICATION_PACKAGE Allows individual apps running under shared UIDs to identify their own downloads. No security concern: can be queried through package manager.
NOTIFICATION_CLASS See NOTIFICATION_PACKAGE.
TOTAL_BYTES Needs to be visible so that the app can display a progress bar. No obvious security concern. Intended to be visible by 3rd-party download UIs.
CURRENT_BYTES See TOTAL_BYTES.
TITLE Intended to be visible by 3rd-party download UIs. TODO Security and Privacy TBD before we implement support for 3rd-party UIs.
DESCRIPTION See TITLE.
-

-

Hiding the URI column

-

-The URI column is visible to the initiating application, which is a mild security risk. It should be hidden, but the OTA update mechanism relies on it to check duplicate downloads and to display the download that's currently ongoing in the settings app. If another string column was exposed to the initiating applications, the OTA update mechanism could use that one, and URI could then be hidden. For Cupcake, without changing the database schema, the ENTITY column could be re-used as it's currently unused. -

-

Handling redirects

-

-There are two important aspects to handle redirects: -

-

    -
  • Storing the intermediate URIs in the provider. -
  • -
  • Protecting against redirect loops. -
  • -
-

-If the URI column gets hidden, it could be used to store the intermediate URIs. After 1.0 the only available integer columns were METHOD and CONTROL. CONTROL was re-exposed to applications and can't be used. METHOD is slated to be re-used for 503 retry-after delays. It could be split into two halves, one for retry-after and one for the redirect count. It would make more sense to count the redirect loop with FAILED_CONNECTIONS, but since there's already quite some code using it it'd take a bit more effort. Ideally handling of redirects would be delayed until a future release, with a cleanup of the database schema (going along with the cleanup of the handling of filenames). -

-Because of the pattern used to read/write DownloadInfo and DownloadProvider, it's impractical to store multiple small integers into a large one. Therefore, since there are no integer columns left in the database, redirects will have to wait beyond Cupcake. -

-

ContentProvider for download UI

-

-In order to allow a UI that can "see" all the relevant downloads, there'll need to be a separate URI (or set of URIs) in the content provider: trying to use the exact same URIs for regular download control and for UI purposes (distinguishing them based on the permissions of the caller) will break down if a same app (or actually a same UID) tries to do both. It'll also break down if the system process tries to do regular download activities, since it has all permissions. -

-Beyond that, there's little technical challenge: there are already mechanisms in place to restrict the list of columns that can be inserted, queried and updated (inserting of course makes no sense through the UI channel), they just need to be duplicated for the case of the UI. The download provider also knows how to check the permissions of its caller, there isn't anything new here. -

-

Getting rid of OTHER_UID

-

-Right now OTHER_UID is used by checkin/update to allow the settings app to display the name of an ongoing OTA update, and by Market to allow the system to install the new apks. It is however a dangerous feature, at least because it touches a part of the code that is critical to the download manager security (separation of applications). -

-Getting rid of OTHER_UID would be beneficial for the download manager, but the existing functionality has to be worked around. At this point, the idea that I consider the most likely would be to have checkin and market implement =ContentProvider= wrappers around their downloads, and expose those content providers to whichever app they want, with whichever security mechanism they wish to have. -

-

Only using SDK APIs.

-

-It'd be good if the download manager could be built against the SDK as much as possible. -

-Here's the list of APIs as of Nov 5 2008 that aren't in the current public API but that are used by the download manager: -

-

-com.google.android.collect.Lists
-android.drm.mobile1.DrmRawContent
-android.media.IMediaScannerService
-android.net.http.AndroidHttpClient
-android.os.FileUtils
-android.provider.DrmStore
-
-

- - -

- -

- - -

- -

-

Schedule

-

- -

-

    -
  • No future milestones currently defined -
  • -
-

-

Detailed Requirements

- -

- -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Req# History Status Feature Description Notes
1xxx N/A   API    
1001 1.0 YES   Download Manager API The download manager provides an API that allows applications to initiate downloads.  
1002 1.0 YES   Cookies The download manager API allows applications to pass cookies to the download manager.  
1003 1.0 YES   Security The download manager provides a mechanism that prevents arbitrary applications from accessing meta-data about current and past downloads. In 1.0, known holes between apps
1004 1.0 YES   Status to Initiator The download manager allows the application initiating a download to query the status of that download.  
1005 1.0 YES   Cancel by Initiator The download manager allows the application initiating a download to cancel that download.  
1006 1.0 YES   Notify Initiator The download manager notifies the application initiating a download when the download completes (with success or failure)  
1007 1.0 YES   Fire and Forget The download manager does not rely on the initiating application when saving the file to a shared filesystem area  
1008 1.0 YES   Short User-Readable Description The download manager allows the initiating application to optionally provide a user-readable short description of the download  
1009 1.0 YES   Long User-Readable Description The download manager allows the initiating application to optionally provide a user-readable full description of the download  
1010 Cupcake YES Cupcake P3 YES Restrict column access The download provider doesn't allow access to columns that aren't strictly necessary.  
1011 Cupcake YES Cupcake P2 YES Pause downloads The download provider allows the application initiating a download to pause that download.  
2xxx N/A   HTTP    
2001 1.0 YES   HTTP Support The download manager supports all the features of HTTP 1.1 (RFC 2616) that are relevant to file downloads. Codes 3xx weren't considered relevant when those requirements were written
2002 1.0 YES   Resume Downloads The download manager resumes downloads that get interrupted.  
2003 1.0 YES   Flaky Downloads The download manager has mechanism that prevent excessive retries of downloads that consistently fail or get interrupted.  
2004 1.0 YES   Resume after Reboot The download manager resumes downloads across device reboots.  
2005 Cupcake YES Cupcake P2 YES Resume after socket closed The download manager resumes incomplete downloads after the socket gets cleanly closed This is necessary in order to reliably download through GFEs, though it pushes us further away from being able to download from servers that don't implement pipelining.
2006 Cupcake YES Cupcake P2 YES Resume after 503 The download manager resumes or retries downloads when the server returns an HTTP code 503  
2007 Cupcake YES Cupcake P2 YES Random retry delay The download manager uses partial randomness when retrying downloads on an exponential backoff pattern.  
2008 Cupcake YES Cupcake P2 YES Retry-after delta-seconds The download manager uses the retry-after header in a 503 response to decide when to retry the request Handling of absolute dates will be covered by a separate requirement.
2009 Cupcake YES Cupcake P2 YES Redirects The download manager handles common redirects.  
25xx N/A   HTTP/Conditions    
3xxx N/A   Storage    
3001 1.0 YES   File Storage The download manager stores the results of downloads in persistent storage.  
3002 1.0 YES   Max File Size The download manager is able to handle large files (order of magnitude: 50MB)  
3003 1.0 YES   Destination File Permissions The download manager restricts access to the internal storage to applications with the appropriate permissions  
3004 1.0 YES   Initiator File Access The download manager allows the initiating application to access the destination file  
3005 1.0 YES   File Types The download manager does not save files that can't be displayed by any currently installed application  
3006 Cupcake NO Cupcake P3 NO Old Files in /cache The download manager deletes old files in /cache  
35xx N/A   Storage/Filename    
4xxx N/A   UI    
4001 1.0 NO   Download Manager UI The download manager provides a UI that lets user get information about current downloads and control them. Didn't get spec on time to be able to even consider it.
4002 Cupcake NO Cupcake P2 NO Single Notification Icon The download manager displays a single icon in the notification bar regardless of the number of ongoing and completed downloads. No spec in Cupcake timeframe.
5xxx N/A   MIME    
52xx N/A   MIME/DRM    
5201 1.0 YES   DRM The download manager respects the DRM information it receives with the responses  
54xx N/A   MIME/OMA    
60xx N/A   Misc    
65xx N/A   Misc/Browser    
-

-

System Architecture

- -

-

-+----------------------+    +--------------------------------------+    +-------------+
-|                      |    |                                      |    |             |
-|   Download Manager   |    |  Browser / Gmail / Market / Updater  |    |  Viewer App |
-|                      |    |                                      |    |             |
-+----------------------+    +--------------------------------------+    +-------------+
-    ^    |    ^                                             ^                ^
-    |    |    |                                             |                |
-    |    |    |                                             |                |
-    |    |    |      +---------------------------+          |                |
-    |    |    |      |                           |          |                |
-    |    |    |      |                           |          |                |
-    |    |    +-------- - - - - - - - - - - - - ------------+                |
-    |    |           |                           |                           |
-    |    |           |                           |                           |
-    |    +------------- - - - - - - - - - - - - -----------------------------+
-    |                |                           |
-    |                |                           |
-    +--------------->|     Android framework     |
-                     |                           |
-                     |                           |
-                     +---------------------------+
-
-

-

-          Application                        Download Manager                         Viewer App
-               |                                     |                                     |
-               |         initiate download           |                                     |
-               |------------------------------------>|                                     |
-               |<------------------------------------|                                     |
-               |        content provider URI         |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |           query download            |                                     |
-               |------------------------------------>|                                     |
-               |<------------------------------------|                                     |
-               |              Cursor                 |                                     |
-               |                                     |                                     |
-               |       register ContentObserver      |                                     |
-               |------------------------------------>|                                     |
-               |                                     |                                     |
-               |     ContentObserver notification    |                                     |
-               |<------------------------------------|                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |    intent "notification clicked"    |                                     |
-               |<------------------------------------|                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |      intent "download complete"     |                                     |
-               |<------------------------------------|                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |            intent "view"            |
-               |                                     |------------------------------------>|
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |           update download           |                                     |
-               |------------------------------------>|                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |         open downloaded file        |                                     |
-               |------------------------------------>|                                     |
-               |<------------------------------------|                                     |
-               |         ParcelFileDescriptor        |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |           delete download           |                                     |
-               |------------------------------------>|                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               |                                     |                                     |
-               v                                     v                                     v
-
-

-

Internal Product Dependencies

-

-

    -
  • [reverse dependency] GMail depends on the download manager to download attachments. -
  • -
  • [reverse dependency] OTA Update depends on the download manager to download system images. -
  • -
  • [reverse dependency] Vending Machine depends on the download manager to download content. -
  • -
  • [reverse dependency] Browser depends on the download manager to download non-browsable. -
  • -
  • Download Manager depends on a notification system to let the user know when downloads complete or otherwise require attention. -
  • -
  • Download Manager depends on a mechanism to share files with another app (letting apps access its files, or accessing apps' files). -
  • -
  • Download Manager depends on the ability to associate individual downloads with separate applications and to restrict apps to only access their own downloads. -
  • -
  • Download Manager depends on an HTTP stack that predictably processes all relevant kinds of HTTP requests and responses. -
  • -
  • Download Manager depends on a connectivity manager that reports accurate information about the status of the different data connections. -
  • -
-

-

Interface Documentation

- -

-WARNING Since none of those APIs are public, they are all subject to change. If you're working in the Android source tree, do NOT use the explicit values, ONLY use the symbolic constants, unless you REALLY know what you're doing and are willing to deal with the consequences; you've been warned. -

-The various constants that are meant to be used by applications are all defined in the android.provider.Downloads class. Whenever possible, the constants should be used instead of the explicit values. -

-

Permissions

-

- - - - - - -
Constant name Permission name Access restrictions Description
Downloads.PERMISSION_ACCESS "android.permission.ACCESS_DOWNLOAD_MANAGER" Signature or System Applications that want to access the Download Manager MUST have this permission.
Downloads.PERMISSION_ACCESS_ADVANCED "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED" Signature or System This permission protects some legacy APIs that new applications SHOULD NOT use.
Downloads.PERMISSION_CACHE "android.permission.ACCESS_CACHE_FILESYSTEM" Signature This permission allows an app to access the /cache filesystem, and is only needed by the Update code. Other applications SHOULD NOT use this permission
Downloads.PERMISSION_SEND_INTENTS "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS" Signature The download manager holds this permission, and the receivers through which applications get intents of completed downloads SHOULD require this permission from the sender
-

-

Content Provider

-

-The primary interface that applications use to communicate with the download manager is exposed as a ContentProvider. -

-

URIs

-

-The URIs for the Content Provider are: -

- - - - -
Constant name URI Description
Downloads.CONTENT_URI Uri.parse("content://downloads/download") The URI of the whole Content Provider, used to insert new rows, or to query all rows.
N/A ContentUris.withAppendedId(CONTENT_URI, <id>) The URI of an individual download. <id> is the value of the Download._ID column
-

-

Columns

-

-The following columns are available: -

- - - - - - - - - - - - - - - - - - - - - - - - - -
Constant name Column name SQL Type Access Description Notes
Downloads._ID "_id" Integer Read   Inherited from BaseColumns._ID.
Downloads.URI "uri" Text Init   Used to be readable.
Downloads.APP_DATA "entity" Text Init/Read/Modify   Actual column name will change in the future.
Downloads.NO_INTEGRITY "no_integrity" Boolean Init   Used to be readable.
Downloads.FILENAME_HINT "hint" Text Init   Used to be readable.
Downloads._DATA "_data" Text Read   Used to be Downloads.FILENAME and "filename".
Downloads.MIMETYPE "mimetype" Text Init/Read    
Downloads.DESTINATION "destination" Integer Init   See Destination codes for details of legal values. Used to be readable.
Downloads.VISIBILITY "visibility" Integer Init/Read/Modify   See Visibility codes for details of legal values.
Downloads.CONTROL "control" Integer Init/Read/Modify   See Control codes for details of legal values.
Downloads.STATUS "status" Integer Read   See Status codes for details of possible values.
Downloads.LAST_MODIFICATION "lastmod" Bigint Read    
Downloads.NOTIFICATION_PACKAGE "notificationpackage" Text Init/Read    
Downloads.NOTIFICATION_CLASS "notificationclass" Text Init/Read    
Downloads.NOTIFICATION_EXTRAS "notificationextras" Text Init    
Downloads.COOKIE_DATA "cookiedata" Text Init    
Downloads.USER_AGENT "useragent" Text Init    
Downloads.REFERER "referer" Text Init    
Downloads.TOTAL_BYTES "total_bytes" Integer Read   Might gain Init access in the future.
Downloads.CURRENT_BYTES "current_bytes" Integer Read    
Downloads.OTHER_UID "otheruid" Integer Init   Requires the android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED permission. Used to be readable and writable. Might disappear entirely if possible.
Downloads.TITLE "title" String Init/Read/Modify    
Downloads.DESCRIPTION "description" String Init/Read/Modify    
-

-

Destination Values

-

- - - - - -
Constants name Constant value Description Notes
Downloads.DESTINATION_EXTERNAL 0 Saves the file to the SD card. Default value. Fails is SD card is not present.
Downloads.DESTINATION_CACHE_PARTITION 1 Saves the file to the internal cache partition. Requires the "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED" permission
Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE 2 Saves the file to the internal cache partition. The download can get deleted at any time by the download manager when it needs space.
-

-

Visibility Values

-

- - - - - -
Constants name Constant value Description Notes
Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED 0 The download is visible in download UIs, and it shows up in the notification area during download and after completion. Default value for external downloads.
Downloads.VISIBILITY_VISIBLE 1 The download is visible in download UIs, and it shows up in the notification area during download but not after completion.  
Downloads.VISIBILITY_HIDDEN 2 The download is hidden from download UIs and doesn't show up in the notification area. Default value for internal downloads.
-

-

Control Values

-

- - - - -
Constants name Constant value Description Notes
Downloads.CONTROL_RUN 0 The download is allowed to run. Default value.
Downloads.CONTROL_PAUSED 0 The download is paused.  
-

-

Status Values

-

- - - - - - - - - - - - - - - - - - - - -
Constants name Constant value Description Notes
Downloads.STATUS_PENDING 190 Download hasn't started.  
Downloads.STATUS_PENDING_PAUSED 191 Download hasn't started and can't start immediately (network unavailable, paused by user). Not currently used.
Downloads.STATUS_RUNNING 192 Download has started and is running  
Downloads.STATUS_RUNNING_PAUSED 193 Download has started, but can't run at the moment (network unavailable, paused by user).  
Downloads.STATUS_SUCCESS 200 Download completed successfully.  
Downloads.STATUS_BAD_REQUEST 400 Couldn't initiate the request, or server response 400.  
Downloads.STATUS_NOT_ACCEPTABLE 406 No handler to view the file (external downloads), or server response 406. External downloads are meant to be user-visible, and are aborted if there's no application to handle the relevant MIME type.
Downloads.STATUS_LENGTH_REQUIRED 411 The download manager can't know the length of the download. Because of the unreliability of cell networks, the download manager only performs downloads when it can verify that it has received all the data for a download, except if the initiating app sets the Downloads.NO_INTEGRITY flag.
Downloads.STATUS_PRECONDITION_FAILED 412 The download manager can't resume an interrupted download, because it didn't receive enough information from the server to be able to resume.  
Downloads.STATUS_CANCELED 490 The download was canceled by a cause outside the Download Manager. Formerly known as Downloads.STATUS_CANCELLED. Might be impossible to observe in 1.0.
Downloads.STATUS_UNKNOWN_ERROR 491 The download was aborted because of an unknown error. Formerly known as Downloads.STATUS_ERROR. Typically the result of a runtime exception that is not explicitly handled.
Downloads.STATUS_FILE_ERROR 492 The download was aborted because the data couldn't be saved. Most commonly happens when the filesystem is full.
Downloads.STATUS_UNHANDLED_REDIRECT 493 The download was aborted because the server returned a redirect code 3xx that the download manager doesn't handle. The download manager currently handles 301, 302 and 307.
Downloads.STATUS_TOO_MANY_REDIRECTS 494 The download was aborted because the download manager received too many redirects while trying to find the actual file.  
Downloads.STATUS_UNHANDLED_HTTP_CODE 495 The download was aborted because the server returned a status code that the download manager doesn't handle. Standard codes 3xx, 4xx and 5xx don't trigger this.
Downloads.STATUS_HTTP_DATA_ERROR 496 The download was aborted because of an unrecoverable error trying to get data over the network. Typically this happens when the download manager received several I/O Exceptions in a row while the network is available and without being able to download any data.
  4xx standard HTTP/1.1 4xx codes returned by the server are used as-is. Don't rely on non-standard values being passed through, especially the higher values that would collide with download manager codes.
  5xx standard HTTP/1.1 5xx codes returned by the server are used as-is. Don't rely on non-standard values being passed through.
-

-

Status Helper Functions

-

- - - - - - - - - -
Function signature Description
public static boolean Downloads.isStatusInformational(int status) Returns whether the status code matches a download that hasn't completed yet.
public static boolean Downloads.isStatusSuspended(int status) Returns whether the download hasn't completed yet but isn't currently making progress.
public static boolean Downloads.isStatusSuccess(int status) Returns whether the download successfully completed.
public static boolean Downloads.isStatusError(int status) Returns whether the download failed.
public static boolean Downloads.isStatusClientError(int status) Returns whether the download failed because of a client error.
public static boolean Downloads.isStatusServerError(int status) Returns whether the download failed because of a server error.
public static boolean Downloads.isStatusCompleted(int status) Returns whether the download completed (with no distinction between success and failure).
-

-

Intents

-

-The download manager sends an intent broadcast Downloads.DOWNLOAD_COMPLETED_ACTION when a download completes. -

-The download manager sends an intent broadcast Downloads.NOTIFICATION_CLICKED_ACTION when the user clicks a download notification that doesn't match a download that can be opened (e.g. because the notification is for several downloads at a time, or because it's for an incomplete download, or because it's for a private download). -

-The download manager starts an activity with Intent.ACTION_VIEW when the user clicks a download notification that matches a download that can be opened. -

-

Differences between 1.0 and Cupcake

-

-WARNING These are the differences for apps built from source in the Android source tree, i.e. they don't cover any of the cases of binary incompatibility. -

-

    -
  • Cursors returned by the content provider are now read-only. -
  • -
  • SQL "where" statements are now verified and must follow a rigid syntax (the most visible aspect being that all parameters much be single-quoted). -
  • -
  • Columns and constants that were unused or ineffective are gone: METHOD, NO_SYSTEM_FILES, DESTINATION_DATA_CACHE, OTA_UPDATE. -
  • -
  • OTHER_UID and DESTINATION_CACHE_PARTITION require android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED. -
  • -
  • The list of columns that can be queried and read is limited: _ID, APP_DATA, _DATA, MIMETYPE, CONTROL, STATUS, LAST_MODIFICATION, NOTIFICATION_PACKAGE, NOTIFICATION_CLASS, TOTAL_BYTES, CURRENT_BYTES, TITLE, DESCRIPTION. -
  • -
  • The list of columns that can be initialized by apps is limited: URI, APP_DATA, NO_INTEGRITY, FILENAME_HINT, MIMETYPE, DESTINATION, VISIBILITY, CONTROL, STATUS, LAST_MODIFICATION, NOTIFICATION_PACKAGE, NOTIFICATION_CLASS, NOTIFICATION_EXTRAS, COOKIE_DATA, USER_AGENT, REFERER, OTHER_UID, TITLE, DESCRIPTION. -
  • -
  • The list of columns that can be updated by apps is limited: APP_DATA, VISIBILITY, CONTROL, TITLE, DESCRIPTION. -
  • -
  • Downloads to the SD card default to have notifications that are visible after completion, internal downloads default to notifications that are always hidden. -
  • -
  • The constant FILENAME was renamed Downloads._DATA. -
  • -
  • Downloads can be paused and resumed by writing to the CONTROL column. Downloads.CONTROL_RUN (Default) makes the download go, Downloads.CONTROL_PAUSED pauses it. -
  • -
  • New column APP_DATA that is untouched by the download manager, used to store app-specific info about the downloads. -
  • -
  • Minor differences unlikely to affect applications: -
      -
    • The notification class/package must now match the UID. -
    • -
    • The backdoor to see the entire provider (which was intended to implement UIs) is gone. -
    • -
    • Private column names were removed from the public API. -
    • -
    -
  • -
-

-

Writing code that works on both the 1.0 and Cupcake versions of the download manager.

-

-If you're not 100% sure that you need to be reading this chapter, don't read it. -

-Basic rule: don't use features that only exist in one of the two implementations (POST, downloads to /data...). -

-Also, don't use columns in 1.0 that are protected or hidden in Cupcake. -

-Unfortunately, that's not always entirely possible. -

-Areas of concern: -

    -
  • Some columns were renamed. FILENAME became Downloads._DATA ("_data"), and ENTITY became APP_DATA ("entity"). -
      -
    • The difference can be used to distinguish between 1.0 and Cupcake, though reflection. -
    • -
    • The difference prevents from using any of the symbolic constants directly in source code: if the same binary wants to run on both 1.0 and Cupcake, it will have to hard-code the values of those constants or use reflection to get to them. -
    • -
    -
  • -
  • URI column accessible in 1.0 but protected in Cupcake. Code that relies on being able to re-read its URI should be using APP_DATA in Cupcake, but that column doesn't exist as such in 1.0. -
      -
    • If the code detects that it's running on Cupcake, write URI to APP_DATA in addition to URI, and query and read from the appropriate column. -
    • -
    • Since the underlying column for APP_DATA exists in both 1.0 and Cupcake even though it has different names, it can actually be used in both cases (see note above about renamed columns). -
    • -
    -
  • -
  • Some of the error codes have been renumbered. STATUS_UNHANDLED_HTTP_CODE and STATUS_HTTP_DATA_ERROR were bumped up from 494 and 495 to 495 and 496. -
  • -
  • Backward compatibility is not guaranteed: the download manager APIs weren't meant to be backward compatible yet. As such it's impossible to guarantee that code that uses the Cupcake download manager will be binary-compatible with future versions. -
      -
    • I intend to eventually change the column name for APP_DATA to "app_data". Because of that, code should use reflection to get to that name instead of hard-coding "entity", so that it always gets the right value for the string. -
    • -
    • I intend to refine the handling of filenames and content URIs, exposing separate columns for situations where a download can be accessed both as a file and through a content URI (e.g. stuff that is recognized by the media scanner). Unfortunately at this point this feature isn't clear in my mind. I'd recommend using reflection to look for the Downloads._DATA column, and if it isn't there to look for the FILENAME column (which has the advantage of also dealing with the difference between 1.0 and Cupcake). -
    • -
    • I intend to renumber the error codes, especially those in the 4xx range, and especially those below 490 (which overlap with standard HTTP error codes but will probably be separated). Reflection would improve the probability to getting to them in the future. Unfortunately, the names of the constants are likely to change in the process, in order to disambiguate codes coming from HTTP from those generated locally. I might try to stick to the following pattern: where a constant is currently named STATUS_XXX, its locally-generated version in the future might be named STATUS_LOCAL_XXX while the current constant name might disappear. Using reflection to try to get to the possible new name instead of using the old name might improve the probability of compatibility in the future. That being said, it is critically important to properly handle the full ranges or error codes, especially the 4xx range, as "expected" errors, and it is far preferable to not try to distinguish between those codes at all: use the functions Downloads.isError and Downloads.isClientError to easily recognize those entire ranges. In order of probability, the 1xx range is the second most likely to be affected. -
    • -
    -
  • -
-

-

Functional Specification

-All the details about what the product does. -

-TODO -

-

Release notes for Cupcake

-

-

    -
  • HTTP codes 301, 302, 303 and 307 (redirects) are now supported -
  • -
  • HTTP code 503 is now handled, with support for retry-after in delay-seconds -
  • -
  • Downloads that were cleanly interrupted are now resumed instead of failing -
  • -
  • Applications can now pause their downloads -
  • -
  • Retry delays are now randomized -
  • -
  • Connectivity is now checked on all interfaces -
  • -
  • Downloads with invalid characters in file name can now be saved -
  • -
  • Various security fixes -
  • -
  • Minor API changes (see API differences between 1.0 and Cupcake) -
  • -
-

-

Product Architecture

-How the tasks are split between the different modules that implement the product/feature. -

-TODO To be completed -

- - - - - - - - - - - - - - - - - - -
Class
com.android.providers.downloads.Constants
com.android.providers.downloads.DownloadFileInfo
com.android.providers.downloads.DownloadInfo
com.android.providers.downloads.DownloadNotification
com.android.providers.downloads.DownloadNotification.NotificationItem
com.android.providers.downloads.DownloadProvider extends ContentProvider
com.android.providers.downloads.DownloadProvider.DatabaseHelper extends SQLiteOpenHelper
com.android.providers.downloads.DownloadProvider.ReadOnlyCursorWrapper extends CursorWrapper implements CrossProcessCursor
com.android.providers.downloads.DownloadReceiver extends BroadcastReceiver
com.android.providers.downloads.DownloadService extends Service
com.android.providers.downloads.DownloadService.DownloadManagerContentObserver extends ContentObserver
com.android.providers.downloads.DownloadService.MediaScannerConnection implements ServiceConnection
com.android.providers.downloads.DownloadService.UpdateThread extends Thread
com.android.providers.downloads.DownloadThread extends Thread
com.android.providers.downloads.Helpers
com.android.providers.downloads.Helpers.Lexer
-

-The download manager is built primarily around a ContentProvider and a Service. The ContentProvider part is the front end, i.e. applications communicate with the download manager through the provider. The Service part is the back end, which contains the actual download logic, running as a background process. -

-As a first approach, the provider is essentially a canonical provider backed by a SQLite3 database. The biggest difference between the download provider and a "plain" provider is that the download provider aggressively validates its inputs, for security reasons. -

-The service is a background process that performs the actual downloads as requested by the applications. The service doesn't offer any bindable interface, the service object exists strictly so that the system knows how to prioritize the download manager's process against other processes when memory is tight. -

-Communication between the provider and the service is done through public Android APIs, so that the two components are deeply decoupled (they could in fact run in different processes). The download manager starts the service whenever a change is made that can start or restart a download. The service observes and queries the provider for changes, and updates the provider as the download progresses. -

-

-There are a few secondary classes that provide auxiliary functions. -

-A Receiver listens to several broadcasts. Is receives some system broadcasts when the system boots (so that the download manager can resume downloads that were interrupted when the system was turned off) or when the connectivity changes (so that the download manager can restart downloads that were interrupted when connectivity was lost). It also receives intents when the user selects a download notification. -

-

-Finally, some helper classes provide support functions. -

-Most significantly, DownloadThread is responsible for performing the actual downloads as part of the DownloadService's functionality, while UpdateThread is responsible for updating the DownloadInfo whenever the DownloadProvider data changes. -

-DownloadInfo and DownloadFileInfo hold pure data structures, with little or no actual logic. -

-Lexer takes care of validating the snippets of SQL data that are received from applications, to avoid cases of SQL injection. -

-

-

-

-

-

-The service keeps a copy of the provider data in RAM, so that it can determine what changed in the provider when it receives a change notification through the ContentObserver. That data is kept in an array of DownloadInfo structures. -

-Each DownloadThread performs the operations for a single download (or, more precisely, for a single HTTP transaction). Each DownloadThread is backed by a DownloadInfo object. which is in fact on of the objects kept by the DownloadService. While a download is running, the DownloadService can influence the download by writing data into the relevant DownloadInfo object, and the DownloadThread checks that object at appropriate times during the download. -

-Because the DownloadService updates the DownloadInfo objects asynchronously from everything else (it uses a dedicated thread for that purpose), a lot of care has to be taken when upgrading the DownloadInfo object. In fact, only the DownloadService's updateThread function can update that object, and it should be considered read-only to every other bit of code. Even within the updateThread function, some care must be taken to ensure that the DownloadInfos don't get out of sync with the provider. -

-On the other hand, the DownloadService's updateThread function does upgrade the DownloadInfo when it spawns new DownloadThreads (and in a few more circumstances), and when it does that it must also update the DownloadProvider (or risk seeing its DownloadInfo data get overwritten). -

-Because of all that, all code outside of the DowloadService's updateThread must neither read from DownloadProvider nor write to the DownloadInfo objects under any circumstances. The DownloadService's updateFunction is responsible for copying data from the DownloadProvider to the DownloadInfo objects, and must ensure that the DownloadProvider remains in sync with the information it writes into the DownloadInfo objects. -

-

-

-

Implementation Documentation

-How individual modules are implemented. -

-TODO To be completed -

-

Database formats

-

-Android 1.0, format version 31, table downloads: -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Column Type
"_id" INTEGER PRIMARY KEY AUTOINCREMENT
"uri" TEXT
"method" INTEGER
"entity" TEXT
"no_integrity" BOOLEAN
"hint" TEXT
"otaupdate" BOOLEAN
"_data" TEXT
"mimetype" TEXT
"destination" INTEGER
"no_system" BOOLEAN
"visibility" INTEGER
"control" INTEGER
"status" INTEGER
"numfailed" INTEGER
"lastmod" BIGINT
"notificationpackage" TEXT
"notificationclass" TEXT
"notificationextras" TEXT
"cookiedata" TEXT
"useragent" TEXT
"referer" TEXT
"total_bytes" INTEGER
"current_bytes" INTEGER
"etag" TEXT
"uid" INTEGER
"otheruid" INTEGER
"title" TEXT
"description" TEXT
"scanned" BOOLEAN
-

-Cupcake, format version 100: Same as format version 31. -

-

Future Directions

- -

-WARNING This section is for informative purposes only. -

-

API

-

-

    -
  • Expose Download Manager to 3rd party apps - security, robustness . -
  • -
  • Validate application-provided user agent, cookies, etc... to protect against e.g. header injection. -
  • -
  • Allow trust-and-verify MIME type. -
  • -
  • Extract response string from HTTP responses, extract entity from failed responses -
  • -
  • If app fails to be notified, retry later - don't give up because of a single failure. -
  • -
  • Support data: URIs . -
  • -
  • Download files to app-provided content provider . -
  • -
  • Don't pass HTTP codes above about 490 to the initiating app (figure out what the threshold should be). -
  • -
  • Allow initiating app to specify that it wants wifi-only downloads . -
  • -
  • Provide SQL "where" clauses for the different categories of status codes, matching isStatusXXX(). -
  • -
  • There has to be a mechanism by which old downloads are automatically purged from /cache if there's not enough space . -
  • -
  • Clicking the notification for a completed download should go through the initiating app instead of directly opening the file (but what about fire and forget?). -
  • -
  • Clean up the difference between pending_network (waiting for network) and running_paused (user paused the download). -
  • -
  • Allow any app to access the downloaded file (but no other column) of user-downloaded files . -
  • -
  • Provider should return more errors and throw fewer exceptions if possible. -
  • -
  • Add option to auto-dismiss notifications for completed downloads after a given time . -
  • -
  • Delete filename in case of failure - better handle the separation between filename and content URI. -
  • -
  • Allow the initiating application to specify that it wants to restart downloads from scratch if they're interrupted and can't be resumed . -
  • -
  • Save images directly from browser without re-downloading data . -
  • -
  • Give applications the ability to explicitly specify the full target filename (not just a hint). -
  • -
  • Give applications the ability to download multiple files into multiple set locations as if they were a single "package". -
  • -
  • Give applications the ability to download files only if they haven't been already downloaded. -
  • -
  • Give applications the ability to download files that have already been downloaded only if there's a newer version. -
  • -
  • Set-cookie in the response. -
  • -
  • basic auth . -
  • -
  • app-provided prompts for basic auth, ssl, redirects. -
  • -
  • File should be hidden from initiating application when DRM. -
  • -
  • Delay writing of app-visible filename column until file visible (split user-visible vs private files?). -
  • -
  • Separate locally-generated status codes from standard HTTP codes. -
  • -
  • Allow app to specify it doesn't want to resume downloads across reboots (because they might require additional work). -
  • -
  • Allow app to prioritize user-initiated downloads. -
  • -
  • Allow app to specify length of download (full trust, or trust-and-verify). -
  • -
  • Support POST. -
  • -
  • Support PUT. -
  • -
  • Support plugins for additional protocols and download descriptors. -
  • -
  • Rename columns to have an appropriate COLUMN_ prefix. -
  • -
-

-

HTTP Handling

-

-

    -
  • Fail download immediately on authoritative unresolved hostnames . -
  • -
  • The download manager should use the browser's user-agent by default. -
  • -
  • Redirect with HTTP Refresh headers (download current and target content with non-zero refresh). -
  • -
  • Handle content-encoding header. -
  • -
  • Handle transfer-encoding header. -
  • -
  • Find other ways to validate interrupted downloads (signature, last-mod/if-modified-since) . -
  • -
  • Make downloads time out in case of long time with no activity. -
  • -
-

-

File names

-

-

    -
  • Protect against situations where there's already a "downloads" directory on SD card. -
  • -
  • Deal with filenames with invalid characters. -
  • -
  • Refine the logic that builds filenames to better match desktop browsers - drop the query string. -
  • -
  • URI-decode filenames generated from URIs. -
  • -
  • Better deal with filenames that end in '.'. -
  • -
  • Deal with URIs that end in '/' or '?'. -
  • -
  • Investigate how to better deal with filenames that have multiple extensions. -
  • -
-

-

UI

-

-

    -
  • Prompt for redirects across domains or cancel. -
  • -
  • Prompt for redirects from SSL or cancel. -
  • -
  • Prompt for basic auth or cancel. -
  • -
  • Prompt for SSL with untrusted/invalid/expired certificates or cancel. -
  • -
  • Reduce number of icons in the title bar, possibly as low as 1 (animated if there are ongoing downloads, fixed if all downloads have completed) . -
  • -
  • UI to cancel visible downloads. -
  • -
  • UI to pause visible downloads. -
  • -
  • Reorder downloads. -
  • -
  • View SSL certificates. -
  • -
  • Indicate secure downloads. -
  • -
-

-

Handling of specific MIME types

-

-

    -
  • Parse HTML for redirects with meta tag. -
  • -
  • Handle charsets and transcoding of text files. -
  • -
  • Deal with multiparts. -
  • -
  • Support OMA downloads with DD and data in same multipart, i.e. combined delivery. -
  • -
  • Assume application/octet-stream for http responses with no mime type. -
  • -
  • Download anything if an app supports application/octet-stream. -
  • -
  • Download any text/* if an application supports text/plain. -
  • -
  • Should the media scanner be invoked on DRM downloads? -
  • -
  • Refresh header with timer should be followed if content is not downloadable. -
  • -
  • Support OMA downloads. -
  • -
  • Support MIDP-OTA downloads. -
  • -
  • Support Sprint MCD downloads. -
  • -
  • Sniff content when receiving MIME-types known to be inaccurately sent by misconfigured servers. -
  • -
-

-

Management of downloads based on environment

-

-

    -
  • If the device routinely connects over wifi, delay non-interactive downloads by a certain amount of time in case wifi becomes available -
  • -
  • Turn on wifi if possible -
  • -
  • Fall back to cell when wifi is available but download doesn't proceed -
  • -
  • Be smarter about spurious losses (i.e. exceptions while network appears up) when the active network changes (e.g. turn on wifi while downloading over cell). -
  • -
  • Investigate the use of wifi locks, especially when performing non-resumable downloads. -
  • -
  • Poll network state (and maybe even try to connect) even without notifications from the connectivity manager (in case the notifications go AWOL or get inconsistent) . -
  • -
  • Pause when conditions degrade . -
  • -
  • Pause when roaming. -
  • -
  • Throttle or pause when user is active. -
  • -
  • Pause on slow networks (2G). -
  • -
  • Pause when battery is low. -
  • -
  • Throttle to not overwhelm the link. -
  • -
  • Pause when sync is active. -
  • -
  • Deal with situations where the active connection is down but there's another connection available -
  • -
  • Download files at night when the user is not explicitly waiting. -
  • -
-

-

Management of simultaneous downloads

-

-

    -
  • Pipeline requests on limited number of sockets, run downloads sequentially . -
  • -
  • Manage bandwidth to not starve foreground tasks. -
  • -
  • Run unsized downloads on their own (on a per-filesystem basis) to avoid failing multiple of them because of a full filesystem . -
  • -
-

-

Minor functional changes, edge cases

-

-

    -
  • The database could be somewhat checked when it's opened. -
  • -
  • [DownloadProvider.java] When upgrading the database, the numbering of ids should restart where it left off. -
  • -
  • [DownloadProvider.java] Handle errors when failing to start the service. -
  • -
  • [DownloadProvider.java] Explicitly populate all database columns that have documented default values, investigate whether that can be done at the SQL level. -
  • -
  • [DownloadProvider.java] It's possible that the last update time should be updated by the Sevice logic, not by the content provider. -
  • -
  • When relevant, combine logged messages on fewer lines. -
  • -
  • [DownloadService.java] Trim the database in the provider, not in the service. Notify application when trimming. Investigate why the row count seems off by one. Enforce on an ongoing basis. -
  • -
  • [DownloadThread.java] When download is restarted and MIME type wasn't provided by app, don't re-use MIME type. -
  • -
  • [DownloadThread.java] Deal with mistmatched file data sizes (between database and filesystem) when resuming a download, or with missing files that should be here. -
  • -
  • [DownloadThread.java] Validate that the response content-length can be properly parsed (i.e. presence of a string doesn't guarantee correctness). -
  • -
  • [DownloadThread.java] Be finer-grained with the way file permissions are managed in /cache - don't 0644 everything . -
  • -
  • Truncate files before deleting them, in case they're still open cross-process. -
  • -
  • Restart from scratch downloads that had very little progress . -
  • -
  • Deal with situations where /data is full as it prevents the database from growing (DoS) . -
  • -
  • Wait until file scanned to notify that download is completed. -
  • -
  • Missing some detailed logging about IOExceptions. -
  • -
  • Allow to disable LOGD debugging independently from system setting. -
  • -
  • Pulling the battery during a download corrupts files (lots of zeros written) . -
  • -
  • Should keep a bit of "emergency" database storage to initiate the download of an OTA update, in a file that is pre-allocated whenever possible (how to know it's an OTA update?). -
  • -
  • Figure out how to hook up into dumpsys and event log. -
  • -
  • Use the event log to log download progress. -
  • -
  • Use /cache to stage downloads that eventually go to the sd card, to avoid having sd files open too long in case the use pulls the card and to avoid partial files for too long. -
  • -
  • Maintain per-application usage statistics. -
  • -
  • There might be corner cases where the notifications are slightly off because different notifications might be using PendingIntents that can't be distinguished (differing only by their extras). -
  • -
-

-

Architecture and Implementation

-

-

    -
  • The content:// Uri of individual downloads could be cached instead of being re-built whenever it's needed. -
  • -
  • [DownloadProvider.java] Solidify extraction of id from URI -
  • -
  • [DownloadProvider.java] Use ContentURIs.parseId(uri) to extra the id from various functions. -
  • -
  • [DownloadProvider.java] Use StringBuilder to build the various queries. -
  • -
  • [DownloadService.java] Cache interface to the media scanner service more aggressively. -
  • -
  • [DownloadService.java] Investigate why unbinding from the media scanner service sometimes throws an exception -
  • -
  • [DownloadService.java] Handle exceptions in the service's UpdateThread - mark that there's no thread left. -
  • -
  • [DownloadService.java] At the end of UpdateThread, closing the cursor should be done even if there's an exception. Also log the exception, as we'd be in an inconsistent state. -
  • -
  • [DownloadProvider.java] Investigate whether the download provider should aggressively cache the result of getContext() and getContext().getContentResolver() -
  • -
  • Document the database columns that are most likely to stay unchanged throughout versions, to increase the chance being able to perform downgrades. -
  • -
  • [DownloadService.java] Sanity-check the ordering of the local cache when adding/removing rows. -
  • -
  • [DownloadService.java] Factor the code that checks for DRM types into a separate function. -
  • -
  • [DownloadService.java] Factor the code that notifies applications into a separate function (codepath with early 406 failure) -
  • -
  • [DownloadService.java] Check for errors when spawning download threads. -
  • -
  • [DownloadService.java] Potential race condition when a download completes at the same time as it gets deleted through the content provider - see deleteDownload(). -
  • -
  • [DownloadService.java] Catch all exceptions in scanFile - don't trust a remote process to the point where we'd let it crash us. -
  • -
  • [DownloadService.java] Limit number of attempts to scan a file. -
  • -
  • [DownloadService.java] Keep less data in RAM, especially about completed downloads. Investigating cutting unused columns if necessary -
  • -
  • [DownloadThread.java] Don't let exceptions out of run() - that'd kill the service, which'd accomplish no good. -
  • -
  • [DownloadThread.java] Keep track of content-length responses in a long, not in a string that we keep parsing . -
  • -
  • [DownloadThread.java] Use variable-size buffer to avoid thousands of operations on large downloads -
  • -
  • [Helpers.java] Deal with atomicity of checking/creating file. -
  • -
  • [Helpers.java] Handle differences between content-location separators and filesystem separators. -
  • -
  • Optimize database queries: use projections to reduce number of columns and get constant column numbers. -
  • -
  • Index last-mod date in DB, because of ordered searches. Investigate whether other columns need to be indexed (Hidden?) -
  • -
  • Deal with the fact that sqlite INTEGER matches java long (63-bit) . -
  • -
  • Use a single HTTP client for the entire download manager. -
  • -
  • Could use fewer alarms - currently setting new alarm each time database updated . -
  • -
  • Obsolete columns should be removed from the database . -
  • -
  • Assign relevant names to threads. -
  • -
  • Investigate and handle the different subclasses of IOException appropriately . -
  • -
  • There's potentially a race condition around read-modify-write cycles in the database, between the Service's updateFromProvider thread and the worker threads (and possibly more). Those should be synchronized appropriately, and the provider should be hardened to prevent asynchronous changes to sensitive data (or to synchronize when there's no other way, though I'd rather avoid that) . -
  • -
  • Temporary file leaks when downloads are deleted while the service isn't running . -
  • -
  • Increase priority of updaterThread while in the critical section (to avoid issues of priority inheritance with the main thread). -
  • -
  • Explicitly specify which interface to use for a given download (to get better sync with the connection manager). -
  • -
  • Cancel the requests on more kinds of errors instead of trusting the garbage collector. -
  • -
  • Issues with the fact that parseInt can throw exceptions on invalid server headers. -
  • -
-

-

Code style, refactoring

-

-

    -
  • Fix lint warnings -
  • -
  • Make sure that comments fit in 80 columns to match style guide -
  • -
  • Unify code style when dealing with lines longer than 100 characters -
  • -
  • [Constants.java] constants should be organized by logical groups to improve readability. -
  • -
  • Use fewer internal classes (Helpers, Constants...) . -
  • -
-

-

Browser changes

-

-

    -
  • Move download UI outside of browser, so that browser doesn't need to access the provider. -
  • -
  • Make browser sniff zips and jars to see if they're apks. -
  • -
  • Live handoff of browser-initiated downloads (download in browser, browser update download UI, hand over to download manager on retry). -
  • -
- - diff --git a/res/layout/status_bar_ongoing_event_progress_bar.xml b/res/layout/status_bar_ongoing_event_progress_bar.xml deleted file mode 100644 index d81c42ba..00000000 --- a/res/layout/status_bar_ongoing_event_progress_bar.xml +++ /dev/null @@ -1,109 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/res/values-cs/strings.xml b/res/values-cs/strings.xml deleted file mode 100644 index cbac9ac2..00000000 --- a/res/values-cs/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "Získat přístup ke správci stahování." - "Umožní aplikaci získat přístup ke správci stahování a stahovat pomocí něj soubory. Škodlivé aplikace mohou pomocí tohoto nastavení narušit stahování a získat přístup k soukromým informacím." - "Pokročilé funkce správce stahování." - "Umožňuje aplikaci přístup k pokročilým funkcím správce stahování."\n" Škodlivé aplikace toho mohou využít a narušit stahování nebo získat přístup k "\n" důvěrným informacím." - "Použít mezipaměť systému." - "Umožní aplikaci získat přímý přístup k mezipaměti systému, měnit ji a mazat. Škodlivé aplikace mohou pomocí tohoto nastavení vážně narušit stahování a ostatní aplikace a získat přístup k soukromým datům." - "Odeslat oznámení o stahování." - "Umožní aplikaci odeslat oznámení o dokončení stahování. Škodlivé aplikace mohou pomocí tohoto nastavení zmást jiné aplikace, které stahují soubory." - "<Bez názvu>" - "," - "a ještě %d" - "Stahování bylo dokončeno" - "Stahování bylo neúspěšné" - diff --git a/res/values-de/strings.xml b/res/values-de/strings.xml deleted file mode 100644 index 966ab2fc..00000000 --- a/res/values-de/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "Auf Download-Manager zugreifen" - "Ermöglicht der Anwendung den Zugriff auf den Download-Manager zum Herunterladen von Dateien. Diese Funktion kann von bösartigen Anwendungen dazu verwendet werden, Ladevorgänge zu unterbrechen und auf private Daten zuzugreifen." - "Erweiterte Funktionen des Download-Managers." - "Erlaubt der Anwendung, auf die erweiterten Funktionen des Download-Managers zuzugreifen."\n" Schädliche Anwendungen können so Downloads unterbrechen und auf"\n" persönliche Daten zugreifen." - "Systemcache verwenden" - "Ermöglicht es der Anwendung, direkt auf den Systemcache zuzugreifen und diesen zu ändern oder zu löschen. Diese Funktion kann von bösartigen Anwendungen dazu verwendet werden, Ladevorgänge und andere Anwendungen schwerwiegend zu stören sowie auf private Daten zuzugreifen." - "Benachrichtigungen zu Ladevorgängen senden" - "Ermöglicht es der Anwendung, Benachrichtigungen zu abgeschlossenen Ladevorgängen zu senden. Diese Funktion kann von bösartigen Anwendungen dazu verwendet werden, den Ladevorgang anderer Anwendungen zu stören." - "<Unbenannt>" - "," - "und %d weitere" - "Ladevorgang abgeschlossen" - "Fehler beim Ladevorgang" - diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml deleted file mode 100644 index 388b6590..00000000 --- a/res/values-es/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "Acceso al administrador de descargas" - "Permite que la aplicación acceda al administrador de descargas y lo utilice para descargar archivos. Las aplicaciones malintencionadas pueden utilizar este permiso para provocar daños en las descargas y acceder a información privada." - "Funciones avanzadas del administrador de descargas" - "Permite que la aplicación acceda a las funciones avanzadas de los administradores de descargas."\n" Las aplicaciones malintencionadas pueden utilizar este permiso para provocar daños en las descargas"\n" y acceder a información privada." - "Uso de la memoria caché del sistema" - "Permite que la aplicación acceda directamente a la memoria caché del sistema, la modifique y la elimine. Las aplicaciones malintencionadas pueden utilizar este permiso para provocar graves daños en las descargas y en otras aplicaciones, así como para acceder a datos privados." - "Envío de notificaciones de descarga" - "Permite que la aplicación envíe notificaciones sobre descargas completadas. Las aplicaciones malintencionadas pueden utilizar este permiso para confundir a otras aplicaciones que descarguen archivos." - "<Sin título>" - "," - "y %d más" - "Descarga completada" - "Descarga incorrecta" - diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml deleted file mode 100644 index d040a3cd..00000000 --- a/res/values-fr/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "Accéder au gestionnaire de téléchargement." - "Permet à l\'application d\'accéder au gestionnaire de téléchargement et de l\'utiliser pour télécharger des fichiers. Les applications malveillantes peuvent s\'en servir pour entraver les téléchargements et accéder aux informations personnelles." - "Fonctions avancées du gestionnaire de téléchargement." - "Permet à l\'application d\'accéder aux fonctions avancées des gestionnaires de téléchargements."\n" Des applications malveillantes peuvent utiliser cette option pour perturber les téléchargements et accéder"\n" à des informations confidentielles." - "Utiliser le cache système" - "Permet à l\'application d\'accéder directement au cache système, de le modifier et de le supprimer. Les applications malveillantes peuvent s\'en servir pour entraver sévèrement les téléchargements et autres applications et pour accéder à des données personnelles." - "Envoyer des notifications de téléchargement." - "Permet à l\'application d\'envoyer des notifications concernant les téléchargements effectués. Les applications malveillantes peuvent s\'en servir pour tromper les autres applications de téléchargement de fichiers." - "<Sans_titre>" - "," - "et %d autres" - "Téléchargement terminé." - "Échec du téléchargement" - diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml deleted file mode 100644 index 0e16675b..00000000 --- a/res/values-it/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "Accedere al gestore dei download." - "Consente l\'accesso dell\'applicazione al gestore dei download e il suo utilizzo per scaricare file. Le applicazioni dannose possono sfruttare questa possibilità per interrompere download e accedere a informazioni riservate." - "Funzioni avanzate del gestore dei download." - "Consente l\'accesso dell\'applicazione alle funzioni avanzate del gestore dei download."\n" Le applicazioni dannose possono sfruttare questa possibilità per interrompere download e accedere a"\n" informazioni riservate." - "Usare la cache del sistema." - "Consente l\'accesso diretto dell\'applicazione alla cache del sistema, nonché la modifica e l\'eliminazione della cache. Le applicazioni dannose possono sfruttare questa possibilità per interrompere download e altre applicazioni e accedere a dati riservati." - "Inviare notifiche di download." - "Consente l\'invio da parte dell\'applicazione di notifiche relative ai download completati. Le applicazioni dannose possono sfruttare questa possibilità per \"confondere\" altre applicazioni usate per scaricare file." - "<Senza nome>" - "," - "e altri %d" - "Download completato" - "Download non riuscito" - diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml deleted file mode 100644 index d26c191e..00000000 --- a/res/values-ja/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "ダウンロードマネージャーにアクセスします。" - "ダウンロードマネージャーにアクセスしてファイルをダウンロードすることをアプリケーションに許可します。悪意のあるアプリケーションがこれを利用して、ダウンロードに深刻な影響を与えたり、個人データにアクセスしたりする恐れがあり。" - "ダウンロードマネージャーの高度な機能です。" - "ダウンロードマネージャーの高度な機能にアプリケーションでアクセスできるようにします。"\n" 悪意のあるアプリケーションではこれを利用して、ダウンロードに深刻な影響を与えたり、"\n" 個人情報にアクセスしたりできます。" - "システムキャッシュを使用します。" - "システムキャッシュの直接アクセス、変更、削除をアプリケーションに許可します。悪意のあるアプリケーションがダウンロードや他のアプリケーションに深刻な影響を与えたり、個人データにアクセスする恐れがあります。" - "ダウンロード通知を送信します。" - "ダウンロード完了の通知の送信をアプリケーションに許可します。悪意のあるアプリケーションがファイルをダウンロードする他のアプリケーションの処理を妨害する恐れがあります。" - "<無題>" - "、" - "他%d件" - "ダウンロード完了" - "ダウンロードに失敗しました" - diff --git a/res/values-ko/strings.xml b/res/values-ko/strings.xml deleted file mode 100644 index c51b1722..00000000 --- a/res/values-ko/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "다운로드 관리자 액세스" - "응용 프로그램이 다운로드 관리자에 액세스하여 파일을 다운로드할 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 다운로드를 손상시키고 개인 정보에 액세스할 수 있습니다." - "다운로드 관리자 고급 기능" - "응용프로그램이 다운로드 관리자의 고급 기능에 액세스할 수 있습니다."\n" 악성 응용프로그램은 이 기능을 이용하여 다운로드를 중단시키고"\n" 개인 정보에 액세스할 수 있습니다." - "시스템 캐시 사용" - "응용 프로그램이 시스템 캐시에 직접 액세스, 수정 및 삭제할 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 다운로드와 기타 응용 프로그램을 심하게 손상시키고 개인 데이터에 액세스할 수 있습니다." - "다운로드 알림 보내기" - "응용 프로그램이 완료된 다운로드에 대한 알림을 보낼 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 파일을 다운로드하는 다른 응용 프로그램과 혼동하도록 할 수 있습니다." - "<제목없음>" - "," - "및 %d개 이상" - "다운로드 완료" - "다운로드 실패" - diff --git a/res/values-nb/strings.xml b/res/values-nb/strings.xml deleted file mode 100644 index 997578e5..00000000 --- a/res/values-nb/strings.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - "Få tilgang til nedlasteren." - "Gir applikasjonen tilgang til nedlasteren, og å bruke den til å laste ned filer. Ondsinnede programmer kan bruke dette til å forstyrre nedlastinger og få tilgang til privat informasjon." - "Avansert nedlastingsfunksjonalitet." - - - "Bruke systemets hurtigbuffer." - "Gir applikasjonen direkte tilgang til systemets hurtigbuffer, inkludert å redigere og slette den. Ondsinnede applikasjoner kan bruke dette til å forstyrre nedlastinger og andre applikasjoner, og til å få tilgang til privat informasjon." - "Sende nedlastingsvarslinger" - "Lar applikasjonen sende varslinger om ferdige nedlastinger. Ondsinnede applikasjoner kan bruke dette for å forvirre andre applikasjoner som laster ned filer." - "<Uten navn>" - "," - "samt %d til" - "Ferdig nedlasting" - "Mislykket nedlasting" - diff --git a/res/values-nl/strings.xml b/res/values-nl/strings.xml deleted file mode 100644 index 66c30b8b..00000000 --- a/res/values-nl/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "Downloadbeheer weergeven." - "Hiermee kan de toepassing Downloadbeheer gebruiken om bestanden te downloaden. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om downloads te verstoren en om toegang te krijgen tot privégegevens." - "Geavanceerde functies van de downloadbeheerder." - "Hiermee krijgt de toepassing toegang tot de geavanceerde functies van de downloadbeheerder."\n" Schadelijke toepassingen kunnen hiermee downloads onderbreken en toegang krijgen tot uw "\n" privégegevens." - "Systeemcache gebruiken." - "Hiermee kan de toepassing rechtstreeks de systeemcache openen, aanpassen of wissen. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om downloads en andere toepassingen te verstoren en om toegang te krijgen tot privégegevens." - "Downloadmeldingen verzenden." - "Hiermee ontvangt u een melding zodra een download is voltooid. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om andere toepassingen die bestanden downloaden, in de war te brengen." - "<Zonder titel>" - "," - "en nog %d" - "Downloaden is voltooid" - "Downloaden is mislukt." - diff --git a/res/values-pl/strings.xml b/res/values-pl/strings.xml deleted file mode 100644 index 7cd3e28e..00000000 --- a/res/values-pl/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "Dostęp do menedżera pobierania." - "Umożliwia programowi dostęp do menedżera pobierania i pobieranie plików przy jego użyciu. Szkodliwe programy mogą w ten sposób zakłócić pobieranie i uzyskać dostęp do prywatnych informacji." - "Zaawansowane funkcje menedżera pobierania." - "Zezwala aplikacji na dostęp do zaawansowanych funkcji menedżera pobierania."\n" Złośliwe aplikacje mogą to wykorzystać do przerywania pobierania i uzyskiwania dostępu do"\n" informacji poufnych." - "Korzystanie z systemowej pamięci podręcznej." - "Umożliwia programowi bezpośredni dostęp do systemowej pamięci podręcznej, jej modyfikację oraz usuwanie. Szkodliwe programy mogą w ten sposób poważnie zakłócić pobieranie plików i działanie innych programów, a także uzyskać dostęp do prywatnych informacji." - "Wysyłanie powiadomień o pobraniu." - "Umożliwia programowi wysyłanie powiadomień o ukończeniu pobierania. Szkodliwe programy mogą korzystać z tego uprawnienia, aby zakłócić działanie innych programów pobierających pliki." - "<Bez nazwy>" - "," - "i %d innych" - "Pobieranie zakończone." - "Pobieranie nie powiodło się" - diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml deleted file mode 100644 index fb2c5c5c..00000000 --- a/res/values-ru/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "Открывать диспетчер загрузок." - "Разрешает приложениям доступ к диспетчеру загрузок и его использование для загрузки файлов. Вредоносные приложения могут использовать это для прерывания загрузок и получения доступа к личной информации." - "Дополнительные функции диспетчера загрузок." - "Разрешает приложению доступ к дополнительным функциям диспетчера загрузок."\n" Вредоносное ПО может использовать это для прерывания загрузок и получения доступа"\n" к личной информации." - "Использовать кэш системы" - "Разрешает приложениям прямой доступ, изменение и удаление в системном кэше. Вредоносные приложения могут использовать это для прерывания загрузок и работы других приложений, а также для получения доступа к личной информации." - "Отправлять уведомления о загрузках." - "Разрешает приложениям отправлять уведомления о завершенных загрузках. Вредоносные приложения могут использовать это, чтобы передавать ложную информацию другим приложениям загрузки файлов." - "<Без названия>" - "," - "и еще %d" - "Загрузка завершена" - "Загрузка не удалась" - diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml deleted file mode 100644 index 642a7e09..00000000 --- a/res/values-zh-rCN/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "访问下载管理程序。" - "允许应用程序访问下载管理程序以及将其用于下载文件。恶意应用程序可以使用该功能干扰下载,以及访问隐私信息。" - "高级下载管理程序功能。" - "允许应用程序访问下载管理程序高级功能。"\n" 恶意应用程序可能会使用此权限干扰下载,以及"\n" 访问隐私信息。" - "使用系统缓存。" - "允许应用程序直接访问、修改和删除系统缓存。恶意应用程序可以使用该功能严重干扰下载和其他应用程序,以及访问隐私数据。" - "发送下载通知。" - "允许应用程序发送关于已完成下载的通知。恶意应用程序可以使用该功能干扰其他下载文件的应用程序。" - "<未命名>" - "、" - "以及另外 %d 个" - "下载完成" - "下载不成功" - diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml deleted file mode 100644 index eeb4ea80..00000000 --- a/res/values-zh-rTW/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - "存取下載管理員。" - "允許應用程式存取下載管理員,並使用它下載檔案。惡意程式可使用此功能,影響下載並存取個人資料。" - "下載管理員進階功能。" - "允許應用程式存取下載管理員的進階功能。"\n" 惡意應用程式可能使用此功能讓下載發生錯誤並存取私人資訊。"\n - "使用系統快取。" - "允許應用程式直接存取、修改與刪除系統快取。惡意程式可使用此功能,嚴重影響下載與其他應用程式,並存取個人資料。" - "傳送下載通知。" - "下載完成時,允許應用程式送出通知。惡意程式可使用此功能干擾其他正在下載檔案的應用程式。" - "(未命名)" - "," - "還有 %d 項下載" - "下載已完成。" - "下載失敗" - diff --git a/res/values/strings.xml b/res/values/strings.xml deleted file mode 100644 index 3a8fa076..00000000 --- a/res/values/strings.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - Access download manager. - - Allows the application to - access the download manager and to use it to download files. - Malicious applications can use this to disrupt downloads and access - private information. - - - Advanced download - manager functions. - - Allows the application to - access the download manager's advanced functions. - Malicious applications can use this to disrupt downloads and access - private information. - - - Use system cache. - - Allows the application - to directly access, modify and delete the system cache. Malicious - applications can use this to severely disrupt downloads and - other applications, and to access private data. - - Send download - notifications. - - Allows the application - to send notifications about completed downloads. Malicious applications - can use this to confuse other applications that download - files. - - - <Untitled> - - - ", " - - - " and %d more" - - - Download complete - - - Download unsuccessful - - - diff --git a/src/com/android/providers/downloads/Constants.java b/src/com/android/providers/downloads/Constants.java deleted file mode 100644 index cffda04a..00000000 --- a/src/com/android/providers/downloads/Constants.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.providers.downloads; - -import android.util.Config; -import android.util.Log; - -/** - * Contains the internal constants that are used in the download manager. - * As a general rule, modifying these constants should be done with care. - */ -public class Constants { - - /** Tag used for debugging/logging */ - public static final String TAG = "DownloadManager"; - - /** The column that used to be used for the HTTP method of the request */ - public static final String RETRY_AFTER___REDIRECT_COUNT = "method"; - - /** The column that used to be used for the magic OTA update filename */ - public static final String OTA_UPDATE = "otaupdate"; - - /** The column that used to be used to reject system filetypes */ - public static final String NO_SYSTEM_FILES = "no_system"; - - /** The column that is used for the downloads's ETag */ - public static final String ETAG = "etag"; - - /** The column that is used for the initiating app's UID */ - public static final String UID = "uid"; - - /** The column that is used to remember whether the media scanner was invoked */ - public static final String MEDIA_SCANNED = "scanned"; - - /** The column that is used to count retries */ - public static final String FAILED_CONNECTIONS = "numfailed"; - - /** The intent that gets sent when the service must wake up for a retry */ - public static final String ACTION_RETRY = "android.intent.action.DOWNLOAD_WAKEUP"; - - /** the intent that gets sent when clicking a successful download */ - public static final String ACTION_OPEN = "android.intent.action.DOWNLOAD_OPEN"; - - /** the intent that gets sent when clicking an incomplete/failed download */ - public static final String ACTION_LIST = "android.intent.action.DOWNLOAD_LIST"; - - /** the intent that gets sent when deleting the notification of a completed download */ - public static final String ACTION_HIDE = "android.intent.action.DOWNLOAD_HIDE"; - - /** The default base name for downloaded files if we can't get one at the HTTP level */ - public static final String DEFAULT_DL_FILENAME = "downloadfile"; - - /** The default extension for html files if we can't get one at the HTTP level */ - public static final String DEFAULT_DL_HTML_EXTENSION = ".html"; - - /** The default extension for text files if we can't get one at the HTTP level */ - public static final String DEFAULT_DL_TEXT_EXTENSION = ".txt"; - - /** The default extension for binary files if we can't get one at the HTTP level */ - public static final String DEFAULT_DL_BINARY_EXTENSION = ".bin"; - - /** - * When a number has to be appended to the filename, this string is used to separate the - * base filename from the sequence number - */ - public static final String FILENAME_SEQUENCE_SEPARATOR = "-"; - - /** Where we store downloaded files on the external storage */ - public static final String DEFAULT_DL_SUBDIR = "/download"; - - /** A magic filename that is allowed to exist within the system cache */ - public static final String KNOWN_SPURIOUS_FILENAME = "lost+found"; - - /** A magic filename that is allowed to exist within the system cache */ - public static final String RECOVERY_DIRECTORY = "recovery"; - - /** The default user agent used for downloads */ - public static final String DEFAULT_USER_AGENT = "AndroidDownloadManager"; - - /** The MIME type of special DRM files */ - public static final String MIMETYPE_DRM_MESSAGE = - android.drm.mobile1.DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING; - - /** The MIME type of APKs */ - public static final String MIMETYPE_APK = "application/vnd.android.package"; - - /** The buffer size used to stream the data */ - public static final int BUFFER_SIZE = 4096; - - /** The minimum amount of progress that has to be done before the progress bar gets updated */ - public static final int MIN_PROGRESS_STEP = 4096; - - /** The minimum amount of time that has to elapse before the progress bar gets updated, in ms */ - public static final long MIN_PROGRESS_TIME = 1500; - - /** The maximum number of rows in the database (FIFO) */ - public static final int MAX_DOWNLOADS = 1000; - - /** - * The number of times that the download manager will retry its network - * operations when no progress is happening before it gives up. - */ - public static final int MAX_RETRIES = 5; - - /** - * The minimum amount of time that the download manager accepts for - * a Retry-After response header with a parameter in delta-seconds. - */ - public static final int MIN_RETRY_AFTER = 30; // 30s - - /** - * The maximum amount of time that the download manager accepts for - * a Retry-After response header with a parameter in delta-seconds. - */ - public static final int MAX_RETRY_AFTER = 24 * 60 * 60; // 24h - - /** - * The maximum number of redirects. - */ - public static final int MAX_REDIRECTS = 5; // can't be more than 7. - - /** - * The time between a failure and the first retry after an IOException. - * Each subsequent retry grows exponentially, doubling each time. - * The time is in seconds. - */ - public static final int RETRY_FIRST_DELAY = 30; - - /** Enable verbose logging - use with "setprop log.tag.DownloadManager VERBOSE" */ - private static final boolean LOCAL_LOGV = true; - public static final boolean LOGV = Config.LOGV - || (Config.LOGD && LOCAL_LOGV && Log.isLoggable(TAG, Log.VERBOSE)); - - /** Enable super-verbose logging */ - private static final boolean LOCAL_LOGVV = false; - public static final boolean LOGVV = LOCAL_LOGVV && LOGV; -} diff --git a/src/com/android/providers/downloads/DownloadFileInfo.java b/src/com/android/providers/downloads/DownloadFileInfo.java deleted file mode 100644 index 29cbd940..00000000 --- a/src/com/android/providers/downloads/DownloadFileInfo.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.providers.downloads; - -import java.io.FileOutputStream; - -/** - * Stores information about the file in which a download gets saved. - */ -public class DownloadFileInfo { - public DownloadFileInfo(String filename, FileOutputStream stream, int status) { - this.filename = filename; - this.stream = stream; - this.status = status; - } - - String filename; - FileOutputStream stream; - int status; -} diff --git a/src/com/android/providers/downloads/DownloadInfo.java b/src/com/android/providers/downloads/DownloadInfo.java deleted file mode 100644 index e051f41a..00000000 --- a/src/com/android/providers/downloads/DownloadInfo.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.providers.downloads; - -import android.net.Uri; -import android.content.Context; -import android.content.Intent; -import android.provider.Downloads; - -/** - * Stores information about an individual download. - */ -public class DownloadInfo { - public int id; - public String uri; - public boolean noIntegrity; - public String hint; - public String filename; - public String mimetype; - public int destination; - public int visibility; - public int control; - public int status; - public int numFailed; - public int retryAfter; - public int redirectCount; - public long lastMod; - public String pckg; - public String clazz; - public String extras; - public String cookies; - public String userAgent; - public String referer; - public int totalBytes; - public int currentBytes; - public String etag; - public boolean mediaScanned; - - public volatile boolean hasActiveThread; - - public DownloadInfo(int id, String uri, boolean noIntegrity, - String hint, String filename, - String mimetype, int destination, int visibility, int control, - int status, int numFailed, int retryAfter, int redirectCount, long lastMod, - String pckg, String clazz, String extras, String cookies, - String userAgent, String referer, int totalBytes, int currentBytes, String etag, - boolean mediaScanned) { - this.id = id; - this.uri = uri; - this.noIntegrity = noIntegrity; - this.hint = hint; - this.filename = filename; - this.mimetype = mimetype; - this.destination = destination; - this.visibility = visibility; - this.control = control; - this.status = status; - this.numFailed = numFailed; - this.retryAfter = retryAfter; - this.redirectCount = redirectCount; - this.lastMod = lastMod; - this.pckg = pckg; - this.clazz = clazz; - this.extras = extras; - this.cookies = cookies; - this.userAgent = userAgent; - this.referer = referer; - this.totalBytes = totalBytes; - this.currentBytes = currentBytes; - this.etag = etag; - this.mediaScanned = mediaScanned; - } - - public void sendIntentIfRequested(Uri contentUri, Context context) { - if (pckg != null && clazz != null) { - Intent intent = new Intent(Downloads.DOWNLOAD_COMPLETED_ACTION); - intent.setClassName(pckg, clazz); - if (extras != null) { - intent.putExtra(Downloads.NOTIFICATION_EXTRAS, extras); - } - // We only send the content: URI, for security reasons. Otherwise, malicious - // applications would have an easier time spoofing download results by - // sending spoofed intents. - intent.setData(contentUri); - context.sendBroadcast(intent); - } - } - - /** - * Returns the time when a download should be restarted. Must only - * be called when numFailed > 0. - */ - public long restartTime() { - if (retryAfter > 0) { - return lastMod + retryAfter; - } - return lastMod + - Constants.RETRY_FIRST_DELAY * - (1000 + Helpers.rnd.nextInt(1001)) * (1 << (numFailed - 1)); - } - - /** - * Returns whether this download (which the download manager hasn't seen yet) - * should be started. - */ - public boolean isReadyToStart(long now) { - if (control == Downloads.CONTROL_PAUSED) { - // the download is paused, so it's not going to start - return false; - } - if (status == 0) { - // status hasn't been initialized yet, this is a new download - return true; - } - if (status == Downloads.STATUS_PENDING) { - // download is explicit marked as ready to start - return true; - } - if (status == Downloads.STATUS_RUNNING) { - // download was interrupted (process killed, loss of power) while it was running, - // without a chance to update the database - return true; - } - if (status == Downloads.STATUS_RUNNING_PAUSED) { - if (numFailed == 0) { - // download is waiting for network connectivity to return before it can resume - return true; - } - if (restartTime() < now) { - // download was waiting for a delayed restart, and the delay has expired - return true; - } - } - return false; - } - - /** - * Returns whether this download (which the download manager has already seen - * and therefore potentially started) should be restarted. - * - * In a nutshell, this returns true if the download isn't already running - * but should be, and it can know whether the download is already running - * by checking the status. - */ - public boolean isReadyToRestart(long now) { - if (control == Downloads.CONTROL_PAUSED) { - // the download is paused, so it's not going to restart - return false; - } - if (status == 0) { - // download hadn't been initialized yet - return true; - } - if (status == Downloads.STATUS_PENDING) { - // download is explicit marked as ready to start - return true; - } - if (status == Downloads.STATUS_RUNNING_PAUSED) { - if (numFailed == 0) { - // download is waiting for network connectivity to return before it can resume - return true; - } - if (restartTime() < now) { - // download was waiting for a delayed restart, and the delay has expired - return true; - } - } - return false; - } - - /** - * Returns whether this download has a visible notification after - * completion. - */ - public boolean hasCompletionNotification() { - if (!Downloads.isStatusCompleted(status)) { - return false; - } - if (visibility == Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) { - return true; - } - return false; - } - - /** - * Returns whether this download is allowed to use the network. - */ - public boolean canUseNetwork(boolean available, boolean roaming) { - if (!available) { - return false; - } - if (destination == Downloads.DESTINATION_CACHE_PARTITION_NOROAMING) { - return !roaming; - } else { - return true; - } - } -} diff --git a/src/com/android/providers/downloads/DownloadNotification.java b/src/com/android/providers/downloads/DownloadNotification.java deleted file mode 100644 index ed17ab7a..00000000 --- a/src/com/android/providers/downloads/DownloadNotification.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.providers.downloads; - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.net.Uri; -import android.provider.Downloads; -import android.widget.RemoteViews; - -import java.util.HashMap; - -/** - * This class handles the updating of the Notification Manager for the - * cases where there is an ongoing download. Once the download is complete - * (be it successful or unsuccessful) it is no longer the responsibility - * of this component to show the download in the notification manager. - * - */ -class DownloadNotification { - - Context mContext; - public NotificationManager mNotificationMgr; - HashMap mNotifications; - - static final String LOGTAG = "DownloadNotification"; - static final String WHERE_RUNNING = - "(" + Downloads.STATUS + " >= '100') AND (" + - Downloads.STATUS + " <= '199') AND (" + - Downloads.VISIBILITY + " IS NULL OR " + - Downloads.VISIBILITY + " == '" + Downloads.VISIBILITY_VISIBLE + "' OR " + - Downloads.VISIBILITY + " == '" + Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED + "')"; - static final String WHERE_COMPLETED = - Downloads.STATUS + " >= '200' AND " + - Downloads.VISIBILITY + " == '" + Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED + "'"; - - - /** - * This inner class is used to collate downloads that are owned by - * the same application. This is so that only one notification line - * item is used for all downloads of a given application. - * - */ - static class NotificationItem { - int id; // This first db _id for the download for the app - int totalCurrent = 0; - int totalTotal = 0; - int titleCount = 0; - String packageName; // App package name - String description; - String[] titles = new String[2]; // download titles. - - /* - * Add a second download to this notification item. - */ - void addItem(String title, int currentBytes, int totalBytes) { - totalCurrent += currentBytes; - if (totalBytes <= 0 || totalTotal == -1) { - totalTotal = -1; - } else { - totalTotal += totalBytes; - } - if (titleCount < 2) { - titles[titleCount] = title; - } - titleCount++; - } - } - - - /** - * Constructor - * @param ctx The context to use to obtain access to the - * Notification Service - */ - DownloadNotification(Context ctx) { - mContext = ctx; - mNotificationMgr = (NotificationManager) mContext - .getSystemService(Context.NOTIFICATION_SERVICE); - mNotifications = new HashMap(); - } - - /* - * Update the notification ui. - */ - public void updateNotification() { - updateActiveNotification(); - updateCompletedNotification(); - } - - private void updateActiveNotification() { - // Active downloads - Cursor c = mContext.getContentResolver().query( - Downloads.CONTENT_URI, new String [] { - Downloads._ID, Downloads.TITLE, Downloads.DESCRIPTION, - Downloads.NOTIFICATION_PACKAGE, - Downloads.NOTIFICATION_CLASS, - Downloads.CURRENT_BYTES, Downloads.TOTAL_BYTES, - Downloads.STATUS, Downloads._DATA - }, - WHERE_RUNNING, null, Downloads._ID); - - if (c == null) { - return; - } - - // Columns match projection in query above - final int idColumn = 0; - final int titleColumn = 1; - final int descColumn = 2; - final int ownerColumn = 3; - final int classOwnerColumn = 4; - final int currentBytesColumn = 5; - final int totalBytesColumn = 6; - final int statusColumn = 7; - final int filenameColumnId = 8; - - // Collate the notifications - mNotifications.clear(); - for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { - String packageName = c.getString(ownerColumn); - int max = c.getInt(totalBytesColumn); - int progress = c.getInt(currentBytesColumn); - String title = c.getString(titleColumn); - if (title == null || title.length() == 0) { - title = mContext.getResources().getString( - R.string.download_unknown_title); - } - if (mNotifications.containsKey(packageName)) { - mNotifications.get(packageName).addItem(title, progress, max); - } else { - NotificationItem item = new NotificationItem(); - item.id = c.getInt(idColumn); - item.packageName = packageName; - item.description = c.getString(descColumn); - String className = c.getString(classOwnerColumn); - item.addItem(title, progress, max); - mNotifications.put(packageName, item); - } - - } - c.close(); - - // Add the notifications - for (NotificationItem item : mNotifications.values()) { - // Build the notification object - Notification n = new Notification(); - n.icon = android.R.drawable.stat_sys_download; - - n.flags |= Notification.FLAG_ONGOING_EVENT; - - // Build the RemoteView object - RemoteViews expandedView = new RemoteViews( - "com.android.providers.downloads", - R.layout.status_bar_ongoing_event_progress_bar); - StringBuilder title = new StringBuilder(item.titles[0]); - if (item.titleCount > 1) { - title.append(mContext.getString(R.string.notification_filename_separator)); - title.append(item.titles[1]); - n.number = item.titleCount; - if (item.titleCount > 2) { - title.append(mContext.getString(R.string.notification_filename_extras, - new Object[] { Integer.valueOf(item.titleCount - 2) })); - } - } else { - expandedView.setTextViewText(R.id.description, - item.description); - } - expandedView.setTextViewText(R.id.title, title); - expandedView.setProgressBar(R.id.progress_bar, - item.totalTotal, - item.totalCurrent, - item.totalTotal == -1); - expandedView.setTextViewText(R.id.progress_text, - getDownloadingText(item.totalTotal, item.totalCurrent)); - expandedView.setImageViewResource(R.id.appIcon, - android.R.drawable.stat_sys_download); - n.contentView = expandedView; - - Intent intent = new Intent(Constants.ACTION_LIST); - intent.setClassName("com.android.providers.downloads", - DownloadReceiver.class.getName()); - intent.setData(Uri.parse(Downloads.CONTENT_URI + "/" + item.id)); - intent.putExtra("multiple", item.titleCount > 1); - - n.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); - - mNotificationMgr.notify(item.id, n); - - } - } - - private void updateCompletedNotification() { - // Completed downloads - Cursor c = mContext.getContentResolver().query( - Downloads.CONTENT_URI, new String [] { - Downloads._ID, Downloads.TITLE, Downloads.DESCRIPTION, - Downloads.NOTIFICATION_PACKAGE, - Downloads.NOTIFICATION_CLASS, - Downloads.CURRENT_BYTES, Downloads.TOTAL_BYTES, - Downloads.STATUS, Downloads._DATA, - Downloads.LAST_MODIFICATION, Downloads.DESTINATION - }, - WHERE_COMPLETED, null, Downloads._ID); - - if (c == null) { - return; - } - - // Columns match projection in query above - final int idColumn = 0; - final int titleColumn = 1; - final int descColumn = 2; - final int ownerColumn = 3; - final int classOwnerColumn = 4; - final int currentBytesColumn = 5; - final int totalBytesColumn = 6; - final int statusColumn = 7; - final int filenameColumnId = 8; - final int lastModColumnId = 9; - final int destinationColumnId = 10; - - for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { - // Add the notifications - Notification n = new Notification(); - n.icon = android.R.drawable.stat_sys_download_done; - - String title = c.getString(titleColumn); - if (title == null || title.length() == 0) { - title = mContext.getResources().getString( - R.string.download_unknown_title); - } - Uri contentUri = Uri.parse(Downloads.CONTENT_URI + "/" + c.getInt(idColumn)); - String caption; - Intent intent; - if (Downloads.isStatusError(c.getInt(statusColumn))) { - caption = mContext.getResources() - .getString(R.string.notification_download_failed); - intent = new Intent(Constants.ACTION_LIST); - } else { - caption = mContext.getResources() - .getString(R.string.notification_download_complete); - if (c.getInt(destinationColumnId) == Downloads.DESTINATION_EXTERNAL) { - intent = new Intent(Constants.ACTION_OPEN); - } else { - intent = new Intent(Constants.ACTION_LIST); - } - } - intent.setClassName("com.android.providers.downloads", - DownloadReceiver.class.getName()); - intent.setData(contentUri); - n.setLatestEventInfo(mContext, title, caption, - PendingIntent.getBroadcast(mContext, 0, intent, 0)); - - intent = new Intent(Constants.ACTION_HIDE); - intent.setClassName("com.android.providers.downloads", - DownloadReceiver.class.getName()); - intent.setData(contentUri); - n.deleteIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); - - n.when = c.getLong(lastModColumnId); - - mNotificationMgr.notify(c.getInt(idColumn), n); - } - c.close(); - } - - /* - * Helper function to build the downloading text. - */ - private String getDownloadingText(long totalBytes, long currentBytes) { - if (totalBytes <= 0) { - return ""; - } - long progress = currentBytes * 100 / totalBytes; - StringBuilder sb = new StringBuilder(); - sb.append(progress); - sb.append('%'); - return sb.toString(); - } - -} diff --git a/src/com/android/providers/downloads/DownloadProvider.java b/src/com/android/providers/downloads/DownloadProvider.java deleted file mode 100644 index f7cdd51e..00000000 --- a/src/com/android/providers/downloads/DownloadProvider.java +++ /dev/null @@ -1,731 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.providers.downloads; - -import android.content.ContentProvider; -import android.content.ContentValues; -import android.content.Context; -import android.content.Intent; -import android.content.UriMatcher; -import android.content.pm.PackageManager; -import android.database.CrossProcessCursor; -import android.database.Cursor; -import android.database.CursorWindow; -import android.database.CursorWrapper; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; -import android.database.sqlite.SQLiteQueryBuilder; -import android.database.SQLException; -import android.net.Uri; -import android.os.Binder; -import android.os.ParcelFileDescriptor; -import android.os.Process; -import android.provider.Downloads; -import android.util.Config; -import android.util.Log; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.HashSet; - - -/** - * Allows application to interact with the download manager. - */ -public final class DownloadProvider extends ContentProvider { - - /** Database filename */ - private static final String DB_NAME = "downloads.db"; - /** Current database version */ - private static final int DB_VERSION = 100; - /** Database version from which upgrading is a nop */ - private static final int DB_VERSION_NOP_UPGRADE_FROM = 31; - /** Database version to which upgrading is a nop */ - private static final int DB_VERSION_NOP_UPGRADE_TO = 100; - /** Name of table in the database */ - private static final String DB_TABLE = "downloads"; - - /** MIME type for the entire download list */ - private static final String DOWNLOAD_LIST_TYPE = "vnd.android.cursor.dir/download"; - /** MIME type for an individual download */ - private static final String DOWNLOAD_TYPE = "vnd.android.cursor.item/download"; - - /** URI matcher used to recognize URIs sent by applications */ - private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH); - /** URI matcher constant for the URI of the entire download list */ - private static final int DOWNLOADS = 1; - /** URI matcher constant for the URI of an individual download */ - private static final int DOWNLOADS_ID = 2; - static { - sURIMatcher.addURI("downloads", "download", DOWNLOADS); - sURIMatcher.addURI("downloads", "download/#", DOWNLOADS_ID); - } - - private static final String[] sAppReadableColumnsArray = new String[] { - Downloads._ID, - Downloads.APP_DATA, - Downloads._DATA, - Downloads.MIMETYPE, - Downloads.VISIBILITY, - Downloads.CONTROL, - Downloads.STATUS, - Downloads.LAST_MODIFICATION, - Downloads.NOTIFICATION_PACKAGE, - Downloads.NOTIFICATION_CLASS, - Downloads.TOTAL_BYTES, - Downloads.CURRENT_BYTES, - Downloads.TITLE, - Downloads.DESCRIPTION - }; - - private static HashSet sAppReadableColumnsSet; - static { - sAppReadableColumnsSet = new HashSet(); - for (int i = 0; i < sAppReadableColumnsArray.length; ++i) { - sAppReadableColumnsSet.add(sAppReadableColumnsArray[i]); - } - } - - /** The database that lies underneath this content provider */ - private SQLiteOpenHelper mOpenHelper = null; - - /** - * Creates and updated database on demand when opening it. - * Helper class to create database the first time the provider is - * initialized and upgrade it when a new version of the provider needs - * an updated version of the database. - */ - private final class DatabaseHelper extends SQLiteOpenHelper { - - public DatabaseHelper(final Context context) { - super(context, DB_NAME, null, DB_VERSION); - } - - /** - * Creates database the first time we try to open it. - */ - @Override - public void onCreate(final SQLiteDatabase db) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "populating new database"); - } - createTable(db); - } - - /* (not a javadoc comment) - * Checks data integrity when opening the database. - */ - /* - * @Override - * public void onOpen(final SQLiteDatabase db) { - * super.onOpen(db); - * } - */ - - /** - * Updates the database format when a content provider is used - * with a database that was created with a different format. - */ - // Note: technically, this could also be a downgrade, so if we want - // to gracefully handle upgrades we should be careful about - // what to do on downgrades. - @Override - public void onUpgrade(final SQLiteDatabase db, int oldV, final int newV) { - if (oldV == DB_VERSION_NOP_UPGRADE_FROM) { - if (newV == DB_VERSION_NOP_UPGRADE_TO) { // that's a no-op upgrade. - return; - } - // NOP_FROM and NOP_TO are identical, just in different codelines. Upgrading - // from NOP_FROM is the same as upgrading from NOP_TO. - oldV = DB_VERSION_NOP_UPGRADE_TO; - } - Log.i(Constants.TAG, "Upgrading downloads database from version " + oldV + " to " + newV - + ", which will destroy all old data"); - dropTable(db); - createTable(db); - } - } - - /** - * Initializes the content provider when it is created. - */ - @Override - public boolean onCreate() { - mOpenHelper = new DatabaseHelper(getContext()); - return true; - } - - /** - * Returns the content-provider-style MIME types of the various - * types accessible through this content provider. - */ - @Override - public String getType(final Uri uri) { - int match = sURIMatcher.match(uri); - switch (match) { - case DOWNLOADS: { - return DOWNLOAD_LIST_TYPE; - } - case DOWNLOADS_ID: { - return DOWNLOAD_TYPE; - } - default: { - if (Constants.LOGV) { - Log.v(Constants.TAG, "calling getType on an unknown URI: " + uri); - } - throw new IllegalArgumentException("Unknown URI: " + uri); - } - } - } - - /** - * Creates the table that'll hold the download information. - */ - private void createTable(SQLiteDatabase db) { - try { - db.execSQL("CREATE TABLE " + DB_TABLE + "(" + - Downloads._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + - Downloads.URI + " TEXT, " + - Constants.RETRY_AFTER___REDIRECT_COUNT + " INTEGER, " + - Downloads.APP_DATA + " TEXT, " + - Downloads.NO_INTEGRITY + " BOOLEAN, " + - Downloads.FILENAME_HINT + " TEXT, " + - Constants.OTA_UPDATE + " BOOLEAN, " + - Downloads._DATA + " TEXT, " + - Downloads.MIMETYPE + " TEXT, " + - Downloads.DESTINATION + " INTEGER, " + - Constants.NO_SYSTEM_FILES + " BOOLEAN, " + - Downloads.VISIBILITY + " INTEGER, " + - Downloads.CONTROL + " INTEGER, " + - Downloads.STATUS + " INTEGER, " + - Constants.FAILED_CONNECTIONS + " INTEGER, " + - Downloads.LAST_MODIFICATION + " BIGINT, " + - Downloads.NOTIFICATION_PACKAGE + " TEXT, " + - Downloads.NOTIFICATION_CLASS + " TEXT, " + - Downloads.NOTIFICATION_EXTRAS + " TEXT, " + - Downloads.COOKIE_DATA + " TEXT, " + - Downloads.USER_AGENT + " TEXT, " + - Downloads.REFERER + " TEXT, " + - Downloads.TOTAL_BYTES + " INTEGER, " + - Downloads.CURRENT_BYTES + " INTEGER, " + - Constants.ETAG + " TEXT, " + - Constants.UID + " INTEGER, " + - Downloads.OTHER_UID + " INTEGER, " + - Downloads.TITLE + " TEXT, " + - Downloads.DESCRIPTION + " TEXT, " + - Constants.MEDIA_SCANNED + " BOOLEAN);"); - } catch (SQLException ex) { - Log.e(Constants.TAG, "couldn't create table in downloads database"); - throw ex; - } - } - - /** - * Deletes the table that holds the download information. - */ - private void dropTable(SQLiteDatabase db) { - try { - db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE); - } catch (SQLException ex) { - Log.e(Constants.TAG, "couldn't drop table in downloads database"); - throw ex; - } - } - - /** - * Inserts a row in the database - */ - @Override - public Uri insert(final Uri uri, final ContentValues values) { - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - - if (sURIMatcher.match(uri) != DOWNLOADS) { - if (Config.LOGD) { - Log.d(Constants.TAG, "calling insert on an unknown/invalid URI: " + uri); - } - throw new IllegalArgumentException("Unknown/Invalid URI " + uri); - } - - ContentValues filteredValues = new ContentValues(); - - copyString(Downloads.URI, values, filteredValues); - copyString(Downloads.APP_DATA, values, filteredValues); - copyBoolean(Downloads.NO_INTEGRITY, values, filteredValues); - copyString(Downloads.FILENAME_HINT, values, filteredValues); - copyString(Downloads.MIMETYPE, values, filteredValues); - Integer dest = values.getAsInteger(Downloads.DESTINATION); - if (dest != null) { - if (getContext().checkCallingPermission(Downloads.PERMISSION_ACCESS_ADVANCED) - != PackageManager.PERMISSION_GRANTED - && dest != Downloads.DESTINATION_EXTERNAL - && dest != Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE) { - throw new SecurityException("unauthorized destination code"); - } - filteredValues.put(Downloads.DESTINATION, dest); - } - Integer vis = values.getAsInteger(Downloads.VISIBILITY); - if (vis == null) { - if (dest == Downloads.DESTINATION_EXTERNAL) { - filteredValues.put(Downloads.VISIBILITY, - Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - } else { - filteredValues.put(Downloads.VISIBILITY, Downloads.VISIBILITY_HIDDEN); - } - } else { - filteredValues.put(Downloads.VISIBILITY, vis); - } - copyInteger(Downloads.CONTROL, values, filteredValues); - filteredValues.put(Downloads.STATUS, Downloads.STATUS_PENDING); - filteredValues.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis()); - String pckg = values.getAsString(Downloads.NOTIFICATION_PACKAGE); - String clazz = values.getAsString(Downloads.NOTIFICATION_CLASS); - if (pckg != null && clazz != null) { - int uid = Binder.getCallingUid(); - try { - if (uid == 0 || - getContext().getPackageManager().getApplicationInfo(pckg, 0).uid == uid) { - filteredValues.put(Downloads.NOTIFICATION_PACKAGE, pckg); - filteredValues.put(Downloads.NOTIFICATION_CLASS, clazz); - } - } catch (PackageManager.NameNotFoundException ex) { - /* ignored for now */ - } - } - copyString(Downloads.NOTIFICATION_EXTRAS, values, filteredValues); - copyString(Downloads.COOKIE_DATA, values, filteredValues); - copyString(Downloads.USER_AGENT, values, filteredValues); - copyString(Downloads.REFERER, values, filteredValues); - if (getContext().checkCallingPermission(Downloads.PERMISSION_ACCESS_ADVANCED) - == PackageManager.PERMISSION_GRANTED) { - copyInteger(Downloads.OTHER_UID, values, filteredValues); - } - filteredValues.put(Constants.UID, Binder.getCallingUid()); - if (Binder.getCallingUid() == 0) { - copyInteger(Constants.UID, values, filteredValues); - } - copyString(Downloads.TITLE, values, filteredValues); - copyString(Downloads.DESCRIPTION, values, filteredValues); - - if (Constants.LOGVV) { - Log.v(Constants.TAG, "initiating download with UID " - + filteredValues.getAsInteger(Constants.UID)); - if (filteredValues.containsKey(Downloads.OTHER_UID)) { - Log.v(Constants.TAG, "other UID " + - filteredValues.getAsInteger(Downloads.OTHER_UID)); - } - } - - Context context = getContext(); - context.startService(new Intent(context, DownloadService.class)); - - long rowID = db.insert(DB_TABLE, null, filteredValues); - - Uri ret = null; - - if (rowID != -1) { - context.startService(new Intent(context, DownloadService.class)); - ret = Uri.parse(Downloads.CONTENT_URI + "/" + rowID); - context.getContentResolver().notifyChange(uri, null); - } else { - if (Config.LOGD) { - Log.d(Constants.TAG, "couldn't insert into downloads database"); - } - } - - return ret; - } - - /** - * Starts a database query - */ - @Override - public Cursor query(final Uri uri, String[] projection, - final String selection, final String[] selectionArgs, - final String sort) { - - Helpers.validateSelection(selection, sAppReadableColumnsSet); - - SQLiteDatabase db = mOpenHelper.getReadableDatabase(); - - SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); - - int match = sURIMatcher.match(uri); - boolean emptyWhere = true; - switch (match) { - case DOWNLOADS: { - qb.setTables(DB_TABLE); - break; - } - case DOWNLOADS_ID: { - qb.setTables(DB_TABLE); - qb.appendWhere(Downloads._ID + "="); - qb.appendWhere(uri.getPathSegments().get(1)); - emptyWhere = false; - break; - } - default: { - if (Constants.LOGV) { - Log.v(Constants.TAG, "querying unknown URI: " + uri); - } - throw new IllegalArgumentException("Unknown URI: " + uri); - } - } - - if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) { - if (!emptyWhere) { - qb.appendWhere(" AND "); - } - qb.appendWhere("( " + Constants.UID + "=" + Binder.getCallingUid() + " OR " - + Downloads.OTHER_UID + "=" + Binder.getCallingUid() + " )"); - emptyWhere = false; - - if (projection == null) { - projection = sAppReadableColumnsArray; - } else { - for (int i = 0; i < projection.length; ++i) { - if (!sAppReadableColumnsSet.contains(projection[i])) { - throw new IllegalArgumentException( - "column " + projection[i] + " is not allowed in queries"); - } - } - } - } - - if (Constants.LOGVV) { - java.lang.StringBuilder sb = new java.lang.StringBuilder(); - sb.append("starting query, database is "); - if (db != null) { - sb.append("not "); - } - sb.append("null; "); - if (projection == null) { - sb.append("projection is null; "); - } else if (projection.length == 0) { - sb.append("projection is empty; "); - } else { - for (int i = 0; i < projection.length; ++i) { - sb.append("projection["); - sb.append(i); - sb.append("] is "); - sb.append(projection[i]); - sb.append("; "); - } - } - sb.append("selection is "); - sb.append(selection); - sb.append("; "); - if (selectionArgs == null) { - sb.append("selectionArgs is null; "); - } else if (selectionArgs.length == 0) { - sb.append("selectionArgs is empty; "); - } else { - for (int i = 0; i < selectionArgs.length; ++i) { - sb.append("selectionArgs["); - sb.append(i); - sb.append("] is "); - sb.append(selectionArgs[i]); - sb.append("; "); - } - } - sb.append("sort is "); - sb.append(sort); - sb.append("."); - Log.v(Constants.TAG, sb.toString()); - } - - Cursor ret = qb.query(db, projection, selection, selectionArgs, - null, null, sort); - - if (ret != null) { - ret = new ReadOnlyCursorWrapper(ret); - } - - if (ret != null) { - ret.setNotificationUri(getContext().getContentResolver(), uri); - if (Constants.LOGVV) { - Log.v(Constants.TAG, - "created cursor " + ret + " on behalf of " + Binder.getCallingPid()); - } - } else { - if (Constants.LOGV) { - Log.v(Constants.TAG, "query failed in downloads database"); - } - } - - return ret; - } - - /** - * Updates a row in the database - */ - @Override - public int update(final Uri uri, final ContentValues values, - final String where, final String[] whereArgs) { - - Helpers.validateSelection(where, sAppReadableColumnsSet); - - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - - int count; - long rowId = 0; - boolean startService = false; - - ContentValues filteredValues; - if (Binder.getCallingPid() != Process.myPid()) { - filteredValues = new ContentValues(); - copyString(Downloads.APP_DATA, values, filteredValues); - copyInteger(Downloads.VISIBILITY, values, filteredValues); - Integer i = values.getAsInteger(Downloads.CONTROL); - if (i != null) { - filteredValues.put(Downloads.CONTROL, i); - startService = true; - } - copyInteger(Downloads.CONTROL, values, filteredValues); - copyString(Downloads.TITLE, values, filteredValues); - copyString(Downloads.DESCRIPTION, values, filteredValues); - } else { - filteredValues = values; - } - int match = sURIMatcher.match(uri); - switch (match) { - case DOWNLOADS: - case DOWNLOADS_ID: { - String myWhere; - if (where != null) { - if (match == DOWNLOADS) { - myWhere = "( " + where + " )"; - } else { - myWhere = "( " + where + " ) AND "; - } - } else { - myWhere = ""; - } - if (match == DOWNLOADS_ID) { - String segment = uri.getPathSegments().get(1); - rowId = Long.parseLong(segment); - myWhere += " ( " + Downloads._ID + " = " + rowId + " ) "; - } - if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) { - myWhere += " AND ( " + Constants.UID + "=" + Binder.getCallingUid() + " OR " - + Downloads.OTHER_UID + "=" + Binder.getCallingUid() + " )"; - } - if (filteredValues.size() > 0) { - count = db.update(DB_TABLE, filteredValues, myWhere, whereArgs); - } else { - count = 0; - } - break; - } - default: { - if (Config.LOGD) { - Log.d(Constants.TAG, "updating unknown/invalid URI: " + uri); - } - throw new UnsupportedOperationException("Cannot update URI: " + uri); - } - } - getContext().getContentResolver().notifyChange(uri, null); - if (startService) { - Context context = getContext(); - context.startService(new Intent(context, DownloadService.class)); - } - return count; - } - - /** - * Deletes a row in the database - */ - @Override - public int delete(final Uri uri, final String where, - final String[] whereArgs) { - - Helpers.validateSelection(where, sAppReadableColumnsSet); - - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - int count; - int match = sURIMatcher.match(uri); - switch (match) { - case DOWNLOADS: - case DOWNLOADS_ID: { - String myWhere; - if (where != null) { - if (match == DOWNLOADS) { - myWhere = "( " + where + " )"; - } else { - myWhere = "( " + where + " ) AND "; - } - } else { - myWhere = ""; - } - if (match == DOWNLOADS_ID) { - String segment = uri.getPathSegments().get(1); - long rowId = Long.parseLong(segment); - myWhere += " ( " + Downloads._ID + " = " + rowId + " ) "; - } - if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) { - myWhere += " AND ( " + Constants.UID + "=" + Binder.getCallingUid() + " OR " - + Downloads.OTHER_UID + "=" + Binder.getCallingUid() + " )"; - } - count = db.delete(DB_TABLE, myWhere, whereArgs); - break; - } - default: { - if (Config.LOGD) { - Log.d(Constants.TAG, "deleting unknown/invalid URI: " + uri); - } - throw new UnsupportedOperationException("Cannot delete URI: " + uri); - } - } - getContext().getContentResolver().notifyChange(uri, null); - return count; - } - - /** - * Remotely opens a file - */ - @Override - public ParcelFileDescriptor openFile(Uri uri, String mode) - throws FileNotFoundException { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "openFile uri: " + uri + ", mode: " + mode - + ", uid: " + Binder.getCallingUid()); - Cursor cursor = query(Downloads.CONTENT_URI, new String[] { "_id" }, null, null, "_id"); - if (cursor == null) { - Log.v(Constants.TAG, "null cursor in openFile"); - } else { - if (!cursor.moveToFirst()) { - Log.v(Constants.TAG, "empty cursor in openFile"); - } else { - do { - Log.v(Constants.TAG, "row " + cursor.getInt(0) + " available"); - } while(cursor.moveToNext()); - } - cursor.close(); - } - cursor = query(uri, new String[] { "_data" }, null, null, null); - if (cursor == null) { - Log.v(Constants.TAG, "null cursor in openFile"); - } else { - if (!cursor.moveToFirst()) { - Log.v(Constants.TAG, "empty cursor in openFile"); - } else { - String filename = cursor.getString(0); - Log.v(Constants.TAG, "filename in openFile: " + filename); - if (new java.io.File(filename).isFile()) { - Log.v(Constants.TAG, "file exists in openFile"); - } - } - cursor.close(); - } - } - - // This logic is mostly copied form openFileHelper. If openFileHelper eventually - // gets split into small bits (to extract the filename and the modebits), - // this code could use the separate bits and be deeply simplified. - Cursor c = query(uri, new String[]{"_data"}, null, null, null); - int count = (c != null) ? c.getCount() : 0; - if (count != 1) { - // If there is not exactly one result, throw an appropriate exception. - if (c != null) { - c.close(); - } - if (count == 0) { - throw new FileNotFoundException("No entry for " + uri); - } - throw new FileNotFoundException("Multiple items at " + uri); - } - - c.moveToFirst(); - String path = c.getString(0); - c.close(); - if (path == null) { - throw new FileNotFoundException("No filename found."); - } - if (!Helpers.isFilenameValid(path)) { - throw new FileNotFoundException("Invalid filename."); - } - - if (!"r".equals(mode)) { - throw new FileNotFoundException("Bad mode for " + uri + ": " + mode); - } - ParcelFileDescriptor ret = ParcelFileDescriptor.open(new File(path), - ParcelFileDescriptor.MODE_READ_ONLY); - - if (ret == null) { - if (Constants.LOGV) { - Log.v(Constants.TAG, "couldn't open file"); - } - throw new FileNotFoundException("couldn't open file"); - } else { - ContentValues values = new ContentValues(); - values.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis()); - update(uri, values, null, null); - } - return ret; - } - - private static final void copyInteger(String key, ContentValues from, ContentValues to) { - Integer i = from.getAsInteger(key); - if (i != null) { - to.put(key, i); - } - } - - private static final void copyBoolean(String key, ContentValues from, ContentValues to) { - Boolean b = from.getAsBoolean(key); - if (b != null) { - to.put(key, b); - } - } - - private static final void copyString(String key, ContentValues from, ContentValues to) { - String s = from.getAsString(key); - if (s != null) { - to.put(key, s); - } - } - - private class ReadOnlyCursorWrapper extends CursorWrapper implements CrossProcessCursor { - public ReadOnlyCursorWrapper(Cursor cursor) { - super(cursor); - mCursor = (CrossProcessCursor) cursor; - } - - public boolean deleteRow() { - throw new SecurityException("Download manager cursors are read-only"); - } - - public boolean commitUpdates() { - throw new SecurityException("Download manager cursors are read-only"); - } - - public void fillWindow(int pos, CursorWindow window) { - mCursor.fillWindow(pos, window); - } - - public CursorWindow getWindow() { - return mCursor.getWindow(); - } - - public boolean onMove(int oldPosition, int newPosition) { - return mCursor.onMove(oldPosition, newPosition); - } - - private CrossProcessCursor mCursor; - } - -} diff --git a/src/com/android/providers/downloads/DownloadReceiver.java b/src/com/android/providers/downloads/DownloadReceiver.java deleted file mode 100644 index 03a37186..00000000 --- a/src/com/android/providers/downloads/DownloadReceiver.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.providers.downloads; - -import android.app.NotificationManager; -import android.content.ActivityNotFoundException; -import android.content.BroadcastReceiver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.database.Cursor; -import android.provider.Downloads; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.net.Uri; -import android.util.Config; -import android.util.Log; - -import java.io.File; -import java.util.List; - -/** - * Receives system broadcasts (boot, network connectivity) - */ -public class DownloadReceiver extends BroadcastReceiver { - - public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Receiver onBoot"); - } - context.startService(new Intent(context, DownloadService.class)); - } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Receiver onConnectivity"); - } - NetworkInfo info = (NetworkInfo) - intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); - if (info != null && info.isConnected()) { - context.startService(new Intent(context, DownloadService.class)); - } - } else if (intent.getAction().equals(Constants.ACTION_RETRY)) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Receiver retry"); - } - context.startService(new Intent(context, DownloadService.class)); - } else if (intent.getAction().equals(Constants.ACTION_OPEN) - || intent.getAction().equals(Constants.ACTION_LIST)) { - if (Constants.LOGVV) { - if (intent.getAction().equals(Constants.ACTION_OPEN)) { - Log.v(Constants.TAG, "Receiver open for " + intent.getData()); - } else { - Log.v(Constants.TAG, "Receiver list for " + intent.getData()); - } - } - Cursor cursor = context.getContentResolver().query( - intent.getData(), null, null, null, null); - if (cursor != null) { - if (cursor.moveToFirst()) { - int statusColumn = cursor.getColumnIndexOrThrow(Downloads.STATUS); - int status = cursor.getInt(statusColumn); - int visibilityColumn = cursor.getColumnIndexOrThrow(Downloads.VISIBILITY); - int visibility = cursor.getInt(visibilityColumn); - if (Downloads.isStatusCompleted(status) - && visibility == Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) { - ContentValues values = new ContentValues(); - values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE); - context.getContentResolver().update(intent.getData(), values, null, null); - } - - if (intent.getAction().equals(Constants.ACTION_OPEN)) { - int filenameColumn = cursor.getColumnIndexOrThrow(Downloads._DATA); - int mimetypeColumn = cursor.getColumnIndexOrThrow(Downloads.MIMETYPE); - String filename = cursor.getString(filenameColumn); - String mimetype = cursor.getString(mimetypeColumn); - Uri path = Uri.parse(filename); - // If there is no scheme, then it must be a file - if (path.getScheme() == null) { - path = Uri.fromFile(new File(filename)); - } - Intent activityIntent = new Intent(Intent.ACTION_VIEW); - activityIntent.setDataAndType(path, mimetype); - activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - try { - context.startActivity(activityIntent); - } catch (ActivityNotFoundException ex) { - if (Config.LOGD) { - Log.d(Constants.TAG, "no activity for " + mimetype, ex); - } - // nothing anyone can do about this, but we're in a clean state, - // swallow the exception entirely - } - } else { - int packageColumn = - cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_PACKAGE); - int classColumn = - cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_CLASS); - String pckg = cursor.getString(packageColumn); - String clazz = cursor.getString(classColumn); - if (pckg != null && clazz != null) { - Intent appIntent = new Intent(Downloads.NOTIFICATION_CLICKED_ACTION); - appIntent.setClassName(pckg, clazz); - if (intent.getBooleanExtra("multiple", true)) { - appIntent.setData(Downloads.CONTENT_URI); - } else { - appIntent.setData(intent.getData()); - } - context.sendBroadcast(appIntent); - } - } - } - cursor.close(); - } - NotificationManager notMgr = (NotificationManager) context - .getSystemService(Context.NOTIFICATION_SERVICE); - if (notMgr != null) { - notMgr.cancel((int) ContentUris.parseId(intent.getData())); - } - } else if (intent.getAction().equals(Constants.ACTION_HIDE)) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Receiver hide for " + intent.getData()); - } - Cursor cursor = context.getContentResolver().query( - intent.getData(), null, null, null, null); - if (cursor != null) { - if (cursor.moveToFirst()) { - int statusColumn = cursor.getColumnIndexOrThrow(Downloads.STATUS); - int status = cursor.getInt(statusColumn); - int visibilityColumn = cursor.getColumnIndexOrThrow(Downloads.VISIBILITY); - int visibility = cursor.getInt(visibilityColumn); - if (Downloads.isStatusCompleted(status) - && visibility == Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) { - ContentValues values = new ContentValues(); - values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE); - context.getContentResolver().update(intent.getData(), values, null, null); - } - } - cursor.close(); - } - } - } -} diff --git a/src/com/android/providers/downloads/DownloadService.java b/src/com/android/providers/downloads/DownloadService.java deleted file mode 100644 index 0600cfb6..00000000 --- a/src/com/android/providers/downloads/DownloadService.java +++ /dev/null @@ -1,879 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.providers.downloads; - -import com.google.android.collect.Lists; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.app.Service; -import android.content.ComponentName; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.content.ServiceConnection; -import android.database.ContentObserver; -import android.database.Cursor; -import android.database.CharArrayBuffer; -import android.drm.mobile1.DrmRawContent; -import android.media.IMediaScannerService; -import android.net.Uri; -import android.os.RemoteException; -import android.os.Environment; -import android.os.Handler; -import android.os.IBinder; -import android.os.Process; -import android.provider.Downloads; -import android.util.Config; -import android.util.Log; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - - -/** - * Performs the background downloads requested by applications that use the Downloads provider. - */ -public class DownloadService extends Service { - - /* ------------ Constants ------------ */ - - /* ------------ Members ------------ */ - - /** Observer to get notified when the content observer's data changes */ - private DownloadManagerContentObserver mObserver; - - /** Class to handle Notification Manager updates */ - private DownloadNotification mNotifier; - - /** - * The Service's view of the list of downloads. This is kept independently - * from the content provider, and the Service only initiates downloads - * based on this data, so that it can deal with situation where the data - * in the content provider changes or disappears. - */ - private ArrayList mDownloads; - - /** - * The thread that updates the internal download list from the content - * provider. - */ - private UpdateThread updateThread; - - /** - * Whether the internal download list should be updated from the content - * provider. - */ - private boolean pendingUpdate; - - /** - * The ServiceConnection object that tells us when we're connected to and disconnected from - * the Media Scanner - */ - private MediaScannerConnection mMediaScannerConnection; - - private boolean mMediaScannerConnecting; - - /** - * The IPC interface to the Media Scanner - */ - private IMediaScannerService mMediaScannerService; - - /** - * Array used when extracting strings from content provider - */ - private CharArrayBuffer oldChars; - - /** - * Array used when extracting strings from content provider - */ - private CharArrayBuffer newChars; - - /* ------------ Inner Classes ------------ */ - - /** - * Receives notifications when the data in the content provider changes - */ - private class DownloadManagerContentObserver extends ContentObserver { - - public DownloadManagerContentObserver() { - super(new Handler()); - } - - /** - * Receives notification when the data in the observed content - * provider changes. - */ - public void onChange(final boolean selfChange) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Service ContentObserver received notification"); - } - updateFromProvider(); - } - - } - - /** - * Gets called back when the connection to the media - * scanner is established or lost. - */ - public class MediaScannerConnection implements ServiceConnection { - public void onServiceConnected(ComponentName className, IBinder service) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Connected to Media Scanner"); - } - mMediaScannerConnecting = false; - synchronized (DownloadService.this) { - mMediaScannerService = IMediaScannerService.Stub.asInterface(service); - if (mMediaScannerService != null) { - updateFromProvider(); - } - } - } - - public void disconnectMediaScanner() { - synchronized (DownloadService.this) { - if (mMediaScannerService != null) { - mMediaScannerService = null; - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Disconnecting from Media Scanner"); - } - try { - unbindService(this); - } catch (IllegalArgumentException ex) { - if (Constants.LOGV) { - Log.v(Constants.TAG, "unbindService threw up: " + ex); - } - } - } - } - } - - public void onServiceDisconnected(ComponentName className) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Disconnected from Media Scanner"); - } - synchronized (DownloadService.this) { - mMediaScannerService = null; - } - } - } - - /* ------------ Methods ------------ */ - - /** - * Returns an IBinder instance when someone wants to connect to this - * service. Binding to this service is not allowed. - * - * @throws UnsupportedOperationException - */ - public IBinder onBind(Intent i) { - throw new UnsupportedOperationException("Cannot bind to Download Manager Service"); - } - - /** - * Initializes the service when it is first created - */ - public void onCreate() { - super.onCreate(); - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Service onCreate"); - } - - mDownloads = Lists.newArrayList(); - - mObserver = new DownloadManagerContentObserver(); - getContentResolver().registerContentObserver(Downloads.CONTENT_URI, - true, mObserver); - - mMediaScannerService = null; - mMediaScannerConnecting = false; - mMediaScannerConnection = new MediaScannerConnection(); - - mNotifier = new DownloadNotification(this); - mNotifier.mNotificationMgr.cancelAll(); - mNotifier.updateNotification(); - - trimDatabase(); - removeSpuriousFiles(); - updateFromProvider(); - } - - /** - * Responds to a call to startService - */ - public void onStart(Intent intent, int startId) { - super.onStart(intent, startId); - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Service onStart"); - } - - updateFromProvider(); - } - - /** - * Cleans up when the service is destroyed - */ - public void onDestroy() { - getContentResolver().unregisterContentObserver(mObserver); - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Service onDestroy"); - } - super.onDestroy(); - } - - /** - * Parses data from the content provider into private array - */ - private void updateFromProvider() { - synchronized (this) { - pendingUpdate = true; - if (updateThread == null) { - updateThread = new UpdateThread(); - updateThread.start(); - } - } - } - - private class UpdateThread extends Thread { - public UpdateThread() { - super("Download Service"); - } - - public void run() { - Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - - boolean keepService = false; - // for each update from the database, remember which download is - // supposed to get restarted soonest in the future - long wakeUp = Long.MAX_VALUE; - for (;;) { - synchronized (DownloadService.this) { - if (updateThread != this) { - throw new IllegalStateException( - "multiple UpdateThreads in DownloadService"); - } - if (!pendingUpdate) { - updateThread = null; - if (!keepService) { - stopSelf(); - } - if (wakeUp != Long.MAX_VALUE) { - AlarmManager alarms = - (AlarmManager) getSystemService(Context.ALARM_SERVICE); - if (alarms == null) { - Log.e(Constants.TAG, "couldn't get alarm manager"); - } else { - if (Constants.LOGV) { - Log.v(Constants.TAG, "scheduling retry in " + wakeUp + "ms"); - } - Intent intent = new Intent(Constants.ACTION_RETRY); - intent.setClassName("com.android.providers.downloads", - DownloadReceiver.class.getName()); - alarms.set( - AlarmManager.RTC_WAKEUP, - System.currentTimeMillis() + wakeUp, - PendingIntent.getBroadcast(DownloadService.this, 0, intent, - PendingIntent.FLAG_ONE_SHOT)); - } - } - oldChars = null; - newChars = null; - return; - } - pendingUpdate = false; - } - boolean networkAvailable = Helpers.isNetworkAvailable(DownloadService.this); - boolean networkRoaming = Helpers.isNetworkRoaming(DownloadService.this); - long now = System.currentTimeMillis(); - - Cursor cursor = getContentResolver().query(Downloads.CONTENT_URI, - null, null, null, Downloads._ID); - - if (cursor == null) { - return; - } - - cursor.moveToFirst(); - - int arrayPos = 0; - - boolean mustScan = false; - keepService = false; - wakeUp = Long.MAX_VALUE; - - boolean isAfterLast = cursor.isAfterLast(); - - int idColumn = cursor.getColumnIndexOrThrow(Downloads._ID); - - /* - * Walk the cursor and the local array to keep them in sync. The key - * to the algorithm is that the ids are unique and sorted both in - * the cursor and in the array, so that they can be processed in - * order in both sources at the same time: at each step, both - * sources point to the lowest id that hasn't been processed from - * that source, and the algorithm processes the lowest id from - * those two possibilities. - * At each step: - * -If the array contains an entry that's not in the cursor, remove the - * entry, move to next entry in the array. - * -If the array contains an entry that's in the cursor, nothing to do, - * move to next cursor row and next array entry. - * -If the cursor contains an entry that's not in the array, insert - * a new entry in the array, move to next cursor row and next - * array entry. - */ - while (!isAfterLast || arrayPos < mDownloads.size()) { - if (isAfterLast) { - // We're beyond the end of the cursor but there's still some - // stuff in the local array, which can only be junk - if (Constants.LOGVV) { - int arrayId = ((DownloadInfo) mDownloads.get(arrayPos)).id; - Log.v(Constants.TAG, "Array update: trimming " + - arrayId + " @ " + arrayPos); - } - if (shouldScanFile(arrayPos) && mediaScannerConnected()) { - scanFile(null, arrayPos); - } - deleteDownload(arrayPos); // this advances in the array - } else { - int id = cursor.getInt(idColumn); - - if (arrayPos == mDownloads.size()) { - insertDownload(cursor, arrayPos, networkAvailable, networkRoaming, now); - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Array update: inserting " + - id + " @ " + arrayPos); - } - if (shouldScanFile(arrayPos) - && (!mediaScannerConnected() || !scanFile(cursor, arrayPos))) { - mustScan = true; - keepService = true; - } - if (visibleNotification(arrayPos)) { - keepService = true; - } - long next = nextAction(arrayPos, now); - if (next == 0) { - keepService = true; - } else if (next > 0 && next < wakeUp) { - wakeUp = next; - } - ++arrayPos; - cursor.moveToNext(); - isAfterLast = cursor.isAfterLast(); - } else { - int arrayId = mDownloads.get(arrayPos).id; - - if (arrayId < id) { - // The array entry isn't in the cursor - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Array update: removing " + arrayId - + " @ " + arrayPos); - } - if (shouldScanFile(arrayPos) && mediaScannerConnected()) { - scanFile(null, arrayPos); - } - deleteDownload(arrayPos); // this advances in the array - } else if (arrayId == id) { - // This cursor row already exists in the stored array - updateDownload( - cursor, arrayPos, - networkAvailable, networkRoaming, now); - if (shouldScanFile(arrayPos) - && (!mediaScannerConnected() - || !scanFile(cursor, arrayPos))) { - mustScan = true; - keepService = true; - } - if (visibleNotification(arrayPos)) { - keepService = true; - } - long next = nextAction(arrayPos, now); - if (next == 0) { - keepService = true; - } else if (next > 0 && next < wakeUp) { - wakeUp = next; - } - ++arrayPos; - cursor.moveToNext(); - isAfterLast = cursor.isAfterLast(); - } else { - // This cursor entry didn't exist in the stored array - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Array update: appending " + - id + " @ " + arrayPos); - } - insertDownload( - cursor, arrayPos, - networkAvailable, networkRoaming, now); - if (shouldScanFile(arrayPos) - && (!mediaScannerConnected() - || !scanFile(cursor, arrayPos))) { - mustScan = true; - keepService = true; - } - if (visibleNotification(arrayPos)) { - keepService = true; - } - long next = nextAction(arrayPos, now); - if (next == 0) { - keepService = true; - } else if (next > 0 && next < wakeUp) { - wakeUp = next; - } - ++arrayPos; - cursor.moveToNext(); - isAfterLast = cursor.isAfterLast(); - } - } - } - } - - mNotifier.updateNotification(); - - if (mustScan) { - if (!mMediaScannerConnecting) { - Intent intent = new Intent(); - intent.setClassName("com.android.providers.media", - "com.android.providers.media.MediaScannerService"); - mMediaScannerConnecting = true; - bindService(intent, mMediaScannerConnection, BIND_AUTO_CREATE); - } - } else { - mMediaScannerConnection.disconnectMediaScanner(); - } - - cursor.close(); - } - } - } - - /** - * Removes files that may have been left behind in the cache directory - */ - private void removeSpuriousFiles() { - File[] files = Environment.getDownloadCacheDirectory().listFiles(); - if (files == null) { - // The cache folder doesn't appear to exist (this is likely the case - // when running the simulator). - return; - } - HashSet fileSet = new HashSet(); - for (int i = 0; i < files.length; i++) { - if (files[i].getName().equals(Constants.KNOWN_SPURIOUS_FILENAME)) { - continue; - } - if (files[i].getName().equalsIgnoreCase(Constants.RECOVERY_DIRECTORY)) { - continue; - } - fileSet.add(files[i].getPath()); - } - - Cursor cursor = getContentResolver().query(Downloads.CONTENT_URI, - new String[] { Downloads._DATA }, null, null, null); - if (cursor != null) { - if (cursor.moveToFirst()) { - do { - fileSet.remove(cursor.getString(0)); - } while (cursor.moveToNext()); - } - cursor.close(); - } - Iterator iterator = fileSet.iterator(); - while (iterator.hasNext()) { - String filename = iterator.next(); - if (Constants.LOGV) { - Log.v(Constants.TAG, "deleting spurious file " + filename); - } - new File(filename).delete(); - } - } - - /** - * Drops old rows from the database to prevent it from growing too large - */ - private void trimDatabase() { - Cursor cursor = getContentResolver().query(Downloads.CONTENT_URI, - new String[] { Downloads._ID }, - Downloads.STATUS + " >= '200'", null, - Downloads.LAST_MODIFICATION); - if (cursor == null) { - // This isn't good - if we can't do basic queries in our database, nothing's gonna work - Log.e(Constants.TAG, "null cursor in trimDatabase"); - return; - } - if (cursor.moveToFirst()) { - int numDelete = cursor.getCount() - Constants.MAX_DOWNLOADS; - int columnId = cursor.getColumnIndexOrThrow(Downloads._ID); - while (numDelete > 0) { - getContentResolver().delete( - ContentUris.withAppendedId(Downloads.CONTENT_URI, cursor.getLong(columnId)), - null, null); - if (!cursor.moveToNext()) { - break; - } - numDelete--; - } - } - cursor.close(); - } - - /** - * Keeps a local copy of the info about a download, and initiates the - * download if appropriate. - */ - private void insertDownload( - Cursor cursor, int arrayPos, - boolean networkAvailable, boolean networkRoaming, long now) { - int statusColumn = cursor.getColumnIndexOrThrow(Downloads.STATUS); - int failedColumn = cursor.getColumnIndexOrThrow(Constants.FAILED_CONNECTIONS); - int retryRedirect = - cursor.getInt(cursor.getColumnIndexOrThrow(Constants.RETRY_AFTER___REDIRECT_COUNT)); - DownloadInfo info = new DownloadInfo( - cursor.getInt(cursor.getColumnIndexOrThrow(Downloads._ID)), - cursor.getString(cursor.getColumnIndexOrThrow(Downloads.URI)), - cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.NO_INTEGRITY)) == 1, - cursor.getString(cursor.getColumnIndexOrThrow(Downloads.FILENAME_HINT)), - cursor.getString(cursor.getColumnIndexOrThrow(Downloads._DATA)), - cursor.getString(cursor.getColumnIndexOrThrow(Downloads.MIMETYPE)), - cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.DESTINATION)), - cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.VISIBILITY)), - cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.CONTROL)), - cursor.getInt(statusColumn), - cursor.getInt(failedColumn), - retryRedirect & 0xfffffff, - retryRedirect >> 28, - cursor.getLong(cursor.getColumnIndexOrThrow(Downloads.LAST_MODIFICATION)), - cursor.getString(cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_PACKAGE)), - cursor.getString(cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_CLASS)), - cursor.getString(cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_EXTRAS)), - cursor.getString(cursor.getColumnIndexOrThrow(Downloads.COOKIE_DATA)), - cursor.getString(cursor.getColumnIndexOrThrow(Downloads.USER_AGENT)), - cursor.getString(cursor.getColumnIndexOrThrow(Downloads.REFERER)), - cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.TOTAL_BYTES)), - cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.CURRENT_BYTES)), - cursor.getString(cursor.getColumnIndexOrThrow(Constants.ETAG)), - cursor.getInt(cursor.getColumnIndexOrThrow(Constants.MEDIA_SCANNED)) == 1); - - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Service adding new entry"); - Log.v(Constants.TAG, "ID : " + info.id); - Log.v(Constants.TAG, "URI : " + ((info.uri != null) ? "yes" : "no")); - Log.v(Constants.TAG, "NO_INTEG: " + info.noIntegrity); - Log.v(Constants.TAG, "HINT : " + info.hint); - Log.v(Constants.TAG, "FILENAME: " + info.filename); - Log.v(Constants.TAG, "MIMETYPE: " + info.mimetype); - Log.v(Constants.TAG, "DESTINAT: " + info.destination); - Log.v(Constants.TAG, "VISIBILI: " + info.visibility); - Log.v(Constants.TAG, "CONTROL : " + info.control); - Log.v(Constants.TAG, "STATUS : " + info.status); - Log.v(Constants.TAG, "FAILED_C: " + info.numFailed); - Log.v(Constants.TAG, "RETRY_AF: " + info.retryAfter); - Log.v(Constants.TAG, "REDIRECT: " + info.redirectCount); - Log.v(Constants.TAG, "LAST_MOD: " + info.lastMod); - Log.v(Constants.TAG, "PACKAGE : " + info.pckg); - Log.v(Constants.TAG, "CLASS : " + info.clazz); - Log.v(Constants.TAG, "COOKIES : " + ((info.cookies != null) ? "yes" : "no")); - Log.v(Constants.TAG, "AGENT : " + info.userAgent); - Log.v(Constants.TAG, "REFERER : " + ((info.referer != null) ? "yes" : "no")); - Log.v(Constants.TAG, "TOTAL : " + info.totalBytes); - Log.v(Constants.TAG, "CURRENT : " + info.currentBytes); - Log.v(Constants.TAG, "ETAG : " + info.etag); - Log.v(Constants.TAG, "SCANNED : " + info.mediaScanned); - } - - mDownloads.add(arrayPos, info); - - if (info.status == 0 - && (info.destination == Downloads.DESTINATION_EXTERNAL - || info.destination == Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE) - && info.mimetype != null - && !DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(info.mimetype)) { - // Check to see if we are allowed to download this file. Only files - // that can be handled by the platform can be downloaded. - // special case DRM files, which we should always allow downloading. - Intent mimetypeIntent = new Intent(Intent.ACTION_VIEW); - - // We can provide data as either content: or file: URIs, - // so allow both. (I think it would be nice if we just did - // everything as content: URIs) - // Actually, right now the download manager's UId restrictions - // prevent use from using content: so it's got to be file: or - // nothing - - mimetypeIntent.setDataAndType(Uri.fromParts("file", "", null), info.mimetype); - ResolveInfo ri = getPackageManager().resolveActivity(mimetypeIntent, - PackageManager.MATCH_DEFAULT_ONLY); - //Log.i(Constants.TAG, "*** QUERY " + mimetypeIntent + ": " + list); - - if (ri == null) { - if (Config.LOGD) { - Log.d(Constants.TAG, "no application to handle MIME type " + info.mimetype); - } - info.status = Downloads.STATUS_NOT_ACCEPTABLE; - - Uri uri = ContentUris.withAppendedId(Downloads.CONTENT_URI, info.id); - ContentValues values = new ContentValues(); - values.put(Downloads.STATUS, Downloads.STATUS_NOT_ACCEPTABLE); - getContentResolver().update(uri, values, null, null); - info.sendIntentIfRequested(uri, this); - return; - } - } - - if (info.canUseNetwork(networkAvailable, networkRoaming)) { - if (info.isReadyToStart(now)) { - if (Constants.LOGV) { - Log.v(Constants.TAG, "Service spawning thread to handle new download " + - info.id); - } - if (info.hasActiveThread) { - throw new IllegalStateException("Multiple threads on same download on insert"); - } - if (info.status != Downloads.STATUS_RUNNING) { - info.status = Downloads.STATUS_RUNNING; - ContentValues values = new ContentValues(); - values.put(Downloads.STATUS, info.status); - getContentResolver().update( - ContentUris.withAppendedId(Downloads.CONTENT_URI, info.id), - values, null, null); - } - DownloadThread downloader = new DownloadThread(this, info); - info.hasActiveThread = true; - downloader.start(); - } - } else { - if (info.status == 0 - || info.status == Downloads.STATUS_PENDING - || info.status == Downloads.STATUS_RUNNING) { - info.status = Downloads.STATUS_RUNNING_PAUSED; - Uri uri = ContentUris.withAppendedId(Downloads.CONTENT_URI, info.id); - ContentValues values = new ContentValues(); - values.put(Downloads.STATUS, Downloads.STATUS_RUNNING_PAUSED); - getContentResolver().update(uri, values, null, null); - } - } - } - - /** - * Updates the local copy of the info about a download. - */ - private void updateDownload( - Cursor cursor, int arrayPos, - boolean networkAvailable, boolean networkRoaming, long now) { - DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); - int statusColumn = cursor.getColumnIndexOrThrow(Downloads.STATUS); - int failedColumn = cursor.getColumnIndexOrThrow(Constants.FAILED_CONNECTIONS); - info.id = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads._ID)); - info.uri = stringFromCursor(info.uri, cursor, Downloads.URI); - info.noIntegrity = - cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.NO_INTEGRITY)) == 1; - info.hint = stringFromCursor(info.hint, cursor, Downloads.FILENAME_HINT); - info.filename = stringFromCursor(info.filename, cursor, Downloads._DATA); - info.mimetype = stringFromCursor(info.mimetype, cursor, Downloads.MIMETYPE); - info.destination = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.DESTINATION)); - int newVisibility = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.VISIBILITY)); - if (info.visibility == Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED - && newVisibility != Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED - && Downloads.isStatusCompleted(info.status)) { - mNotifier.mNotificationMgr.cancel(info.id); - } - info.visibility = newVisibility; - synchronized(info) { - info.control = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.CONTROL)); - } - int newStatus = cursor.getInt(statusColumn); - if (!Downloads.isStatusCompleted(info.status) && Downloads.isStatusCompleted(newStatus)) { - mNotifier.mNotificationMgr.cancel(info.id); - } - info.status = newStatus; - info.numFailed = cursor.getInt(failedColumn); - int retryRedirect = - cursor.getInt(cursor.getColumnIndexOrThrow(Constants.RETRY_AFTER___REDIRECT_COUNT)); - info.retryAfter = retryRedirect & 0xfffffff; - info.redirectCount = retryRedirect >> 28; - info.lastMod = cursor.getLong(cursor.getColumnIndexOrThrow(Downloads.LAST_MODIFICATION)); - info.pckg = stringFromCursor(info.pckg, cursor, Downloads.NOTIFICATION_PACKAGE); - info.clazz = stringFromCursor(info.clazz, cursor, Downloads.NOTIFICATION_CLASS); - info.cookies = stringFromCursor(info.cookies, cursor, Downloads.COOKIE_DATA); - info.userAgent = stringFromCursor(info.userAgent, cursor, Downloads.USER_AGENT); - info.referer = stringFromCursor(info.referer, cursor, Downloads.REFERER); - info.totalBytes = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.TOTAL_BYTES)); - info.currentBytes = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.CURRENT_BYTES)); - info.etag = stringFromCursor(info.etag, cursor, Constants.ETAG); - info.mediaScanned = - cursor.getInt(cursor.getColumnIndexOrThrow(Constants.MEDIA_SCANNED)) == 1; - - if (info.canUseNetwork(networkAvailable, networkRoaming)) { - if (info.isReadyToRestart(now)) { - if (Constants.LOGV) { - Log.v(Constants.TAG, "Service spawning thread to handle updated download " + - info.id); - } - if (info.hasActiveThread) { - throw new IllegalStateException("Multiple threads on same download on update"); - } - info.status = Downloads.STATUS_RUNNING; - ContentValues values = new ContentValues(); - values.put(Downloads.STATUS, info.status); - getContentResolver().update( - ContentUris.withAppendedId(Downloads.CONTENT_URI, info.id), - values, null, null); - DownloadThread downloader = new DownloadThread(this, info); - info.hasActiveThread = true; - downloader.start(); - } - } - } - - /** - * Returns a String that holds the current value of the column, - * optimizing for the case where the value hasn't changed. - */ - private String stringFromCursor(String old, Cursor cursor, String column) { - int index = cursor.getColumnIndexOrThrow(column); - if (old == null) { - return cursor.getString(index); - } - if (newChars == null) { - newChars = new CharArrayBuffer(128); - } - cursor.copyStringToBuffer(index, newChars); - int length = newChars.sizeCopied; - if (length != old.length()) { - return cursor.getString(index); - } - if (oldChars == null || oldChars.sizeCopied < length) { - oldChars = new CharArrayBuffer(length); - } - char[] oldArray = oldChars.data; - char[] newArray = newChars.data; - old.getChars(0, length, oldArray, 0); - for (int i = length - 1; i >= 0; --i) { - if (oldArray[i] != newArray[i]) { - return new String(newArray, 0, length); - } - } - return old; - } - - /** - * Removes the local copy of the info about a download. - */ - private void deleteDownload(int arrayPos) { - DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); - if (info.status == Downloads.STATUS_RUNNING) { - info.status = Downloads.STATUS_CANCELED; - } else if (info.destination != Downloads.DESTINATION_EXTERNAL && info.filename != null) { - new File(info.filename).delete(); - } - mNotifier.mNotificationMgr.cancel(info.id); - - mDownloads.remove(arrayPos); - } - - /** - * Returns the amount of time (as measured from the "now" parameter) - * at which a download will be active. - * 0 = immediately - service should stick around to handle this download. - * -1 = never - service can go away without ever waking up. - * positive value - service must wake up in the future, as specified in ms from "now" - */ - private long nextAction(int arrayPos, long now) { - DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); - if (Downloads.isStatusCompleted(info.status)) { - return -1; - } - if (info.status != Downloads.STATUS_RUNNING_PAUSED) { - return 0; - } - if (info.numFailed == 0) { - return 0; - } - long when = info.restartTime(); - if (when <= now) { - return 0; - } - return when - now; - } - - /** - * Returns whether there's a visible notification for this download - */ - private boolean visibleNotification(int arrayPos) { - DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); - return info.hasCompletionNotification(); - } - - /** - * Returns whether a file should be scanned - */ - private boolean shouldScanFile(int arrayPos) { - DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); - return !info.mediaScanned - && info.destination == Downloads.DESTINATION_EXTERNAL - && Downloads.isStatusSuccess(info.status) - && !DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(info.mimetype); - } - - /** - * Returns whether we have a live connection to the Media Scanner - */ - private boolean mediaScannerConnected() { - return mMediaScannerService != null; - } - - /** - * Attempts to scan the file if necessary. - * Returns true if the file has been properly scanned. - */ - private boolean scanFile(Cursor cursor, int arrayPos) { - DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); - synchronized (this) { - if (mMediaScannerService != null) { - try { - if (Constants.LOGV) { - Log.v(Constants.TAG, "Scanning file " + info.filename); - } - mMediaScannerService.scanFile(info.filename, info.mimetype); - if (cursor != null) { - ContentValues values = new ContentValues(); - values.put(Constants.MEDIA_SCANNED, 1); - getContentResolver().update( - ContentUris.withAppendedId(Downloads.CONTENT_URI, - cursor.getLong(cursor.getColumnIndexOrThrow(Downloads._ID))), - values, null, null); - } - return true; - } catch (RemoteException e) { - if (Config.LOGD) { - Log.d(Constants.TAG, "Failed to scan file " + info.filename); - } - } - } - } - return false; - } - -} diff --git a/src/com/android/providers/downloads/DownloadThread.java b/src/com/android/providers/downloads/DownloadThread.java deleted file mode 100644 index 923e36d1..00000000 --- a/src/com/android/providers/downloads/DownloadThread.java +++ /dev/null @@ -1,710 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.providers.downloads; - -import org.apache.http.client.methods.AbortableHttpRequest; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.HttpClient; -import org.apache.http.entity.StringEntity; -import org.apache.http.Header; -import org.apache.http.HttpResponse; - -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.drm.mobile1.DrmRawContent; -import android.net.http.AndroidHttpClient; -import android.net.Uri; -import android.os.FileUtils; -import android.os.PowerManager; -import android.os.Process; -import android.provider.Downloads; -import android.provider.DrmStore; -import android.util.Config; -import android.util.Log; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URI; - -/** - * Runs an actual download - */ -public class DownloadThread extends Thread { - - private Context mContext; - private DownloadInfo mInfo; - - public DownloadThread(Context context, DownloadInfo info) { - mContext = context; - mInfo = info; - } - - /** - * Returns the user agent provided by the initiating app, or use the default one - */ - private String userAgent() { - String userAgent = mInfo.userAgent; - if (userAgent != null) { - } - if (userAgent == null) { - userAgent = Constants.DEFAULT_USER_AGENT; - } - return userAgent; - } - - /** - * Executes the download in a separate thread - */ - public void run() { - Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - - int finalStatus = Downloads.STATUS_UNKNOWN_ERROR; - boolean countRetry = false; - int retryAfter = 0; - int redirectCount = mInfo.redirectCount; - String newUri = null; - boolean gotData = false; - String filename = null; - String mimeType = mInfo.mimetype; - FileOutputStream stream = null; - AndroidHttpClient client = null; - PowerManager.WakeLock wakeLock = null; - Uri contentUri = Uri.parse(Downloads.CONTENT_URI + "/" + mInfo.id); - - try { - boolean continuingDownload = false; - String headerAcceptRanges = null; - String headerContentDisposition = null; - String headerContentLength = null; - String headerContentLocation = null; - String headerETag = null; - String headerTransferEncoding = null; - - byte data[] = new byte[Constants.BUFFER_SIZE]; - - int bytesSoFar = 0; - - PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); - wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); - wakeLock.acquire(); - - filename = mInfo.filename; - if (filename != null) { - if (!Helpers.isFilenameValid(filename)) { - finalStatus = Downloads.STATUS_FILE_ERROR; - notifyDownloadCompleted( - finalStatus, false, 0, 0, false, filename, null, mInfo.mimetype); - return; - } - // We're resuming a download that got interrupted - File f = new File(filename); - if (f.exists()) { - long fileLength = f.length(); - if (fileLength == 0) { - // The download hadn't actually started, we can restart from scratch - f.delete(); - filename = null; - } else if (mInfo.etag == null && !mInfo.noIntegrity) { - // Tough luck, that's not a resumable download - if (Config.LOGD) { - Log.d(Constants.TAG, - "can't resume interrupted non-resumable download"); - } - f.delete(); - finalStatus = Downloads.STATUS_PRECONDITION_FAILED; - notifyDownloadCompleted( - finalStatus, false, 0, 0, false, filename, null, mInfo.mimetype); - return; - } else { - // All right, we'll be able to resume this download - stream = new FileOutputStream(filename, true); - bytesSoFar = (int) fileLength; - if (mInfo.totalBytes != -1) { - headerContentLength = Integer.toString(mInfo.totalBytes); - } - headerETag = mInfo.etag; - continuingDownload = true; - } - } - } - - int bytesNotified = bytesSoFar; - // starting with MIN_VALUE means that the first write will commit - // progress to the database - long timeLastNotification = 0; - - client = AndroidHttpClient.newInstance(userAgent()); - - if (stream != null && mInfo.destination == Downloads.DESTINATION_EXTERNAL - && !DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING - .equalsIgnoreCase(mimeType)) { - try { - stream.close(); - stream = null; - } catch (IOException ex) { - if (Constants.LOGV) { - Log.v(Constants.TAG, "exception when closing the file before download : " + - ex); - } - // nothing can really be done if the file can't be closed - } - } - - /* - * This loop is run once for every individual HTTP request that gets sent. - * The very first HTTP request is a "virgin" request, while every subsequent - * request is done with the original ETag and a byte-range. - */ -http_request_loop: - while (true) { - // Prepares the request and fires it. - HttpGet request = new HttpGet(mInfo.uri); - - if (Constants.LOGV) { - Log.v(Constants.TAG, "initiating download for " + mInfo.uri); - } - - if (mInfo.cookies != null) { - request.addHeader("Cookie", mInfo.cookies); - } - if (mInfo.referer != null) { - request.addHeader("Referer", mInfo.referer); - } - if (continuingDownload) { - if (headerETag != null) { - request.addHeader("If-Match", headerETag); - } - request.addHeader("Range", "bytes=" + bytesSoFar + "-"); - } - - HttpResponse response; - try { - response = client.execute(request); - } catch (IllegalArgumentException ex) { - if (Constants.LOGV) { - Log.d(Constants.TAG, "Arg exception trying to execute request for " + - mInfo.uri + " : " + ex); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "Arg exception trying to execute request for " + - mInfo.id + " : " + ex); - } - finalStatus = Downloads.STATUS_BAD_REQUEST; - request.abort(); - break http_request_loop; - } catch (IOException ex) { - if (!Helpers.isNetworkAvailable(mContext)) { - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - } else if (mInfo.numFailed < Constants.MAX_RETRIES) { - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - countRetry = true; - } else { - if (Constants.LOGV) { - Log.d(Constants.TAG, "IOException trying to execute request for " + - mInfo.uri + " : " + ex); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "IOException trying to execute request for " + - mInfo.id + " : " + ex); - } - finalStatus = Downloads.STATUS_HTTP_DATA_ERROR; - } - request.abort(); - break http_request_loop; - } - - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode == 503 && mInfo.numFailed < Constants.MAX_RETRIES) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "got HTTP response code 503"); - } - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - countRetry = true; - Header header = response.getFirstHeader("Retry-After"); - if (header != null) { - try { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Retry-After :" + header.getValue()); - } - retryAfter = Integer.parseInt(header.getValue()); - if (retryAfter < 0) { - retryAfter = 0; - } else { - if (retryAfter < Constants.MIN_RETRY_AFTER) { - retryAfter = Constants.MIN_RETRY_AFTER; - } else if (retryAfter > Constants.MAX_RETRY_AFTER) { - retryAfter = Constants.MAX_RETRY_AFTER; - } - retryAfter += Helpers.rnd.nextInt(Constants.MIN_RETRY_AFTER + 1); - retryAfter *= 1000; - } - } catch (NumberFormatException ex) { - // ignored - retryAfter stays 0 in this case. - } - } - request.abort(); - break http_request_loop; - } - if (statusCode == 301 || - statusCode == 302 || - statusCode == 303 || - statusCode == 307) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "got HTTP redirect " + statusCode); - } - if (redirectCount >= Constants.MAX_REDIRECTS) { - if (Constants.LOGV) { - Log.d(Constants.TAG, "too many redirects for download " + mInfo.id + - " at " + mInfo.uri); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "too many redirects for download " + mInfo.id); - } - finalStatus = Downloads.STATUS_TOO_MANY_REDIRECTS; - request.abort(); - break http_request_loop; - } - Header header = response.getFirstHeader("Location"); - if (header != null) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Location :" + header.getValue()); - } - newUri = new URI(mInfo.uri).resolve(new URI(header.getValue())).toString(); - ++redirectCount; - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - request.abort(); - break http_request_loop; - } - } - if ((!continuingDownload && statusCode != Downloads.STATUS_SUCCESS) - || (continuingDownload && statusCode != 206)) { - if (Constants.LOGV) { - Log.d(Constants.TAG, "http error " + statusCode + " for " + mInfo.uri); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "http error " + statusCode + " for download " + - mInfo.id); - } - if (Downloads.isStatusError(statusCode)) { - finalStatus = statusCode; - } else if (statusCode >= 300 && statusCode < 400) { - finalStatus = Downloads.STATUS_UNHANDLED_REDIRECT; - } else if (continuingDownload && statusCode == Downloads.STATUS_SUCCESS) { - finalStatus = Downloads.STATUS_PRECONDITION_FAILED; - } else { - finalStatus = Downloads.STATUS_UNHANDLED_HTTP_CODE; - } - request.abort(); - break http_request_loop; - } else { - // Handles the response, saves the file - if (Constants.LOGV) { - Log.v(Constants.TAG, "received response for " + mInfo.uri); - } - - if (!continuingDownload) { - Header header = response.getFirstHeader("Accept-Ranges"); - if (header != null) { - headerAcceptRanges = header.getValue(); - } - header = response.getFirstHeader("Content-Disposition"); - if (header != null) { - headerContentDisposition = header.getValue(); - } - header = response.getFirstHeader("Content-Location"); - if (header != null) { - headerContentLocation = header.getValue(); - } - if (mimeType == null) { - header = response.getFirstHeader("Content-Type"); - if (header != null) { - mimeType = header.getValue(); - final int semicolonIndex = mimeType.indexOf(';'); - if (semicolonIndex != -1) { - mimeType = mimeType.substring(0, semicolonIndex); - } - } - } - header = response.getFirstHeader("ETag"); - if (header != null) { - headerETag = header.getValue(); - } - header = response.getFirstHeader("Transfer-Encoding"); - if (header != null) { - headerTransferEncoding = header.getValue(); - } - if (headerTransferEncoding == null) { - header = response.getFirstHeader("Content-Length"); - if (header != null) { - headerContentLength = header.getValue(); - } - } else { - // Ignore content-length with transfer-encoding - 2616 4.4 3 - if (Constants.LOGVV) { - Log.v(Constants.TAG, - "ignoring content-length because of xfer-encoding"); - } - } - if (Constants.LOGVV) { - Log.v(Constants.TAG, "Accept-Ranges: " + headerAcceptRanges); - Log.v(Constants.TAG, "Content-Disposition: " + - headerContentDisposition); - Log.v(Constants.TAG, "Content-Length: " + headerContentLength); - Log.v(Constants.TAG, "Content-Location: " + headerContentLocation); - Log.v(Constants.TAG, "Content-Type: " + mimeType); - Log.v(Constants.TAG, "ETag: " + headerETag); - Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding); - } - - if (!mInfo.noIntegrity && headerContentLength == null && - (headerTransferEncoding == null - || !headerTransferEncoding.equalsIgnoreCase("chunked")) - ) { - if (Config.LOGD) { - Log.d(Constants.TAG, "can't know size of download, giving up"); - } - finalStatus = Downloads.STATUS_LENGTH_REQUIRED; - request.abort(); - break http_request_loop; - } - - DownloadFileInfo fileInfo = Helpers.generateSaveFile( - mContext, - mInfo.uri, - mInfo.hint, - headerContentDisposition, - headerContentLocation, - mimeType, - mInfo.destination, - (headerContentLength != null) ? - Integer.parseInt(headerContentLength) : 0); - if (fileInfo.filename == null) { - finalStatus = fileInfo.status; - request.abort(); - break http_request_loop; - } - filename = fileInfo.filename; - stream = fileInfo.stream; - if (Constants.LOGV) { - Log.v(Constants.TAG, "writing " + mInfo.uri + " to " + filename); - } - - ContentValues values = new ContentValues(); - values.put(Downloads._DATA, filename); - if (headerETag != null) { - values.put(Constants.ETAG, headerETag); - } - if (mimeType != null) { - values.put(Downloads.MIMETYPE, mimeType); - } - int contentLength = -1; - if (headerContentLength != null) { - contentLength = Integer.parseInt(headerContentLength); - } - values.put(Downloads.TOTAL_BYTES, contentLength); - mContext.getContentResolver().update(contentUri, values, null, null); - } - - InputStream entityStream; - try { - entityStream = response.getEntity().getContent(); - } catch (IOException ex) { - if (!Helpers.isNetworkAvailable(mContext)) { - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - } else if (mInfo.numFailed < Constants.MAX_RETRIES) { - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - countRetry = true; - } else { - if (Constants.LOGV) { - Log.d(Constants.TAG, "IOException getting entity for " + mInfo.uri + - " : " + ex); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "IOException getting entity for download " + - mInfo.id + " : " + ex); - } - finalStatus = Downloads.STATUS_HTTP_DATA_ERROR; - } - request.abort(); - break http_request_loop; - } - for (;;) { - int bytesRead; - try { - bytesRead = entityStream.read(data); - } catch (IOException ex) { - ContentValues values = new ContentValues(); - values.put(Downloads.CURRENT_BYTES, bytesSoFar); - mContext.getContentResolver().update(contentUri, values, null, null); - if (!mInfo.noIntegrity && headerETag == null) { - if (Constants.LOGV) { - Log.v(Constants.TAG, "download IOException for " + mInfo.uri + - " : " + ex); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "download IOException for download " + - mInfo.id + " : " + ex); - } - if (Config.LOGD) { - Log.d(Constants.TAG, - "can't resume interrupted download with no ETag"); - } - finalStatus = Downloads.STATUS_PRECONDITION_FAILED; - } else if (!Helpers.isNetworkAvailable(mContext)) { - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - } else if (mInfo.numFailed < Constants.MAX_RETRIES) { - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - countRetry = true; - } else { - if (Constants.LOGV) { - Log.v(Constants.TAG, "download IOException for " + mInfo.uri + - " : " + ex); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "download IOException for download " + - mInfo.id + " : " + ex); - } - finalStatus = Downloads.STATUS_HTTP_DATA_ERROR; - } - request.abort(); - break http_request_loop; - } - if (bytesRead == -1) { // success - ContentValues values = new ContentValues(); - values.put(Downloads.CURRENT_BYTES, bytesSoFar); - if (headerContentLength == null) { - values.put(Downloads.TOTAL_BYTES, bytesSoFar); - } - mContext.getContentResolver().update(contentUri, values, null, null); - if ((headerContentLength != null) - && (bytesSoFar - != Integer.parseInt(headerContentLength))) { - if (!mInfo.noIntegrity && headerETag == null) { - if (Constants.LOGV) { - Log.d(Constants.TAG, "mismatched content length " + - mInfo.uri); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "mismatched content length for " + - mInfo.id); - } - finalStatus = Downloads.STATUS_LENGTH_REQUIRED; - } else if (!Helpers.isNetworkAvailable(mContext)) { - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - } else if (mInfo.numFailed < Constants.MAX_RETRIES) { - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - countRetry = true; - } else { - if (Constants.LOGV) { - Log.v(Constants.TAG, "closed socket for " + mInfo.uri); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "closed socket for download " + - mInfo.id); - } - finalStatus = Downloads.STATUS_HTTP_DATA_ERROR; - } - break http_request_loop; - } - break; - } - gotData = true; - for (;;) { - try { - if (stream == null) { - stream = new FileOutputStream(filename, true); - } - stream.write(data, 0, bytesRead); - if (mInfo.destination == Downloads.DESTINATION_EXTERNAL - && !DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING - .equalsIgnoreCase(mimeType)) { - try { - stream.close(); - stream = null; - } catch (IOException ex) { - if (Constants.LOGV) { - Log.v(Constants.TAG, - "exception when closing the file " + - "during download : " + ex); - } - // nothing can really be done if the file can't be closed - } - } - break; - } catch (IOException ex) { - if (!Helpers.discardPurgeableFiles( - mContext, Constants.BUFFER_SIZE)) { - finalStatus = Downloads.STATUS_FILE_ERROR; - break http_request_loop; - } - } - } - bytesSoFar += bytesRead; - long now = System.currentTimeMillis(); - if (bytesSoFar - bytesNotified > Constants.MIN_PROGRESS_STEP - && now - timeLastNotification - > Constants.MIN_PROGRESS_TIME) { - ContentValues values = new ContentValues(); - values.put(Downloads.CURRENT_BYTES, bytesSoFar); - mContext.getContentResolver().update( - contentUri, values, null, null); - bytesNotified = bytesSoFar; - timeLastNotification = now; - } - - if (Constants.LOGVV) { - Log.v(Constants.TAG, "downloaded " + bytesSoFar + " for " + mInfo.uri); - } - synchronized(mInfo) { - if (mInfo.control == Downloads.CONTROL_PAUSED) { - if (Constants.LOGV) { - Log.v(Constants.TAG, "paused " + mInfo.uri); - } - finalStatus = Downloads.STATUS_RUNNING_PAUSED; - request.abort(); - break http_request_loop; - } - } - if (mInfo.status == Downloads.STATUS_CANCELED) { - if (Constants.LOGV) { - Log.d(Constants.TAG, "canceled " + mInfo.uri); - } else if (Config.LOGD) { - // Log.d(Constants.TAG, "canceled id " + mInfo.id); - } - finalStatus = Downloads.STATUS_CANCELED; - break http_request_loop; - } - } - if (Constants.LOGV) { - Log.v(Constants.TAG, "download completed for " + mInfo.uri); - } - finalStatus = Downloads.STATUS_SUCCESS; - } - break; - } - } catch (FileNotFoundException ex) { - if (Config.LOGD) { - Log.d(Constants.TAG, "FileNotFoundException for " + filename + " : " + ex); - } - finalStatus = Downloads.STATUS_FILE_ERROR; - // falls through to the code that reports an error - } catch (Exception ex) { //sometimes the socket code throws unchecked exceptions - if (Constants.LOGV) { - Log.d(Constants.TAG, "Exception for " + mInfo.uri, ex); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "Exception for id " + mInfo.id, ex); - } - finalStatus = Downloads.STATUS_UNKNOWN_ERROR; - // falls through to the code that reports an error - } finally { - mInfo.hasActiveThread = false; - if (wakeLock != null) { - wakeLock.release(); - wakeLock = null; - } - if (client != null) { - client.close(); - client = null; - } - try { - // close the file - if (stream != null) { - stream.close(); - } - } catch (IOException ex) { - if (Constants.LOGV) { - Log.v(Constants.TAG, "exception when closing the file after download : " + ex); - } - // nothing can really be done if the file can't be closed - } - if (filename != null) { - // if the download wasn't successful, delete the file - if (Downloads.isStatusError(finalStatus)) { - new File(filename).delete(); - filename = null; - } else if (Downloads.isStatusSuccess(finalStatus) && - DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING - .equalsIgnoreCase(mimeType)) { - // transfer the file to the DRM content provider - File file = new File(filename); - Intent item = DrmStore.addDrmFile(mContext.getContentResolver(), file, null); - if (item == null) { - Log.w(Constants.TAG, "unable to add file " + filename + " to DrmProvider"); - finalStatus = Downloads.STATUS_UNKNOWN_ERROR; - } else { - filename = item.getDataString(); - mimeType = item.getType(); - } - - file.delete(); - } else if (Downloads.isStatusSuccess(finalStatus)) { - // make sure the file is readable - FileUtils.setPermissions(filename, 0644, -1, -1); - } - } - notifyDownloadCompleted(finalStatus, countRetry, retryAfter, redirectCount, - gotData, filename, newUri, mimeType); - } - } - - /** - * Stores information about the completed download, and notifies the initiating application. - */ - private void notifyDownloadCompleted( - int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData, - String filename, String uri, String mimeType) { - notifyThroughDatabase( - status, countRetry, retryAfter, redirectCount, gotData, filename, uri, mimeType); - if (Downloads.isStatusCompleted(status)) { - notifyThroughIntent(); - } - } - - private void notifyThroughDatabase( - int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData, - String filename, String uri, String mimeType) { - ContentValues values = new ContentValues(); - values.put(Downloads.STATUS, status); - values.put(Downloads._DATA, filename); - if (uri != null) { - values.put(Downloads.URI, uri); - } - values.put(Downloads.MIMETYPE, mimeType); - values.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis()); - values.put(Constants.RETRY_AFTER___REDIRECT_COUNT, retryAfter + (redirectCount << 28)); - if (!countRetry) { - values.put(Constants.FAILED_CONNECTIONS, 0); - } else if (gotData) { - values.put(Constants.FAILED_CONNECTIONS, 1); - } else { - values.put(Constants.FAILED_CONNECTIONS, mInfo.numFailed + 1); - } - - mContext.getContentResolver().update( - ContentUris.withAppendedId(Downloads.CONTENT_URI, mInfo.id), values, null, null); - } - - /** - * Notifies the initiating app if it requested it. That way, it can know that the - * download completed even if it's not actively watching the cursor. - */ - private void notifyThroughIntent() { - Uri uri = Uri.parse(Downloads.CONTENT_URI + "/" + mInfo.id); - mInfo.sendIntentIfRequested(uri, mContext); - } - -} diff --git a/src/com/android/providers/downloads/Helpers.java b/src/com/android/providers/downloads/Helpers.java deleted file mode 100644 index 7c6070f3..00000000 --- a/src/com/android/providers/downloads/Helpers.java +++ /dev/null @@ -1,793 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.providers.downloads; - -import android.content.ContentUris; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.database.Cursor; -import android.drm.mobile1.DrmRawContent; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.net.Uri; -import android.os.Environment; -import android.os.StatFs; -import android.os.SystemClock; -import android.provider.Downloads; -import android.telephony.TelephonyManager; -import android.util.Config; -import android.util.Log; -import android.webkit.MimeTypeMap; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.util.List; -import java.util.Random; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.Set; - -/** - * Some helper functions for the download manager - */ -public class Helpers { - - public static Random rnd = new Random(SystemClock.uptimeMillis()); - - /** Regex used to parse content-disposition headers */ - private static final Pattern CONTENT_DISPOSITION_PATTERN = - Pattern.compile("attachment;\\s*filename\\s*=\\s*\"([^\"]*)\""); - - private Helpers() { - } - - /* - * Parse the Content-Disposition HTTP Header. The format of the header - * is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html - * This header provides a filename for content that is going to be - * downloaded to the file system. We only support the attachment type. - */ - private static String parseContentDisposition(String contentDisposition) { - try { - Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition); - if (m.find()) { - return m.group(1); - } - } catch (IllegalStateException ex) { - // This function is defined as returning null when it can't parse the header - } - return null; - } - - /** - * Creates a filename (where the file should be saved) from a uri. - */ - public static DownloadFileInfo generateSaveFile( - Context context, - String url, - String hint, - String contentDisposition, - String contentLocation, - String mimeType, - int destination, - int contentLength) throws FileNotFoundException { - - /* - * Don't download files that we won't be able to handle - */ - if (destination == Downloads.DESTINATION_EXTERNAL - || destination == Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE) { - if (mimeType == null) { - if (Config.LOGD) { - Log.d(Constants.TAG, "external download with no mime type not allowed"); - } - return new DownloadFileInfo(null, null, Downloads.STATUS_NOT_ACCEPTABLE); - } - if (!DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(mimeType)) { - // Check to see if we are allowed to download this file. Only files - // that can be handled by the platform can be downloaded. - // special case DRM files, which we should always allow downloading. - Intent intent = new Intent(Intent.ACTION_VIEW); - - // We can provide data as either content: or file: URIs, - // so allow both. (I think it would be nice if we just did - // everything as content: URIs) - // Actually, right now the download manager's UId restrictions - // prevent use from using content: so it's got to be file: or - // nothing - - PackageManager pm = context.getPackageManager(); - intent.setDataAndType(Uri.fromParts("file", "", null), mimeType); - ResolveInfo ri = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); - //Log.i(Constants.TAG, "*** FILENAME QUERY " + intent + ": " + list); - - if (ri == null) { - if (Config.LOGD) { - Log.d(Constants.TAG, "no handler found for type " + mimeType); - } - return new DownloadFileInfo(null, null, Downloads.STATUS_NOT_ACCEPTABLE); - } - } - } - String filename = chooseFilename( - url, hint, contentDisposition, contentLocation, destination); - - // Split filename between base and extension - // Add an extension if filename does not have one - String extension = null; - int dotIndex = filename.indexOf('.'); - if (dotIndex < 0) { - extension = chooseExtensionFromMimeType(mimeType, true); - } else { - extension = chooseExtensionFromFilename( - mimeType, destination, filename, dotIndex); - filename = filename.substring(0, dotIndex); - } - - /* - * Locate the directory where the file will be saved - */ - - File base = null; - StatFs stat = null; - // DRM messages should be temporarily stored internally and then passed to - // the DRM content provider - if (destination == Downloads.DESTINATION_CACHE_PARTITION - || destination == Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE - || destination == Downloads.DESTINATION_CACHE_PARTITION_NOROAMING - || DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(mimeType)) { - base = Environment.getDownloadCacheDirectory(); - stat = new StatFs(base.getPath()); - - /* - * Check whether there's enough space on the target filesystem to save the file. - * Put a bit of margin (in case creating the file grows the system by a few blocks). - */ - int blockSize = stat.getBlockSize(); - for (;;) { - int availableBlocks = stat.getAvailableBlocks(); - if (blockSize * ((long) availableBlocks - 4) >= contentLength) { - break; - } - if (!discardPurgeableFiles(context, - contentLength - blockSize * ((long) availableBlocks - 4))) { - if (Config.LOGD) { - Log.d(Constants.TAG, - "download aborted - not enough free space in internal storage"); - } - return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); - } - stat.restat(base.getPath()); - } - - } else { - if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { - String root = Environment.getExternalStorageDirectory().getPath(); - base = new File(root + Constants.DEFAULT_DL_SUBDIR); - if (!base.isDirectory() && !base.mkdir()) { - if (Config.LOGD) { - Log.d(Constants.TAG, "download aborted - can't create base directory " - + base.getPath()); - } - return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); - } - stat = new StatFs(base.getPath()); - } else { - if (Config.LOGD) { - Log.d(Constants.TAG, "download aborted - no external storage"); - } - return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); - } - - /* - * Check whether there's enough space on the target filesystem to save the file. - * Put a bit of margin (in case creating the file grows the system by a few blocks). - */ - if (stat.getBlockSize() * ((long) stat.getAvailableBlocks() - 4) < contentLength) { - if (Config.LOGD) { - Log.d(Constants.TAG, "download aborted - not enough free space"); - } - return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); - } - - } - - boolean recoveryDir = Constants.RECOVERY_DIRECTORY.equalsIgnoreCase(filename + extension); - - filename = base.getPath() + File.separator + filename; - - /* - * Generate a unique filename, create the file, return it. - */ - if (Constants.LOGVV) { - Log.v(Constants.TAG, "target file: " + filename + extension); - } - - String fullFilename = chooseUniqueFilename( - destination, filename, extension, recoveryDir); - if (fullFilename != null) { - return new DownloadFileInfo(fullFilename, new FileOutputStream(fullFilename), 0); - } else { - return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); - } - } - - private static String chooseFilename(String url, String hint, String contentDisposition, - String contentLocation, int destination) { - String filename = null; - - // First, try to use the hint from the application, if there's one - if (filename == null && hint != null && !hint.endsWith("/")) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "getting filename from hint"); - } - int index = hint.lastIndexOf('/') + 1; - if (index > 0) { - filename = hint.substring(index); - } else { - filename = hint; - } - } - - // If we couldn't do anything with the hint, move toward the content disposition - if (filename == null && contentDisposition != null) { - filename = parseContentDisposition(contentDisposition); - if (filename != null) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "getting filename from content-disposition"); - } - int index = filename.lastIndexOf('/') + 1; - if (index > 0) { - filename = filename.substring(index); - } - } - } - - // If we still have nothing at this point, try the content location - if (filename == null && contentLocation != null) { - String decodedContentLocation = Uri.decode(contentLocation); - if (decodedContentLocation != null - && !decodedContentLocation.endsWith("/") - && decodedContentLocation.indexOf('?') < 0) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "getting filename from content-location"); - } - int index = decodedContentLocation.lastIndexOf('/') + 1; - if (index > 0) { - filename = decodedContentLocation.substring(index); - } else { - filename = decodedContentLocation; - } - } - } - - // If all the other http-related approaches failed, use the plain uri - if (filename == null) { - String decodedUrl = Uri.decode(url); - if (decodedUrl != null - && !decodedUrl.endsWith("/") && decodedUrl.indexOf('?') < 0) { - int index = decodedUrl.lastIndexOf('/') + 1; - if (index > 0) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "getting filename from uri"); - } - filename = decodedUrl.substring(index); - } - } - } - - // Finally, if couldn't get filename from URI, get a generic filename - if (filename == null) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "using default filename"); - } - filename = Constants.DEFAULT_DL_FILENAME; - } - - filename = filename.replaceAll("[^a-zA-Z0-9\\.\\-_]+", "_"); - - - return filename; - } - - private static String chooseExtensionFromMimeType(String mimeType, boolean useDefaults) { - String extension = null; - if (mimeType != null) { - extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); - if (extension != null) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "adding extension from type"); - } - extension = "." + extension; - } else { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "couldn't find extension for " + mimeType); - } - } - } - if (extension == null) { - if (mimeType != null && mimeType.toLowerCase().startsWith("text/")) { - if (mimeType.equalsIgnoreCase("text/html")) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "adding default html extension"); - } - extension = Constants.DEFAULT_DL_HTML_EXTENSION; - } else if (useDefaults) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "adding default text extension"); - } - extension = Constants.DEFAULT_DL_TEXT_EXTENSION; - } - } else if (useDefaults) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "adding default binary extension"); - } - extension = Constants.DEFAULT_DL_BINARY_EXTENSION; - } - } - return extension; - } - - private static String chooseExtensionFromFilename(String mimeType, int destination, - String filename, int dotIndex) { - String extension = null; - if (mimeType != null) { - // Compare the last segment of the extension against the mime type. - // If there's a mismatch, discard the entire extension. - int lastDotIndex = filename.lastIndexOf('.'); - String typeFromExt = MimeTypeMap.getSingleton().getMimeTypeFromExtension( - filename.substring(lastDotIndex + 1)); - if (typeFromExt == null || !typeFromExt.equalsIgnoreCase(mimeType)) { - extension = chooseExtensionFromMimeType(mimeType, false); - if (extension != null) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "substituting extension from type"); - } - } else { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "couldn't find extension for " + mimeType); - } - } - } - } - if (extension == null) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "keeping extension"); - } - extension = filename.substring(dotIndex); - } - return extension; - } - - private static String chooseUniqueFilename(int destination, String filename, - String extension, boolean recoveryDir) { - String fullFilename = filename + extension; - if (!new File(fullFilename).exists() - && (!recoveryDir || - (destination != Downloads.DESTINATION_CACHE_PARTITION && - destination != Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE && - destination != Downloads.DESTINATION_CACHE_PARTITION_NOROAMING))) { - return fullFilename; - } - filename = filename + Constants.FILENAME_SEQUENCE_SEPARATOR; - /* - * This number is used to generate partially randomized filenames to avoid - * collisions. - * It starts at 1. - * The next 9 iterations increment it by 1 at a time (up to 10). - * The next 9 iterations increment it by 1 to 10 (random) at a time. - * The next 9 iterations increment it by 1 to 100 (random) at a time. - * ... Up to the point where it increases by 100000000 at a time. - * (the maximum value that can be reached is 1000000000) - * As soon as a number is reached that generates a filename that doesn't exist, - * that filename is used. - * If the filename coming in is [base].[ext], the generated filenames are - * [base]-[sequence].[ext]. - */ - int sequence = 1; - for (int magnitude = 1; magnitude < 1000000000; magnitude *= 10) { - for (int iteration = 0; iteration < 9; ++iteration) { - fullFilename = filename + sequence + extension; - if (!new File(fullFilename).exists()) { - return fullFilename; - } - if (Constants.LOGVV) { - Log.v(Constants.TAG, "file with sequence number " + sequence + " exists"); - } - sequence += rnd.nextInt(magnitude) + 1; - } - } - return null; - } - - /** - * Deletes purgeable files from the cache partition. This also deletes - * the matching database entries. Files are deleted in LRU order until - * the total byte size is greater than targetBytes. - */ - public static final boolean discardPurgeableFiles(Context context, long targetBytes) { - Cursor cursor = context.getContentResolver().query( - Downloads.CONTENT_URI, - null, - "( " + - Downloads.STATUS + " = " + Downloads.STATUS_SUCCESS + " AND " + - Downloads.DESTINATION + " = " + Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE - + " )", - null, - Downloads.LAST_MODIFICATION); - if (cursor == null) { - return false; - } - long totalFreed = 0; - try { - cursor.moveToFirst(); - while (!cursor.isAfterLast() && totalFreed < targetBytes) { - File file = new File(cursor.getString(cursor.getColumnIndex(Downloads._DATA))); - if (Constants.LOGVV) { - Log.v(Constants.TAG, "purging " + file.getAbsolutePath() + " for " + - file.length() + " bytes"); - } - totalFreed += file.length(); - file.delete(); - long id = cursor.getLong(cursor.getColumnIndex(Downloads._ID)); - context.getContentResolver().delete( - ContentUris.withAppendedId(Downloads.CONTENT_URI, id), null, null); - cursor.moveToNext(); - } - } finally { - cursor.close(); - } - if (Constants.LOGV) { - if (totalFreed > 0) { - Log.v(Constants.TAG, "Purged files, freed " + totalFreed + " for " + - targetBytes + " requested"); - } - } - return totalFreed > 0; - } - - /** - * Returns whether the network is available - */ - public static boolean isNetworkAvailable(Context context) { - ConnectivityManager connectivity = - (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if (connectivity == null) { - Log.w(Constants.TAG, "couldn't get connectivity manager"); - } else { - NetworkInfo[] info = connectivity.getAllNetworkInfo(); - if (info != null) { - for (int i = 0; i < info.length; i++) { - if (info[i].getState() == NetworkInfo.State.CONNECTED) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "network is available"); - } - return true; - } - } - } - } - if (Constants.LOGVV) { - Log.v(Constants.TAG, "network is not available"); - } - return false; - } - - /** - * Returns whether the network is roaming - */ - public static boolean isNetworkRoaming(Context context) { - ConnectivityManager connectivity = - (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if (connectivity == null) { - Log.w(Constants.TAG, "couldn't get connectivity manager"); - } else { - NetworkInfo info = connectivity.getActiveNetworkInfo(); - if (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE) { - if (TelephonyManager.getDefault().isNetworkRoaming()) { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "network is roaming"); - } - return true; - } else { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "network is not roaming"); - } - } - } else { - if (Constants.LOGVV) { - Log.v(Constants.TAG, "not using mobile network"); - } - } - } - return false; - } - - /** - * Checks whether the filename looks legitimate - */ - public static boolean isFilenameValid(String filename) { - File dir = new File(filename).getParentFile(); - return dir.equals(Environment.getDownloadCacheDirectory()) - || dir.equals(new File(Environment.getExternalStorageDirectory() - + Constants.DEFAULT_DL_SUBDIR)); - } - - /** - * Checks whether this looks like a legitimate selection parameter - */ - public static void validateSelection(String selection, Set allowedColumns) { - try { - if (selection == null) { - return; - } - Lexer lexer = new Lexer(selection, allowedColumns); - parseExpression(lexer); - if (lexer.currentToken() != Lexer.TOKEN_END) { - throw new IllegalArgumentException("syntax error"); - } - } catch (RuntimeException ex) { - if (Constants.LOGV) { - Log.d(Constants.TAG, "invalid selection [" + selection + "] triggered " + ex); - } else if (Config.LOGD) { - Log.d(Constants.TAG, "invalid selection triggered " + ex); - } - throw ex; - } - - } - - // expression <- ( expression ) | statement [AND_OR ( expression ) | statement] * - // | statement [AND_OR expression]* - private static void parseExpression(Lexer lexer) { - for (;;) { - // ( expression ) - if (lexer.currentToken() == Lexer.TOKEN_OPEN_PAREN) { - lexer.advance(); - parseExpression(lexer); - if (lexer.currentToken() != Lexer.TOKEN_CLOSE_PAREN) { - throw new IllegalArgumentException("syntax error, unmatched parenthese"); - } - lexer.advance(); - } else { - // statement - parseStatement(lexer); - } - if (lexer.currentToken() != Lexer.TOKEN_AND_OR) { - break; - } - lexer.advance(); - } - } - - // statement <- COLUMN COMPARE VALUE - // | COLUMN IS NULL - private static void parseStatement(Lexer lexer) { - // both possibilities start with COLUMN - if (lexer.currentToken() != Lexer.TOKEN_COLUMN) { - throw new IllegalArgumentException("syntax error, expected column name"); - } - lexer.advance(); - - // statement <- COLUMN COMPARE VALUE - if (lexer.currentToken() == Lexer.TOKEN_COMPARE) { - lexer.advance(); - if (lexer.currentToken() != Lexer.TOKEN_VALUE) { - throw new IllegalArgumentException("syntax error, expected quoted string"); - } - lexer.advance(); - return; - } - - // statement <- COLUMN IS NULL - if (lexer.currentToken() == Lexer.TOKEN_IS) { - lexer.advance(); - if (lexer.currentToken() != Lexer.TOKEN_NULL) { - throw new IllegalArgumentException("syntax error, expected NULL"); - } - lexer.advance(); - return; - } - - // didn't get anything good after COLUMN - throw new IllegalArgumentException("syntax error after column name"); - } - - /** - * A simple lexer that recognizes the words of our restricted subset of SQL where clauses - */ - private static class Lexer { - public static final int TOKEN_START = 0; - public static final int TOKEN_OPEN_PAREN = 1; - public static final int TOKEN_CLOSE_PAREN = 2; - public static final int TOKEN_AND_OR = 3; - public static final int TOKEN_COLUMN = 4; - public static final int TOKEN_COMPARE = 5; - public static final int TOKEN_VALUE = 6; - public static final int TOKEN_IS = 7; - public static final int TOKEN_NULL = 8; - public static final int TOKEN_END = 9; - - private final String mSelection; - private final Set mAllowedColumns; - private int mOffset = 0; - private int mCurrentToken = TOKEN_START; - private final char[] mChars; - - public Lexer(String selection, Set allowedColumns) { - mSelection = selection; - mAllowedColumns = allowedColumns; - mChars = new char[mSelection.length()]; - mSelection.getChars(0, mChars.length, mChars, 0); - advance(); - } - - public int currentToken() { - return mCurrentToken; - } - - public void advance() { - char[] chars = mChars; - - // consume whitespace - while (mOffset < chars.length && chars[mOffset] == ' ') { - ++mOffset; - } - - // end of input - if (mOffset == chars.length) { - mCurrentToken = TOKEN_END; - return; - } - - // "(" - if (chars[mOffset] == '(') { - ++mOffset; - mCurrentToken = TOKEN_OPEN_PAREN; - return; - } - - // ")" - if (chars[mOffset] == ')') { - ++mOffset; - mCurrentToken = TOKEN_CLOSE_PAREN; - return; - } - - // "?" - if (chars[mOffset] == '?') { - ++mOffset; - mCurrentToken = TOKEN_VALUE; - return; - } - - // "=" and "==" - if (chars[mOffset] == '=') { - ++mOffset; - mCurrentToken = TOKEN_COMPARE; - if (mOffset < chars.length && chars[mOffset] == '=') { - ++mOffset; - } - return; - } - - // ">" and ">=" - if (chars[mOffset] == '>') { - ++mOffset; - mCurrentToken = TOKEN_COMPARE; - if (mOffset < chars.length && chars[mOffset] == '=') { - ++mOffset; - } - return; - } - - // "<", "<=" and "<>" - if (chars[mOffset] == '<') { - ++mOffset; - mCurrentToken = TOKEN_COMPARE; - if (mOffset < chars.length && (chars[mOffset] == '=' || chars[mOffset] == '>')) { - ++mOffset; - } - return; - } - - // "!=" - if (chars[mOffset] == '!') { - ++mOffset; - mCurrentToken = TOKEN_COMPARE; - if (mOffset < chars.length && chars[mOffset] == '=') { - ++mOffset; - return; - } - throw new IllegalArgumentException("Unexpected character after !"); - } - - // columns and keywords - // first look for anything that looks like an identifier or a keyword - // and then recognize the individual words. - // no attempt is made at discarding sequences of underscores with no alphanumeric - // characters, even though it's not clear that they'd be legal column names. - if (isIdentifierStart(chars[mOffset])) { - int startOffset = mOffset; - ++mOffset; - while (mOffset < chars.length && isIdentifierChar(chars[mOffset])) { - ++mOffset; - } - String word = mSelection.substring(startOffset, mOffset); - if (mOffset - startOffset <= 4) { - if (word.equals("IS")) { - mCurrentToken = TOKEN_IS; - return; - } - if (word.equals("OR") || word.equals("AND")) { - mCurrentToken = TOKEN_AND_OR; - return; - } - if (word.equals("NULL")) { - mCurrentToken = TOKEN_NULL; - return; - } - } - if (mAllowedColumns.contains(word)) { - mCurrentToken = TOKEN_COLUMN; - return; - } - throw new IllegalArgumentException("unrecognized column or keyword"); - } - - // quoted strings - if (chars[mOffset] == '\'') { - ++mOffset; - while(mOffset < chars.length) { - if (chars[mOffset] == '\'') { - if (mOffset + 1 < chars.length && chars[mOffset + 1] == '\'') { - ++mOffset; - } else { - break; - } - } - ++mOffset; - } - if (mOffset == chars.length) { - throw new IllegalArgumentException("unterminated string"); - } - ++mOffset; - mCurrentToken = TOKEN_VALUE; - return; - } - - // anything we don't recognize - throw new IllegalArgumentException("illegal character"); - } - - private static final boolean isIdentifierStart(char c) { - return c == '_' || - (c >= 'A' && c <= 'Z') || - (c >= 'a' && c <= 'z'); - } - - private static final boolean isIdentifierChar(char c) { - return c == '_' || - (c >= 'A' && c <= 'Z') || - (c >= 'a' && c <= 'z') || - (c >= '0' && c <= '9'); - } - } -} -- cgit v1.2.3 From 2dd83ce992eaaf3d44c32bc7468b47e3db014027 Mon Sep 17 00:00:00 2001 From: The Android Open Source Project Date: Tue, 3 Mar 2009 19:32:40 -0800 Subject: auto import from //depot/cupcake/@135843 --- Android.mk | 11 + AndroidManifest.xml | 52 + MODULE_LICENSE_APACHE2 | 0 NOTICE | 190 +++ docs/index.html | 1205 ++++++++++++++++++++ .../status_bar_ongoing_event_progress_bar.xml | 109 ++ res/values-cs/strings.xml | 31 + res/values-de/strings.xml | 31 + res/values-es/strings.xml | 31 + res/values-fr/strings.xml | 31 + res/values-it/strings.xml | 31 + res/values-ja/strings.xml | 31 + res/values-ko/strings.xml | 31 + res/values-nb/strings.xml | 32 + res/values-nl/strings.xml | 31 + res/values-pl/strings.xml | 31 + res/values-ru/strings.xml | 31 + res/values-zh-rCN/strings.xml | 31 + res/values-zh-rTW/strings.xml | 31 + res/values/strings.xml | 119 ++ src/com/android/providers/downloads/Constants.java | 151 +++ .../providers/downloads/DownloadFileInfo.java | 34 + .../android/providers/downloads/DownloadInfo.java | 212 ++++ .../providers/downloads/DownloadNotification.java | 300 +++++ .../providers/downloads/DownloadProvider.java | 731 ++++++++++++ .../providers/downloads/DownloadReceiver.java | 159 +++ .../providers/downloads/DownloadService.java | 879 ++++++++++++++ .../providers/downloads/DownloadThread.java | 710 ++++++++++++ src/com/android/providers/downloads/Helpers.java | 793 +++++++++++++ 29 files changed, 6059 insertions(+) create mode 100644 Android.mk create mode 100644 AndroidManifest.xml create mode 100644 MODULE_LICENSE_APACHE2 create mode 100644 NOTICE create mode 100644 docs/index.html create mode 100644 res/layout/status_bar_ongoing_event_progress_bar.xml create mode 100644 res/values-cs/strings.xml create mode 100644 res/values-de/strings.xml create mode 100644 res/values-es/strings.xml create mode 100644 res/values-fr/strings.xml create mode 100644 res/values-it/strings.xml create mode 100644 res/values-ja/strings.xml create mode 100644 res/values-ko/strings.xml create mode 100644 res/values-nb/strings.xml create mode 100644 res/values-nl/strings.xml create mode 100644 res/values-pl/strings.xml create mode 100644 res/values-ru/strings.xml create mode 100644 res/values-zh-rCN/strings.xml create mode 100644 res/values-zh-rTW/strings.xml create mode 100644 res/values/strings.xml create mode 100644 src/com/android/providers/downloads/Constants.java create mode 100644 src/com/android/providers/downloads/DownloadFileInfo.java create mode 100644 src/com/android/providers/downloads/DownloadInfo.java create mode 100644 src/com/android/providers/downloads/DownloadNotification.java create mode 100644 src/com/android/providers/downloads/DownloadProvider.java create mode 100644 src/com/android/providers/downloads/DownloadReceiver.java create mode 100644 src/com/android/providers/downloads/DownloadService.java create mode 100644 src/com/android/providers/downloads/DownloadThread.java create mode 100644 src/com/android/providers/downloads/Helpers.java diff --git a/Android.mk b/Android.mk new file mode 100644 index 00000000..82f0d585 --- /dev/null +++ b/Android.mk @@ -0,0 +1,11 @@ +LOCAL_PATH:= $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := user development + +LOCAL_SRC_FILES := $(call all-subdir-java-files) + +LOCAL_PACKAGE_NAME := DownloadProvider +LOCAL_CERTIFICATE := media + +include $(BUILD_PACKAGE) diff --git a/AndroidManifest.xml b/AndroidManifest.xml new file mode 100644 index 00000000..a7d424a9 --- /dev/null +++ b/AndroidManifest.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2 new file mode 100644 index 00000000..e69de29b diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..c5b1efa7 --- /dev/null +++ b/NOTICE @@ -0,0 +1,190 @@ + + Copyright (c) 2005-2008, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 00000000..a073a004 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,1205 @@ + + + + Download Provider + + + +
+

Download Provider

+

+

Contents

+

+

+

+

+


+

+

High-level requirements

+ +

+

Requirements for Android

+

+ + + + + + + + + + + + +
Req# Description Detailed Requirements Status
DLMGR_A_1 The Download Manager MUST satisfy the basic download needs of OTA Updates.   YES done in 1.0
DLMGR_A_2 The Download Manager MUST satisfy the basic download needs of Market.   YES done in 1.0
DLMGR_A_3 The Download Manager MUST satisfy the basic download needs of Gmail.   YES done in 1.0
DLMGR_A_4 The Download Manager MUST satisfy the basic download needs of the Browser.   YES done in 1.0
DLMGR_A_5 Downloads MUST happen and continue in the background, independently of the application in front.   YES done in 1.0
DLMGR_A_6 Downloads MUST be reliable even on unreliable network connections, within the capabilities of the underlying protocol and of the server.   YES done in 1.0
DLMGR_A_7 User-accessible files MUST be stored on the external storage card, and only files that are explicitly supported by an installed application must be downloaded.   YES done in 1.0
DLMGR_A_8 OMA downloads SHOULD be supported.   NO deferred beyond Cupcake (not enough time)
DLMGR_A_9 The Download Manager SHOULD only download when using high-speed (3G/wifi) links, or only when not roaming (if that can be detected).   NO deferred beyond Cupcake (not enough time)
DLMGR_A_10 Downloads SHOULD be user-controllable (if allowed by the initiating application), including pause, resume, and restart of failed downloads. 4001 NO deferred beyond Cupcake (not enough time, need precise specifications)
+

+

Requirements for Cupcake

+

+ + + + + + + + + + + +
Req# Description Detailed Requirements Status
DLMGR_C_1 The Download Manager SHOULD resume downloads where the socket got cleanly closed while the download was incomplete (common behavior on proxies and Google servers) 2005 YES done in Cupcake
DLMGR_C_2 The Download Manager SHOULD retry/resume downloads instead of aborting when the server returns a HTTP code 503 2006 YES done in Cupcake
DLMGR_C_3 The Download Manager SHOULD randomize the retry delay 2007 YES done in Cupcake
DLMGR_C_4 The Download Manager SHOULD use the retry-after header (delta-seconds) for 503 responses 2008 YES done in Cupcake
DLMGR_C_5 The Download Manager MAY hide columns that aren't strictly necessary 1010 YES done in Cupcake
DLMGR_C_6 The Download Manager SHOULD allow the initiating app to pause an ongoing download 1011 YES done in Cupcake
DLMGR_C_7 The Download Manager SHOULD not display multiple notification icons for completed downloads. 4002 NO deferred beyond Cupcake (no precise specifications, need framework support)
DLMGR_C_8 The Download Manager SHOULD delete old files from /cache 3006 NO deferred beyond Cupcake (no precise specifications)
DLMGR_C_9 The Download Manager SHOULD handle redirects 2009 YES done in Cupcake
+

+

Requirements for Donut

+

+ + +
Req# Description Detailed Requirements Status
+

+

Technology Evaluation

+ +

+ALSO See also future directions for possible additional technical changes. +

+

Possible scope for Cupcake

+

+Because there is no testing environment in place in the 1.0 code, and because the schedule between +1.0 and Cupcake doesn't leave enough time to develop a testing environment solid enough to be able +to test the database upgrades from 1.0 database scheme to a new scheme, any work done in Cupcake will +have to work within the existing 1.0 database scheme. +

+

Reducing the number of classes

+

+Each class in the system has a measurable RAM cost (because of the associated Class objects), +and therefore reducing the number of classes when possible or relevant can reduce the memory +requirements. That being said, classes that extend system classes and are necessary for the +operation of the download manager can't be removed. +

+ + + + + + + + + + + + + + + + + + +
Class Comments
com.android.providers.downloads.Constants Only contains constants, can be merged into another class.
com.android.providers.downloads.DownloadFileInfo Should be merged with DownloadInfo.
com.android.providers.downloads.DownloadInfo Once we only store information in RAM about downloads that are explicitly active, can be merged with DownloadThread.
com.android.providers.downloads.DownloadNotification Looks like it could be merged with DownloadProvider or DownloadService.
com.android.providers.downloads.DownloadNotification.NotificationItem Can probably be eliminated by using queries intelligently.
com.android.providers.downloads.DownloadProvider Extends ContentProvider, can't be eliminated.
com.android.providers.downloads.DownloadProvider.DatabaseHelper Can probably be eliminated by re-implementing by hand the logic of SQLiteOpenHelper.
com.android.providers.downloads.DownloadProvider.ReadOnlyCursorWrapper Can be eliminated once Cursor is read-only system-wide.
com.android.providers.downloads.DownloadReceiver Extends BroadcastReceiver, can't be eliminated.
com.android.providers.downloads.DownloadService Extends Service, unlikely that this can be eliminated. TBD.
com.android.providers.downloads.DownloadService.DownloadManagerContentObserver Extends ContentObserver, can be eliminated if the download manager can be re-architected to not depend on ContentObserver any more.
com.android.providers.downloads.DownloadService.MediaScannerConnection Can probably be merged into another class.
com.android.providers.downloads.DownloadService.UpdateThread Can probably be made to implement Runnable instead and merged into another class, can be eliminated if the download manager can be re-architected to not depend on ContentObserver any more.
com.android.providers.downloads.DownloadThread Can probably be made to implement Runnable instead. Unclear whether this can be eliminated as we will probably need one object that represents an ongoing download (unless the entire state can be stored on the stack with primitive types, which is unlikely).
com.android.providers.downloads.Helpers Can't be instantiated, can be merged into another class.
com.android.providers.downloads.Helpers.Lexer Keeps state about an ongoing lex, can probably be merged into another class by making the lexer synchronized, since the operation is short-lived.
+

+

Reducing the list of visible columns

+

+Security in the download provider is primarily enforced with two separate mechanisms: +

+

    +
  • Column restrictions, such that only a small number of the download provider's columns can be read or queried by applications. +
  • +
  • UID restrictions, such that only the application that initiated a download can access information about that download. +
  • +
+

+The first mechanism is expected to be fairly robust (the implementation is quite simple, based on projection maps, which are highly +structured), but the second one relies on arbitrary strings (URIs and SQL fragments) passed by applications and is therefore at a +higher risk of being compromised. Therefore, sensitive information stored in unrestricted columns (for which the first mechanism +doesn't apply) is at a greater risk than other information. +

+Here's the list of columns that can currently be read/queried, with comments: +

+ + + + + + + + + + + + + + +
Column Notes
_ID Needs to be visible so that the app can uniquely identify downloads. No security concern: those numbers are sequential and aren't hard to guess.
_DATA Probably should not be visible to applications. WARNING Security concern: This holds filenames, including those of private files. While file permissions are supposed to kick in and protect the files, hiding private filenames deeper in would probably be a reasonable idea.
MIMETYPE Needs to be visible so that app can display the icon matching the mime type. Intended to be visible by 3rd-party download UIs. TODO Security TBD before we implement support for 3rd-party UIs.
VISIBILITY Needs to be visible in case an app has both visible and invisible downloads. No obvious security concern.
STATUS Needs to be visible (1004). No obvious security concern.
LAST_MODIFICATION Needs to be visible, e.g. so that apps can sort downloads by date of last activity, or discard old downloads. No obvious security concern.
NOTIFICATION_PACKAGE Allows individual apps running under shared UIDs to identify their own downloads. No security concern: can be queried through package manager.
NOTIFICATION_CLASS See NOTIFICATION_PACKAGE.
TOTAL_BYTES Needs to be visible so that the app can display a progress bar. No obvious security concern. Intended to be visible by 3rd-party download UIs.
CURRENT_BYTES See TOTAL_BYTES.
TITLE Intended to be visible by 3rd-party download UIs. TODO Security and Privacy TBD before we implement support for 3rd-party UIs.
DESCRIPTION See TITLE.
+

+

Hiding the URI column

+

+The URI column is visible to the initiating application, which is a mild security risk. It should be hidden, but the OTA update mechanism relies on it to check duplicate downloads and to display the download that's currently ongoing in the settings app. If another string column was exposed to the initiating applications, the OTA update mechanism could use that one, and URI could then be hidden. For Cupcake, without changing the database schema, the ENTITY column could be re-used as it's currently unused. +

+

Handling redirects

+

+There are two important aspects to handle redirects: +

+

    +
  • Storing the intermediate URIs in the provider. +
  • +
  • Protecting against redirect loops. +
  • +
+

+If the URI column gets hidden, it could be used to store the intermediate URIs. After 1.0 the only available integer columns were METHOD and CONTROL. CONTROL was re-exposed to applications and can't be used. METHOD is slated to be re-used for 503 retry-after delays. It could be split into two halves, one for retry-after and one for the redirect count. It would make more sense to count the redirect loop with FAILED_CONNECTIONS, but since there's already quite some code using it it'd take a bit more effort. Ideally handling of redirects would be delayed until a future release, with a cleanup of the database schema (going along with the cleanup of the handling of filenames). +

+Because of the pattern used to read/write DownloadInfo and DownloadProvider, it's impractical to store multiple small integers into a large one. Therefore, since there are no integer columns left in the database, redirects will have to wait beyond Cupcake. +

+

ContentProvider for download UI

+

+In order to allow a UI that can "see" all the relevant downloads, there'll need to be a separate URI (or set of URIs) in the content provider: trying to use the exact same URIs for regular download control and for UI purposes (distinguishing them based on the permissions of the caller) will break down if a same app (or actually a same UID) tries to do both. It'll also break down if the system process tries to do regular download activities, since it has all permissions. +

+Beyond that, there's little technical challenge: there are already mechanisms in place to restrict the list of columns that can be inserted, queried and updated (inserting of course makes no sense through the UI channel), they just need to be duplicated for the case of the UI. The download provider also knows how to check the permissions of its caller, there isn't anything new here. +

+

Getting rid of OTHER_UID

+

+Right now OTHER_UID is used by checkin/update to allow the settings app to display the name of an ongoing OTA update, and by Market to allow the system to install the new apks. It is however a dangerous feature, at least because it touches a part of the code that is critical to the download manager security (separation of applications). +

+Getting rid of OTHER_UID would be beneficial for the download manager, but the existing functionality has to be worked around. At this point, the idea that I consider the most likely would be to have checkin and market implement =ContentProvider= wrappers around their downloads, and expose those content providers to whichever app they want, with whichever security mechanism they wish to have. +

+

Only using SDK APIs.

+

+It'd be good if the download manager could be built against the SDK as much as possible. +

+Here's the list of APIs as of Nov 5 2008 that aren't in the current public API but that are used by the download manager: +

+

+com.google.android.collect.Lists
+android.drm.mobile1.DrmRawContent
+android.media.IMediaScannerService
+android.net.http.AndroidHttpClient
+android.os.FileUtils
+android.provider.DrmStore
+
+

+ + +

+ +

+ + +

+ +

+

Schedule

+

+ +

+

    +
  • No future milestones currently defined +
  • +
+

+

Detailed Requirements

+ +

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Req# History Status Feature Description Notes
1xxx N/A   API    
1001 1.0 YES   Download Manager API The download manager provides an API that allows applications to initiate downloads.  
1002 1.0 YES   Cookies The download manager API allows applications to pass cookies to the download manager.  
1003 1.0 YES   Security The download manager provides a mechanism that prevents arbitrary applications from accessing meta-data about current and past downloads. In 1.0, known holes between apps
1004 1.0 YES   Status to Initiator The download manager allows the application initiating a download to query the status of that download.  
1005 1.0 YES   Cancel by Initiator The download manager allows the application initiating a download to cancel that download.  
1006 1.0 YES   Notify Initiator The download manager notifies the application initiating a download when the download completes (with success or failure)  
1007 1.0 YES   Fire and Forget The download manager does not rely on the initiating application when saving the file to a shared filesystem area  
1008 1.0 YES   Short User-Readable Description The download manager allows the initiating application to optionally provide a user-readable short description of the download  
1009 1.0 YES   Long User-Readable Description The download manager allows the initiating application to optionally provide a user-readable full description of the download  
1010 Cupcake YES Cupcake P3 YES Restrict column access The download provider doesn't allow access to columns that aren't strictly necessary.  
1011 Cupcake YES Cupcake P2 YES Pause downloads The download provider allows the application initiating a download to pause that download.  
2xxx N/A   HTTP    
2001 1.0 YES   HTTP Support The download manager supports all the features of HTTP 1.1 (RFC 2616) that are relevant to file downloads. Codes 3xx weren't considered relevant when those requirements were written
2002 1.0 YES   Resume Downloads The download manager resumes downloads that get interrupted.  
2003 1.0 YES   Flaky Downloads The download manager has mechanism that prevent excessive retries of downloads that consistently fail or get interrupted.  
2004 1.0 YES   Resume after Reboot The download manager resumes downloads across device reboots.  
2005 Cupcake YES Cupcake P2 YES Resume after socket closed The download manager resumes incomplete downloads after the socket gets cleanly closed This is necessary in order to reliably download through GFEs, though it pushes us further away from being able to download from servers that don't implement pipelining.
2006 Cupcake YES Cupcake P2 YES Resume after 503 The download manager resumes or retries downloads when the server returns an HTTP code 503  
2007 Cupcake YES Cupcake P2 YES Random retry delay The download manager uses partial randomness when retrying downloads on an exponential backoff pattern.  
2008 Cupcake YES Cupcake P2 YES Retry-after delta-seconds The download manager uses the retry-after header in a 503 response to decide when to retry the request Handling of absolute dates will be covered by a separate requirement.
2009 Cupcake YES Cupcake P2 YES Redirects The download manager handles common redirects.  
25xx N/A   HTTP/Conditions    
3xxx N/A   Storage    
3001 1.0 YES   File Storage The download manager stores the results of downloads in persistent storage.  
3002 1.0 YES   Max File Size The download manager is able to handle large files (order of magnitude: 50MB)  
3003 1.0 YES   Destination File Permissions The download manager restricts access to the internal storage to applications with the appropriate permissions  
3004 1.0 YES   Initiator File Access The download manager allows the initiating application to access the destination file  
3005 1.0 YES   File Types The download manager does not save files that can't be displayed by any currently installed application  
3006 Cupcake NO Cupcake P3 NO Old Files in /cache The download manager deletes old files in /cache  
35xx N/A   Storage/Filename    
4xxx N/A   UI    
4001 1.0 NO   Download Manager UI The download manager provides a UI that lets user get information about current downloads and control them. Didn't get spec on time to be able to even consider it.
4002 Cupcake NO Cupcake P2 NO Single Notification Icon The download manager displays a single icon in the notification bar regardless of the number of ongoing and completed downloads. No spec in Cupcake timeframe.
5xxx N/A   MIME    
52xx N/A   MIME/DRM    
5201 1.0 YES   DRM The download manager respects the DRM information it receives with the responses  
54xx N/A   MIME/OMA    
60xx N/A   Misc    
65xx N/A   Misc/Browser    
+

+

System Architecture

+ +

+

++----------------------+    +--------------------------------------+    +-------------+
+|                      |    |                                      |    |             |
+|   Download Manager   |    |  Browser / Gmail / Market / Updater  |    |  Viewer App |
+|                      |    |                                      |    |             |
++----------------------+    +--------------------------------------+    +-------------+
+    ^    |    ^                                             ^                ^
+    |    |    |                                             |                |
+    |    |    |                                             |                |
+    |    |    |      +---------------------------+          |                |
+    |    |    |      |                           |          |                |
+    |    |    |      |                           |          |                |
+    |    |    +-------- - - - - - - - - - - - - ------------+                |
+    |    |           |                           |                           |
+    |    |           |                           |                           |
+    |    +------------- - - - - - - - - - - - - -----------------------------+
+    |                |                           |
+    |                |                           |
+    +--------------->|     Android framework     |
+                     |                           |
+                     |                           |
+                     +---------------------------+
+
+

+

+          Application                        Download Manager                         Viewer App
+               |                                     |                                     |
+               |         initiate download           |                                     |
+               |------------------------------------>|                                     |
+               |<------------------------------------|                                     |
+               |        content provider URI         |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |           query download            |                                     |
+               |------------------------------------>|                                     |
+               |<------------------------------------|                                     |
+               |              Cursor                 |                                     |
+               |                                     |                                     |
+               |       register ContentObserver      |                                     |
+               |------------------------------------>|                                     |
+               |                                     |                                     |
+               |     ContentObserver notification    |                                     |
+               |<------------------------------------|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |    intent "notification clicked"    |                                     |
+               |<------------------------------------|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |      intent "download complete"     |                                     |
+               |<------------------------------------|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |            intent "view"            |
+               |                                     |------------------------------------>|
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |           update download           |                                     |
+               |------------------------------------>|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |         open downloaded file        |                                     |
+               |------------------------------------>|                                     |
+               |<------------------------------------|                                     |
+               |         ParcelFileDescriptor        |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |           delete download           |                                     |
+               |------------------------------------>|                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               |                                     |                                     |
+               v                                     v                                     v
+
+

+

Internal Product Dependencies

+

+

    +
  • [reverse dependency] GMail depends on the download manager to download attachments. +
  • +
  • [reverse dependency] OTA Update depends on the download manager to download system images. +
  • +
  • [reverse dependency] Vending Machine depends on the download manager to download content. +
  • +
  • [reverse dependency] Browser depends on the download manager to download non-browsable. +
  • +
  • Download Manager depends on a notification system to let the user know when downloads complete or otherwise require attention. +
  • +
  • Download Manager depends on a mechanism to share files with another app (letting apps access its files, or accessing apps' files). +
  • +
  • Download Manager depends on the ability to associate individual downloads with separate applications and to restrict apps to only access their own downloads. +
  • +
  • Download Manager depends on an HTTP stack that predictably processes all relevant kinds of HTTP requests and responses. +
  • +
  • Download Manager depends on a connectivity manager that reports accurate information about the status of the different data connections. +
  • +
+

+

Interface Documentation

+ +

+WARNING Since none of those APIs are public, they are all subject to change. If you're working in the Android source tree, do NOT use the explicit values, ONLY use the symbolic constants, unless you REALLY know what you're doing and are willing to deal with the consequences; you've been warned. +

+The various constants that are meant to be used by applications are all defined in the android.provider.Downloads class. Whenever possible, the constants should be used instead of the explicit values. +

+

Permissions

+

+ + + + + + +
Constant name Permission name Access restrictions Description
Downloads.PERMISSION_ACCESS "android.permission.ACCESS_DOWNLOAD_MANAGER" Signature or System Applications that want to access the Download Manager MUST have this permission.
Downloads.PERMISSION_ACCESS_ADVANCED "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED" Signature or System This permission protects some legacy APIs that new applications SHOULD NOT use.
Downloads.PERMISSION_CACHE "android.permission.ACCESS_CACHE_FILESYSTEM" Signature This permission allows an app to access the /cache filesystem, and is only needed by the Update code. Other applications SHOULD NOT use this permission
Downloads.PERMISSION_SEND_INTENTS "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS" Signature The download manager holds this permission, and the receivers through which applications get intents of completed downloads SHOULD require this permission from the sender
+

+

Content Provider

+

+The primary interface that applications use to communicate with the download manager is exposed as a ContentProvider. +

+

URIs

+

+The URIs for the Content Provider are: +

+ + + + +
Constant name URI Description
Downloads.CONTENT_URI Uri.parse("content://downloads/download") The URI of the whole Content Provider, used to insert new rows, or to query all rows.
N/A ContentUris.withAppendedId(CONTENT_URI, <id>) The URI of an individual download. <id> is the value of the Download._ID column
+

+

Columns

+

+The following columns are available: +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Constant name Column name SQL Type Access Description Notes
Downloads._ID "_id" Integer Read   Inherited from BaseColumns._ID.
Downloads.URI "uri" Text Init   Used to be readable.
Downloads.APP_DATA "entity" Text Init/Read/Modify   Actual column name will change in the future.
Downloads.NO_INTEGRITY "no_integrity" Boolean Init   Used to be readable.
Downloads.FILENAME_HINT "hint" Text Init   Used to be readable.
Downloads._DATA "_data" Text Read   Used to be Downloads.FILENAME and "filename".
Downloads.MIMETYPE "mimetype" Text Init/Read    
Downloads.DESTINATION "destination" Integer Init   See Destination codes for details of legal values. Used to be readable.
Downloads.VISIBILITY "visibility" Integer Init/Read/Modify   See Visibility codes for details of legal values.
Downloads.CONTROL "control" Integer Init/Read/Modify   See Control codes for details of legal values.
Downloads.STATUS "status" Integer Read   See Status codes for details of possible values.
Downloads.LAST_MODIFICATION "lastmod" Bigint Read    
Downloads.NOTIFICATION_PACKAGE "notificationpackage" Text Init/Read    
Downloads.NOTIFICATION_CLASS "notificationclass" Text Init/Read    
Downloads.NOTIFICATION_EXTRAS "notificationextras" Text Init    
Downloads.COOKIE_DATA "cookiedata" Text Init    
Downloads.USER_AGENT "useragent" Text Init    
Downloads.REFERER "referer" Text Init    
Downloads.TOTAL_BYTES "total_bytes" Integer Read   Might gain Init access in the future.
Downloads.CURRENT_BYTES "current_bytes" Integer Read    
Downloads.OTHER_UID "otheruid" Integer Init   Requires the android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED permission. Used to be readable and writable. Might disappear entirely if possible.
Downloads.TITLE "title" String Init/Read/Modify    
Downloads.DESCRIPTION "description" String Init/Read/Modify    
+

+

Destination Values

+

+ + + + + +
Constants name Constant value Description Notes
Downloads.DESTINATION_EXTERNAL 0 Saves the file to the SD card. Default value. Fails is SD card is not present.
Downloads.DESTINATION_CACHE_PARTITION 1 Saves the file to the internal cache partition. Requires the "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED" permission
Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE 2 Saves the file to the internal cache partition. The download can get deleted at any time by the download manager when it needs space.
+

+

Visibility Values

+

+ + + + + +
Constants name Constant value Description Notes
Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED 0 The download is visible in download UIs, and it shows up in the notification area during download and after completion. Default value for external downloads.
Downloads.VISIBILITY_VISIBLE 1 The download is visible in download UIs, and it shows up in the notification area during download but not after completion.  
Downloads.VISIBILITY_HIDDEN 2 The download is hidden from download UIs and doesn't show up in the notification area. Default value for internal downloads.
+

+

Control Values

+

+ + + + +
Constants name Constant value Description Notes
Downloads.CONTROL_RUN 0 The download is allowed to run. Default value.
Downloads.CONTROL_PAUSED 0 The download is paused.  
+

+

Status Values

+

+ + + + + + + + + + + + + + + + + + + + +
Constants name Constant value Description Notes
Downloads.STATUS_PENDING 190 Download hasn't started.  
Downloads.STATUS_PENDING_PAUSED 191 Download hasn't started and can't start immediately (network unavailable, paused by user). Not currently used.
Downloads.STATUS_RUNNING 192 Download has started and is running  
Downloads.STATUS_RUNNING_PAUSED 193 Download has started, but can't run at the moment (network unavailable, paused by user).  
Downloads.STATUS_SUCCESS 200 Download completed successfully.  
Downloads.STATUS_BAD_REQUEST 400 Couldn't initiate the request, or server response 400.  
Downloads.STATUS_NOT_ACCEPTABLE 406 No handler to view the file (external downloads), or server response 406. External downloads are meant to be user-visible, and are aborted if there's no application to handle the relevant MIME type.
Downloads.STATUS_LENGTH_REQUIRED 411 The download manager can't know the length of the download. Because of the unreliability of cell networks, the download manager only performs downloads when it can verify that it has received all the data for a download, except if the initiating app sets the Downloads.NO_INTEGRITY flag.
Downloads.STATUS_PRECONDITION_FAILED 412 The download manager can't resume an interrupted download, because it didn't receive enough information from the server to be able to resume.  
Downloads.STATUS_CANCELED 490 The download was canceled by a cause outside the Download Manager. Formerly known as Downloads.STATUS_CANCELLED. Might be impossible to observe in 1.0.
Downloads.STATUS_UNKNOWN_ERROR 491 The download was aborted because of an unknown error. Formerly known as Downloads.STATUS_ERROR. Typically the result of a runtime exception that is not explicitly handled.
Downloads.STATUS_FILE_ERROR 492 The download was aborted because the data couldn't be saved. Most commonly happens when the filesystem is full.
Downloads.STATUS_UNHANDLED_REDIRECT 493 The download was aborted because the server returned a redirect code 3xx that the download manager doesn't handle. The download manager currently handles 301, 302 and 307.
Downloads.STATUS_TOO_MANY_REDIRECTS 494 The download was aborted because the download manager received too many redirects while trying to find the actual file.  
Downloads.STATUS_UNHANDLED_HTTP_CODE 495 The download was aborted because the server returned a status code that the download manager doesn't handle. Standard codes 3xx, 4xx and 5xx don't trigger this.
Downloads.STATUS_HTTP_DATA_ERROR 496 The download was aborted because of an unrecoverable error trying to get data over the network. Typically this happens when the download manager received several I/O Exceptions in a row while the network is available and without being able to download any data.
  4xx standard HTTP/1.1 4xx codes returned by the server are used as-is. Don't rely on non-standard values being passed through, especially the higher values that would collide with download manager codes.
  5xx standard HTTP/1.1 5xx codes returned by the server are used as-is. Don't rely on non-standard values being passed through.
+

+

Status Helper Functions

+

+ + + + + + + + + +
Function signature Description
public static boolean Downloads.isStatusInformational(int status) Returns whether the status code matches a download that hasn't completed yet.
public static boolean Downloads.isStatusSuspended(int status) Returns whether the download hasn't completed yet but isn't currently making progress.
public static boolean Downloads.isStatusSuccess(int status) Returns whether the download successfully completed.
public static boolean Downloads.isStatusError(int status) Returns whether the download failed.
public static boolean Downloads.isStatusClientError(int status) Returns whether the download failed because of a client error.
public static boolean Downloads.isStatusServerError(int status) Returns whether the download failed because of a server error.
public static boolean Downloads.isStatusCompleted(int status) Returns whether the download completed (with no distinction between success and failure).
+

+

Intents

+

+The download manager sends an intent broadcast Downloads.DOWNLOAD_COMPLETED_ACTION when a download completes. +

+The download manager sends an intent broadcast Downloads.NOTIFICATION_CLICKED_ACTION when the user clicks a download notification that doesn't match a download that can be opened (e.g. because the notification is for several downloads at a time, or because it's for an incomplete download, or because it's for a private download). +

+The download manager starts an activity with Intent.ACTION_VIEW when the user clicks a download notification that matches a download that can be opened. +

+

Differences between 1.0 and Cupcake

+

+WARNING These are the differences for apps built from source in the Android source tree, i.e. they don't cover any of the cases of binary incompatibility. +

+

    +
  • Cursors returned by the content provider are now read-only. +
  • +
  • SQL "where" statements are now verified and must follow a rigid syntax (the most visible aspect being that all parameters much be single-quoted). +
  • +
  • Columns and constants that were unused or ineffective are gone: METHOD, NO_SYSTEM_FILES, DESTINATION_DATA_CACHE, OTA_UPDATE. +
  • +
  • OTHER_UID and DESTINATION_CACHE_PARTITION require android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED. +
  • +
  • The list of columns that can be queried and read is limited: _ID, APP_DATA, _DATA, MIMETYPE, CONTROL, STATUS, LAST_MODIFICATION, NOTIFICATION_PACKAGE, NOTIFICATION_CLASS, TOTAL_BYTES, CURRENT_BYTES, TITLE, DESCRIPTION. +
  • +
  • The list of columns that can be initialized by apps is limited: URI, APP_DATA, NO_INTEGRITY, FILENAME_HINT, MIMETYPE, DESTINATION, VISIBILITY, CONTROL, STATUS, LAST_MODIFICATION, NOTIFICATION_PACKAGE, NOTIFICATION_CLASS, NOTIFICATION_EXTRAS, COOKIE_DATA, USER_AGENT, REFERER, OTHER_UID, TITLE, DESCRIPTION. +
  • +
  • The list of columns that can be updated by apps is limited: APP_DATA, VISIBILITY, CONTROL, TITLE, DESCRIPTION. +
  • +
  • Downloads to the SD card default to have notifications that are visible after completion, internal downloads default to notifications that are always hidden. +
  • +
  • The constant FILENAME was renamed Downloads._DATA. +
  • +
  • Downloads can be paused and resumed by writing to the CONTROL column. Downloads.CONTROL_RUN (Default) makes the download go, Downloads.CONTROL_PAUSED pauses it. +
  • +
  • New column APP_DATA that is untouched by the download manager, used to store app-specific info about the downloads. +
  • +
  • Minor differences unlikely to affect applications: +
      +
    • The notification class/package must now match the UID. +
    • +
    • The backdoor to see the entire provider (which was intended to implement UIs) is gone. +
    • +
    • Private column names were removed from the public API. +
    • +
    +
  • +
+

+

Writing code that works on both the 1.0 and Cupcake versions of the download manager.

+

+If you're not 100% sure that you need to be reading this chapter, don't read it. +

+Basic rule: don't use features that only exist in one of the two implementations (POST, downloads to /data...). +

+Also, don't use columns in 1.0 that are protected or hidden in Cupcake. +

+Unfortunately, that's not always entirely possible. +

+Areas of concern: +

    +
  • Some columns were renamed. FILENAME became Downloads._DATA ("_data"), and ENTITY became APP_DATA ("entity"). +
      +
    • The difference can be used to distinguish between 1.0 and Cupcake, though reflection. +
    • +
    • The difference prevents from using any of the symbolic constants directly in source code: if the same binary wants to run on both 1.0 and Cupcake, it will have to hard-code the values of those constants or use reflection to get to them. +
    • +
    +
  • +
  • URI column accessible in 1.0 but protected in Cupcake. Code that relies on being able to re-read its URI should be using APP_DATA in Cupcake, but that column doesn't exist as such in 1.0. +
      +
    • If the code detects that it's running on Cupcake, write URI to APP_DATA in addition to URI, and query and read from the appropriate column. +
    • +
    • Since the underlying column for APP_DATA exists in both 1.0 and Cupcake even though it has different names, it can actually be used in both cases (see note above about renamed columns). +
    • +
    +
  • +
  • Some of the error codes have been renumbered. STATUS_UNHANDLED_HTTP_CODE and STATUS_HTTP_DATA_ERROR were bumped up from 494 and 495 to 495 and 496. +
  • +
  • Backward compatibility is not guaranteed: the download manager APIs weren't meant to be backward compatible yet. As such it's impossible to guarantee that code that uses the Cupcake download manager will be binary-compatible with future versions. +
      +
    • I intend to eventually change the column name for APP_DATA to "app_data". Because of that, code should use reflection to get to that name instead of hard-coding "entity", so that it always gets the right value for the string. +
    • +
    • I intend to refine the handling of filenames and content URIs, exposing separate columns for situations where a download can be accessed both as a file and through a content URI (e.g. stuff that is recognized by the media scanner). Unfortunately at this point this feature isn't clear in my mind. I'd recommend using reflection to look for the Downloads._DATA column, and if it isn't there to look for the FILENAME column (which has the advantage of also dealing with the difference between 1.0 and Cupcake). +
    • +
    • I intend to renumber the error codes, especially those in the 4xx range, and especially those below 490 (which overlap with standard HTTP error codes but will probably be separated). Reflection would improve the probability to getting to them in the future. Unfortunately, the names of the constants are likely to change in the process, in order to disambiguate codes coming from HTTP from those generated locally. I might try to stick to the following pattern: where a constant is currently named STATUS_XXX, its locally-generated version in the future might be named STATUS_LOCAL_XXX while the current constant name might disappear. Using reflection to try to get to the possible new name instead of using the old name might improve the probability of compatibility in the future. That being said, it is critically important to properly handle the full ranges or error codes, especially the 4xx range, as "expected" errors, and it is far preferable to not try to distinguish between those codes at all: use the functions Downloads.isError and Downloads.isClientError to easily recognize those entire ranges. In order of probability, the 1xx range is the second most likely to be affected. +
    • +
    +
  • +
+

+

Functional Specification

+All the details about what the product does. +

+TODO +

+

Release notes for Cupcake

+

+

    +
  • HTTP codes 301, 302, 303 and 307 (redirects) are now supported +
  • +
  • HTTP code 503 is now handled, with support for retry-after in delay-seconds +
  • +
  • Downloads that were cleanly interrupted are now resumed instead of failing +
  • +
  • Applications can now pause their downloads +
  • +
  • Retry delays are now randomized +
  • +
  • Connectivity is now checked on all interfaces +
  • +
  • Downloads with invalid characters in file name can now be saved +
  • +
  • Various security fixes +
  • +
  • Minor API changes (see API differences between 1.0 and Cupcake) +
  • +
+

+

Product Architecture

+How the tasks are split between the different modules that implement the product/feature. +

+TODO To be completed +

+ + + + + + + + + + + + + + + + + + +
Class
com.android.providers.downloads.Constants
com.android.providers.downloads.DownloadFileInfo
com.android.providers.downloads.DownloadInfo
com.android.providers.downloads.DownloadNotification
com.android.providers.downloads.DownloadNotification.NotificationItem
com.android.providers.downloads.DownloadProvider extends ContentProvider
com.android.providers.downloads.DownloadProvider.DatabaseHelper extends SQLiteOpenHelper
com.android.providers.downloads.DownloadProvider.ReadOnlyCursorWrapper extends CursorWrapper implements CrossProcessCursor
com.android.providers.downloads.DownloadReceiver extends BroadcastReceiver
com.android.providers.downloads.DownloadService extends Service
com.android.providers.downloads.DownloadService.DownloadManagerContentObserver extends ContentObserver
com.android.providers.downloads.DownloadService.MediaScannerConnection implements ServiceConnection
com.android.providers.downloads.DownloadService.UpdateThread extends Thread
com.android.providers.downloads.DownloadThread extends Thread
com.android.providers.downloads.Helpers
com.android.providers.downloads.Helpers.Lexer
+

+The download manager is built primarily around a ContentProvider and a Service. The ContentProvider part is the front end, i.e. applications communicate with the download manager through the provider. The Service part is the back end, which contains the actual download logic, running as a background process. +

+As a first approach, the provider is essentially a canonical provider backed by a SQLite3 database. The biggest difference between the download provider and a "plain" provider is that the download provider aggressively validates its inputs, for security reasons. +

+The service is a background process that performs the actual downloads as requested by the applications. The service doesn't offer any bindable interface, the service object exists strictly so that the system knows how to prioritize the download manager's process against other processes when memory is tight. +

+Communication between the provider and the service is done through public Android APIs, so that the two components are deeply decoupled (they could in fact run in different processes). The download manager starts the service whenever a change is made that can start or restart a download. The service observes and queries the provider for changes, and updates the provider as the download progresses. +

+

+There are a few secondary classes that provide auxiliary functions. +

+A Receiver listens to several broadcasts. Is receives some system broadcasts when the system boots (so that the download manager can resume downloads that were interrupted when the system was turned off) or when the connectivity changes (so that the download manager can restart downloads that were interrupted when connectivity was lost). It also receives intents when the user selects a download notification. +

+

+Finally, some helper classes provide support functions. +

+Most significantly, DownloadThread is responsible for performing the actual downloads as part of the DownloadService's functionality, while UpdateThread is responsible for updating the DownloadInfo whenever the DownloadProvider data changes. +

+DownloadInfo and DownloadFileInfo hold pure data structures, with little or no actual logic. +

+Lexer takes care of validating the snippets of SQL data that are received from applications, to avoid cases of SQL injection. +

+

+

+

+

+

+The service keeps a copy of the provider data in RAM, so that it can determine what changed in the provider when it receives a change notification through the ContentObserver. That data is kept in an array of DownloadInfo structures. +

+Each DownloadThread performs the operations for a single download (or, more precisely, for a single HTTP transaction). Each DownloadThread is backed by a DownloadInfo object. which is in fact on of the objects kept by the DownloadService. While a download is running, the DownloadService can influence the download by writing data into the relevant DownloadInfo object, and the DownloadThread checks that object at appropriate times during the download. +

+Because the DownloadService updates the DownloadInfo objects asynchronously from everything else (it uses a dedicated thread for that purpose), a lot of care has to be taken when upgrading the DownloadInfo object. In fact, only the DownloadService's updateThread function can update that object, and it should be considered read-only to every other bit of code. Even within the updateThread function, some care must be taken to ensure that the DownloadInfos don't get out of sync with the provider. +

+On the other hand, the DownloadService's updateThread function does upgrade the DownloadInfo when it spawns new DownloadThreads (and in a few more circumstances), and when it does that it must also update the DownloadProvider (or risk seeing its DownloadInfo data get overwritten). +

+Because of all that, all code outside of the DowloadService's updateThread must neither read from DownloadProvider nor write to the DownloadInfo objects under any circumstances. The DownloadService's updateFunction is responsible for copying data from the DownloadProvider to the DownloadInfo objects, and must ensure that the DownloadProvider remains in sync with the information it writes into the DownloadInfo objects. +

+

+

+

Implementation Documentation

+How individual modules are implemented. +

+TODO To be completed +

+

Database formats

+

+Android 1.0, format version 31, table downloads: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Column Type
"_id" INTEGER PRIMARY KEY AUTOINCREMENT
"uri" TEXT
"method" INTEGER
"entity" TEXT
"no_integrity" BOOLEAN
"hint" TEXT
"otaupdate" BOOLEAN
"_data" TEXT
"mimetype" TEXT
"destination" INTEGER
"no_system" BOOLEAN
"visibility" INTEGER
"control" INTEGER
"status" INTEGER
"numfailed" INTEGER
"lastmod" BIGINT
"notificationpackage" TEXT
"notificationclass" TEXT
"notificationextras" TEXT
"cookiedata" TEXT
"useragent" TEXT
"referer" TEXT
"total_bytes" INTEGER
"current_bytes" INTEGER
"etag" TEXT
"uid" INTEGER
"otheruid" INTEGER
"title" TEXT
"description" TEXT
"scanned" BOOLEAN
+

+Cupcake, format version 100: Same as format version 31. +

+

Future Directions

+ +

+WARNING This section is for informative purposes only. +

+

API

+

+

    +
  • Expose Download Manager to 3rd party apps - security, robustness . +
  • +
  • Validate application-provided user agent, cookies, etc... to protect against e.g. header injection. +
  • +
  • Allow trust-and-verify MIME type. +
  • +
  • Extract response string from HTTP responses, extract entity from failed responses +
  • +
  • If app fails to be notified, retry later - don't give up because of a single failure. +
  • +
  • Support data: URIs . +
  • +
  • Download files to app-provided content provider . +
  • +
  • Don't pass HTTP codes above about 490 to the initiating app (figure out what the threshold should be). +
  • +
  • Allow initiating app to specify that it wants wifi-only downloads . +
  • +
  • Provide SQL "where" clauses for the different categories of status codes, matching isStatusXXX(). +
  • +
  • There has to be a mechanism by which old downloads are automatically purged from /cache if there's not enough space . +
  • +
  • Clicking the notification for a completed download should go through the initiating app instead of directly opening the file (but what about fire and forget?). +
  • +
  • Clean up the difference between pending_network (waiting for network) and running_paused (user paused the download). +
  • +
  • Allow any app to access the downloaded file (but no other column) of user-downloaded files . +
  • +
  • Provider should return more errors and throw fewer exceptions if possible. +
  • +
  • Add option to auto-dismiss notifications for completed downloads after a given time . +
  • +
  • Delete filename in case of failure - better handle the separation between filename and content URI. +
  • +
  • Allow the initiating application to specify that it wants to restart downloads from scratch if they're interrupted and can't be resumed . +
  • +
  • Save images directly from browser without re-downloading data . +
  • +
  • Give applications the ability to explicitly specify the full target filename (not just a hint). +
  • +
  • Give applications the ability to download multiple files into multiple set locations as if they were a single "package". +
  • +
  • Give applications the ability to download files only if they haven't been already downloaded. +
  • +
  • Give applications the ability to download files that have already been downloaded only if there's a newer version. +
  • +
  • Set-cookie in the response. +
  • +
  • basic auth . +
  • +
  • app-provided prompts for basic auth, ssl, redirects. +
  • +
  • File should be hidden from initiating application when DRM. +
  • +
  • Delay writing of app-visible filename column until file visible (split user-visible vs private files?). +
  • +
  • Separate locally-generated status codes from standard HTTP codes. +
  • +
  • Allow app to specify it doesn't want to resume downloads across reboots (because they might require additional work). +
  • +
  • Allow app to prioritize user-initiated downloads. +
  • +
  • Allow app to specify length of download (full trust, or trust-and-verify). +
  • +
  • Support POST. +
  • +
  • Support PUT. +
  • +
  • Support plugins for additional protocols and download descriptors. +
  • +
  • Rename columns to have an appropriate COLUMN_ prefix. +
  • +
+

+

HTTP Handling

+

+

    +
  • Fail download immediately on authoritative unresolved hostnames . +
  • +
  • The download manager should use the browser's user-agent by default. +
  • +
  • Redirect with HTTP Refresh headers (download current and target content with non-zero refresh). +
  • +
  • Handle content-encoding header. +
  • +
  • Handle transfer-encoding header. +
  • +
  • Find other ways to validate interrupted downloads (signature, last-mod/if-modified-since) . +
  • +
  • Make downloads time out in case of long time with no activity. +
  • +
+

+

File names

+

+

    +
  • Protect against situations where there's already a "downloads" directory on SD card. +
  • +
  • Deal with filenames with invalid characters. +
  • +
  • Refine the logic that builds filenames to better match desktop browsers - drop the query string. +
  • +
  • URI-decode filenames generated from URIs. +
  • +
  • Better deal with filenames that end in '.'. +
  • +
  • Deal with URIs that end in '/' or '?'. +
  • +
  • Investigate how to better deal with filenames that have multiple extensions. +
  • +
+

+

UI

+

+

    +
  • Prompt for redirects across domains or cancel. +
  • +
  • Prompt for redirects from SSL or cancel. +
  • +
  • Prompt for basic auth or cancel. +
  • +
  • Prompt for SSL with untrusted/invalid/expired certificates or cancel. +
  • +
  • Reduce number of icons in the title bar, possibly as low as 1 (animated if there are ongoing downloads, fixed if all downloads have completed) . +
  • +
  • UI to cancel visible downloads. +
  • +
  • UI to pause visible downloads. +
  • +
  • Reorder downloads. +
  • +
  • View SSL certificates. +
  • +
  • Indicate secure downloads. +
  • +
+

+

Handling of specific MIME types

+

+

    +
  • Parse HTML for redirects with meta tag. +
  • +
  • Handle charsets and transcoding of text files. +
  • +
  • Deal with multiparts. +
  • +
  • Support OMA downloads with DD and data in same multipart, i.e. combined delivery. +
  • +
  • Assume application/octet-stream for http responses with no mime type. +
  • +
  • Download anything if an app supports application/octet-stream. +
  • +
  • Download any text/* if an application supports text/plain. +
  • +
  • Should the media scanner be invoked on DRM downloads? +
  • +
  • Refresh header with timer should be followed if content is not downloadable. +
  • +
  • Support OMA downloads. +
  • +
  • Support MIDP-OTA downloads. +
  • +
  • Support Sprint MCD downloads. +
  • +
  • Sniff content when receiving MIME-types known to be inaccurately sent by misconfigured servers. +
  • +
+

+

Management of downloads based on environment

+

+

    +
  • If the device routinely connects over wifi, delay non-interactive downloads by a certain amount of time in case wifi becomes available +
  • +
  • Turn on wifi if possible +
  • +
  • Fall back to cell when wifi is available but download doesn't proceed +
  • +
  • Be smarter about spurious losses (i.e. exceptions while network appears up) when the active network changes (e.g. turn on wifi while downloading over cell). +
  • +
  • Investigate the use of wifi locks, especially when performing non-resumable downloads. +
  • +
  • Poll network state (and maybe even try to connect) even without notifications from the connectivity manager (in case the notifications go AWOL or get inconsistent) . +
  • +
  • Pause when conditions degrade . +
  • +
  • Pause when roaming. +
  • +
  • Throttle or pause when user is active. +
  • +
  • Pause on slow networks (2G). +
  • +
  • Pause when battery is low. +
  • +
  • Throttle to not overwhelm the link. +
  • +
  • Pause when sync is active. +
  • +
  • Deal with situations where the active connection is down but there's another connection available +
  • +
  • Download files at night when the user is not explicitly waiting. +
  • +
+

+

Management of simultaneous downloads

+

+

    +
  • Pipeline requests on limited number of sockets, run downloads sequentially . +
  • +
  • Manage bandwidth to not starve foreground tasks. +
  • +
  • Run unsized downloads on their own (on a per-filesystem basis) to avoid failing multiple of them because of a full filesystem . +
  • +
+

+

Minor functional changes, edge cases

+

+

    +
  • The database could be somewhat checked when it's opened. +
  • +
  • [DownloadProvider.java] When upgrading the database, the numbering of ids should restart where it left off. +
  • +
  • [DownloadProvider.java] Handle errors when failing to start the service. +
  • +
  • [DownloadProvider.java] Explicitly populate all database columns that have documented default values, investigate whether that can be done at the SQL level. +
  • +
  • [DownloadProvider.java] It's possible that the last update time should be updated by the Sevice logic, not by the content provider. +
  • +
  • When relevant, combine logged messages on fewer lines. +
  • +
  • [DownloadService.java] Trim the database in the provider, not in the service. Notify application when trimming. Investigate why the row count seems off by one. Enforce on an ongoing basis. +
  • +
  • [DownloadThread.java] When download is restarted and MIME type wasn't provided by app, don't re-use MIME type. +
  • +
  • [DownloadThread.java] Deal with mistmatched file data sizes (between database and filesystem) when resuming a download, or with missing files that should be here. +
  • +
  • [DownloadThread.java] Validate that the response content-length can be properly parsed (i.e. presence of a string doesn't guarantee correctness). +
  • +
  • [DownloadThread.java] Be finer-grained with the way file permissions are managed in /cache - don't 0644 everything . +
  • +
  • Truncate files before deleting them, in case they're still open cross-process. +
  • +
  • Restart from scratch downloads that had very little progress . +
  • +
  • Deal with situations where /data is full as it prevents the database from growing (DoS) . +
  • +
  • Wait until file scanned to notify that download is completed. +
  • +
  • Missing some detailed logging about IOExceptions. +
  • +
  • Allow to disable LOGD debugging independently from system setting. +
  • +
  • Pulling the battery during a download corrupts files (lots of zeros written) . +
  • +
  • Should keep a bit of "emergency" database storage to initiate the download of an OTA update, in a file that is pre-allocated whenever possible (how to know it's an OTA update?). +
  • +
  • Figure out how to hook up into dumpsys and event log. +
  • +
  • Use the event log to log download progress. +
  • +
  • Use /cache to stage downloads that eventually go to the sd card, to avoid having sd files open too long in case the use pulls the card and to avoid partial files for too long. +
  • +
  • Maintain per-application usage statistics. +
  • +
  • There might be corner cases where the notifications are slightly off because different notifications might be using PendingIntents that can't be distinguished (differing only by their extras). +
  • +
+

+

Architecture and Implementation

+

+

    +
  • The content:// Uri of individual downloads could be cached instead of being re-built whenever it's needed. +
  • +
  • [DownloadProvider.java] Solidify extraction of id from URI +
  • +
  • [DownloadProvider.java] Use ContentURIs.parseId(uri) to extra the id from various functions. +
  • +
  • [DownloadProvider.java] Use StringBuilder to build the various queries. +
  • +
  • [DownloadService.java] Cache interface to the media scanner service more aggressively. +
  • +
  • [DownloadService.java] Investigate why unbinding from the media scanner service sometimes throws an exception +
  • +
  • [DownloadService.java] Handle exceptions in the service's UpdateThread - mark that there's no thread left. +
  • +
  • [DownloadService.java] At the end of UpdateThread, closing the cursor should be done even if there's an exception. Also log the exception, as we'd be in an inconsistent state. +
  • +
  • [DownloadProvider.java] Investigate whether the download provider should aggressively cache the result of getContext() and getContext().getContentResolver() +
  • +
  • Document the database columns that are most likely to stay unchanged throughout versions, to increase the chance being able to perform downgrades. +
  • +
  • [DownloadService.java] Sanity-check the ordering of the local cache when adding/removing rows. +
  • +
  • [DownloadService.java] Factor the code that checks for DRM types into a separate function. +
  • +
  • [DownloadService.java] Factor the code that notifies applications into a separate function (codepath with early 406 failure) +
  • +
  • [DownloadService.java] Check for errors when spawning download threads. +
  • +
  • [DownloadService.java] Potential race condition when a download completes at the same time as it gets deleted through the content provider - see deleteDownload(). +
  • +
  • [DownloadService.java] Catch all exceptions in scanFile - don't trust a remote process to the point where we'd let it crash us. +
  • +
  • [DownloadService.java] Limit number of attempts to scan a file. +
  • +
  • [DownloadService.java] Keep less data in RAM, especially about completed downloads. Investigating cutting unused columns if necessary +
  • +
  • [DownloadThread.java] Don't let exceptions out of run() - that'd kill the service, which'd accomplish no good. +
  • +
  • [DownloadThread.java] Keep track of content-length responses in a long, not in a string that we keep parsing . +
  • +
  • [DownloadThread.java] Use variable-size buffer to avoid thousands of operations on large downloads +
  • +
  • [Helpers.java] Deal with atomicity of checking/creating file. +
  • +
  • [Helpers.java] Handle differences between content-location separators and filesystem separators. +
  • +
  • Optimize database queries: use projections to reduce number of columns and get constant column numbers. +
  • +
  • Index last-mod date in DB, because of ordered searches. Investigate whether other columns need to be indexed (Hidden?) +
  • +
  • Deal with the fact that sqlite INTEGER matches java long (63-bit) . +
  • +
  • Use a single HTTP client for the entire download manager. +
  • +
  • Could use fewer alarms - currently setting new alarm each time database updated . +
  • +
  • Obsolete columns should be removed from the database . +
  • +
  • Assign relevant names to threads. +
  • +
  • Investigate and handle the different subclasses of IOException appropriately . +
  • +
  • There's potentially a race condition around read-modify-write cycles in the database, between the Service's updateFromProvider thread and the worker threads (and possibly more). Those should be synchronized appropriately, and the provider should be hardened to prevent asynchronous changes to sensitive data (or to synchronize when there's no other way, though I'd rather avoid that) . +
  • +
  • Temporary file leaks when downloads are deleted while the service isn't running . +
  • +
  • Increase priority of updaterThread while in the critical section (to avoid issues of priority inheritance with the main thread). +
  • +
  • Explicitly specify which interface to use for a given download (to get better sync with the connection manager). +
  • +
  • Cancel the requests on more kinds of errors instead of trusting the garbage collector. +
  • +
  • Issues with the fact that parseInt can throw exceptions on invalid server headers. +
  • +
+

+

Code style, refactoring

+

+

    +
  • Fix lint warnings +
  • +
  • Make sure that comments fit in 80 columns to match style guide +
  • +
  • Unify code style when dealing with lines longer than 100 characters +
  • +
  • [Constants.java] constants should be organized by logical groups to improve readability. +
  • +
  • Use fewer internal classes (Helpers, Constants...) . +
  • +
+

+

Browser changes

+

+

    +
  • Move download UI outside of browser, so that browser doesn't need to access the provider. +
  • +
  • Make browser sniff zips and jars to see if they're apks. +
  • +
  • Live handoff of browser-initiated downloads (download in browser, browser update download UI, hand over to download manager on retry). +
  • +
+ + diff --git a/res/layout/status_bar_ongoing_event_progress_bar.xml b/res/layout/status_bar_ongoing_event_progress_bar.xml new file mode 100644 index 00000000..d81c42ba --- /dev/null +++ b/res/layout/status_bar_ongoing_event_progress_bar.xml @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/values-cs/strings.xml b/res/values-cs/strings.xml new file mode 100644 index 00000000..96cd35c4 --- /dev/null +++ b/res/values-cs/strings.xml @@ -0,0 +1,31 @@ + + + + "Získat přístup ke správci stahování." + "Umožní aplikaci získat přístup ke správci stahování a stahovat pomocí něj soubory. Škodlivé aplikace mohou pomocí tohoto nastavení narušit stahování a získat přístup k soukromým informacím." + "Pokročilé funkce správce stahování." + "Umožňuje aplikaci přístup k pokročilým funkcím správce stahování."\n" Škodlivé aplikace toho mohou využít a narušit stahování nebo získat přístup k "\n" důvěrným informacím." + "Použít mezipaměť systému." + "Umožní aplikaci získat přímý přístup k mezipaměti systému, měnit ji a mazat. Škodlivé aplikace mohou pomocí tohoto nastavení vážně narušit stahování a ostatní aplikace a získat přístup k soukromým datům." + "Odeslat oznámení o stahování." + "Umožní aplikaci odeslat oznámení o dokončení stahování. Škodlivé aplikace mohou pomocí tohoto nastavení zmást jiné aplikace, které stahují soubory." + "<Bez názvu>" + ", " + " a ještě %d" + "Stahování bylo dokončeno" + "Stahování bylo neúspěšné" + diff --git a/res/values-de/strings.xml b/res/values-de/strings.xml new file mode 100644 index 00000000..224245d0 --- /dev/null +++ b/res/values-de/strings.xml @@ -0,0 +1,31 @@ + + + + "Auf Download-Manager zugreifen" + "Ermöglicht der Anwendung den Zugriff auf den Download-Manager zum Herunterladen von Dateien. Diese Funktion kann von bösartigen Anwendungen dazu verwendet werden, Ladevorgänge zu unterbrechen und auf private Daten zuzugreifen." + "Erweiterte Funktionen des Download-Managers." + "Erlaubt der Anwendung, auf die erweiterten Funktionen des Download-Managers zuzugreifen."\n" Schädliche Anwendungen können so Downloads unterbrechen und auf"\n" persönliche Daten zugreifen." + "Systemcache verwenden" + "Ermöglicht es der Anwendung, direkt auf den Systemcache zuzugreifen und diesen zu ändern oder zu löschen. Diese Funktion kann von bösartigen Anwendungen dazu verwendet werden, Ladevorgänge und andere Anwendungen schwerwiegend zu stören sowie auf private Daten zuzugreifen." + "Benachrichtigungen zu Ladevorgängen senden" + "Ermöglicht es der Anwendung, Benachrichtigungen zu abgeschlossenen Ladevorgängen zu senden. Diese Funktion kann von bösartigen Anwendungen dazu verwendet werden, den Ladevorgang anderer Anwendungen zu stören." + "<Unbenannt>" + ", " + " und %d weitere" + "Ladevorgang abgeschlossen" + "Fehler beim Ladevorgang" + diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml new file mode 100644 index 00000000..61e0dbf4 --- /dev/null +++ b/res/values-es/strings.xml @@ -0,0 +1,31 @@ + + + + "Acceso al administrador de descargas" + "Permite que la aplicación acceda al administrador de descargas y lo utilice para descargar archivos. Las aplicaciones malintencionadas pueden utilizar este permiso para provocar daños en las descargas y acceder a información privada." + "Funciones avanzadas del administrador de descargas" + "Permite que la aplicación acceda a las funciones avanzadas de los administradores de descargas."\n" Las aplicaciones malintencionadas pueden utilizar este permiso para provocar daños en las descargas"\n" y acceder a información privada." + "Uso de la memoria caché del sistema" + "Permite que la aplicación acceda directamente a la memoria caché del sistema, la modifique y la elimine. Las aplicaciones malintencionadas pueden utilizar este permiso para provocar graves daños en las descargas y en otras aplicaciones, así como para acceder a datos privados." + "Envío de notificaciones de descarga" + "Permite que la aplicación envíe notificaciones sobre descargas completadas. Las aplicaciones malintencionadas pueden utilizar este permiso para confundir a otras aplicaciones que descarguen archivos." + "<Sin título>" + ", " + " y %d más" + "Descarga completada" + "Descarga incorrecta" + diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml new file mode 100644 index 00000000..dd1693a3 --- /dev/null +++ b/res/values-fr/strings.xml @@ -0,0 +1,31 @@ + + + + "Accéder au gestionnaire de téléchargement." + "Permet à l\'application d\'accéder au gestionnaire de téléchargement et de l\'utiliser pour télécharger des fichiers. Les applications malveillantes peuvent s\'en servir pour entraver les téléchargements et accéder aux informations personnelles." + "Fonctions avancées du gestionnaire de téléchargement." + "Permet à l\'application d\'accéder aux fonctions avancées des gestionnaires de téléchargements."\n" Des applications malveillantes peuvent utiliser cette option pour perturber les téléchargements et accéder"\n" à des informations confidentielles." + "Utiliser le cache système" + "Permet à l\'application d\'accéder directement au cache système, de le modifier et de le supprimer. Les applications malveillantes peuvent s\'en servir pour entraver sévèrement les téléchargements et autres applications et pour accéder à des données personnelles." + "Envoyer des notifications de téléchargement." + "Permet à l\'application d\'envoyer des notifications concernant les téléchargements effectués. Les applications malveillantes peuvent s\'en servir pour tromper les autres applications de téléchargement de fichiers." + "<Sans_titre>" + ", " + " et %d autres" + "Téléchargement terminé." + "Échec du téléchargement" + diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml new file mode 100644 index 00000000..38b353c6 --- /dev/null +++ b/res/values-it/strings.xml @@ -0,0 +1,31 @@ + + + + "Accedere al gestore dei download." + "Consente l\'accesso dell\'applicazione al gestore dei download e il suo utilizzo per scaricare file. Le applicazioni dannose possono sfruttare questa possibilità per interrompere download e accedere a informazioni riservate." + "Funzioni avanzate del gestore dei download." + "Consente l\'accesso dell\'applicazione alle funzioni avanzate del gestore dei download."\n" Le applicazioni dannose possono sfruttare questa possibilità per interrompere download e accedere a"\n" informazioni riservate." + "Usare la cache del sistema." + "Consente l\'accesso diretto dell\'applicazione alla cache del sistema, nonché la modifica e l\'eliminazione della cache. Le applicazioni dannose possono sfruttare questa possibilità per interrompere download e altre applicazioni e accedere a dati riservati." + "Inviare notifiche di download." + "Consente l\'invio da parte dell\'applicazione di notifiche relative ai download completati. Le applicazioni dannose possono sfruttare questa possibilità per \"confondere\" altre applicazioni usate per scaricare file." + "<Senza nome>" + ", " + " e altri %d" + "Download completato" + "Download non riuscito" + diff --git a/res/values-ja/strings.xml b/res/values-ja/strings.xml new file mode 100644 index 00000000..ceb551c4 --- /dev/null +++ b/res/values-ja/strings.xml @@ -0,0 +1,31 @@ + + + + "ダウンロードマネージャーにアクセスします。" + "ダウンロードマネージャーにアクセスしてファイルをダウンロードすることをアプリケーションに許可します。悪意のあるアプリケーションがこれを利用して、ダウンロードに深刻な影響を与えたり、個人データにアクセスしたりする恐れがあり。" + "ダウンロードマネージャーの高度な機能です。" + "ダウンロードマネージャーの高度な機能にアプリケーションでアクセスできるようにします。"\n" 悪意のあるアプリケーションではこれを利用して、ダウンロードに深刻な影響を与えたり、"\n" 個人情報にアクセスしたりできます。" + "システムキャッシュを使用します。" + "システムキャッシュの直接アクセス、変更、削除をアプリケーションに許可します。悪意のあるアプリケーションがダウンロードや他のアプリケーションに深刻な影響を与えたり、個人データにアクセスする恐れがあります。" + "ダウンロード通知を送信します。" + "ダウンロード完了の通知の送信をアプリケーションに許可します。悪意のあるアプリケーションがファイルをダウンロードする他のアプリケーションの処理を妨害する恐れがあります。" + "<無題>" + "、 " + " 他%d件" + "ダウンロード完了" + "ダウンロードに失敗しました" + diff --git a/res/values-ko/strings.xml b/res/values-ko/strings.xml new file mode 100644 index 00000000..c37f4bd1 --- /dev/null +++ b/res/values-ko/strings.xml @@ -0,0 +1,31 @@ + + + + "다운로드 관리자 액세스" + "응용 프로그램이 다운로드 관리자에 액세스하여 파일을 다운로드할 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 다운로드를 손상시키고 개인 정보에 액세스할 수 있습니다." + "다운로드 관리자 고급 기능" + "응용프로그램이 다운로드 관리자의 고급 기능에 액세스할 수 있습니다."\n" 악성 응용프로그램은 이 기능을 이용하여 다운로드를 중단시키고"\n" 개인 정보에 액세스할 수 있습니다." + "시스템 캐시 사용" + "응용 프로그램이 시스템 캐시에 직접 액세스, 수정 및 삭제할 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 다운로드와 기타 응용 프로그램을 심하게 손상시키고 개인 데이터에 액세스할 수 있습니다." + "다운로드 알림 보내기" + "응용 프로그램이 완료된 다운로드에 대한 알림을 보낼 수 있습니다. 악성 응용 프로그램은 이 기능을 이용하여 파일을 다운로드하는 다른 응용 프로그램과 혼동하도록 할 수 있습니다." + "<제목없음>" + ", " + " 및 %d개 이상" + "다운로드 완료" + "다운로드 실패" + diff --git a/res/values-nb/strings.xml b/res/values-nb/strings.xml new file mode 100644 index 00000000..548d737d --- /dev/null +++ b/res/values-nb/strings.xml @@ -0,0 +1,32 @@ + + + + "Få tilgang til nedlasteren." + "Gir applikasjonen tilgang til nedlasteren, og å bruke den til å laste ned filer. Ondsinnede programmer kan bruke dette til å forstyrre nedlastinger og få tilgang til privat informasjon." + "Avansert nedlastingsfunksjonalitet." + + + "Bruke systemets hurtigbuffer." + "Gir applikasjonen direkte tilgang til systemets hurtigbuffer, inkludert å redigere og slette den. Ondsinnede applikasjoner kan bruke dette til å forstyrre nedlastinger og andre applikasjoner, og til å få tilgang til privat informasjon." + "Sende nedlastingsvarslinger" + "Lar applikasjonen sende varslinger om ferdige nedlastinger. Ondsinnede applikasjoner kan bruke dette for å forvirre andre applikasjoner som laster ned filer." + "<Uten navn>" + ", " + " samt %d til" + "Ferdig nedlasting" + "Mislykket nedlasting" + diff --git a/res/values-nl/strings.xml b/res/values-nl/strings.xml new file mode 100644 index 00000000..cdaaf544 --- /dev/null +++ b/res/values-nl/strings.xml @@ -0,0 +1,31 @@ + + + + "Downloadbeheer weergeven." + "Hiermee kan de toepassing Downloadbeheer gebruiken om bestanden te downloaden. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om downloads te verstoren en om toegang te krijgen tot privégegevens." + "Geavanceerde functies van de downloadbeheerder." + "Hiermee krijgt de toepassing toegang tot de geavanceerde functies van de downloadbeheerder."\n" Schadelijke toepassingen kunnen hiermee downloads onderbreken en toegang krijgen tot uw "\n" privégegevens." + "Systeemcache gebruiken." + "Hiermee kan de toepassing rechtstreeks de systeemcache openen, aanpassen of wissen. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om downloads en andere toepassingen te verstoren en om toegang te krijgen tot privégegevens." + "Downloadmeldingen verzenden." + "Hiermee ontvangt u een melding zodra een download is voltooid. Kwaadwillende toepassingen kunnen hiervan gebruikmaken om andere toepassingen die bestanden downloaden, in de war te brengen." + "<Zonder titel>" + ", " + " en nog %d" + "Downloaden is voltooid" + "Downloaden is mislukt." + diff --git a/res/values-pl/strings.xml b/res/values-pl/strings.xml new file mode 100644 index 00000000..6e77eafc --- /dev/null +++ b/res/values-pl/strings.xml @@ -0,0 +1,31 @@ + + + + "Dostęp do menedżera pobierania." + "Umożliwia programowi dostęp do menedżera pobierania i pobieranie plików przy jego użyciu. Szkodliwe programy mogą w ten sposób zakłócić pobieranie i uzyskać dostęp do prywatnych informacji." + "Zaawansowane funkcje menedżera pobierania." + "Zezwala aplikacji na dostęp do zaawansowanych funkcji menedżera pobierania."\n" Złośliwe aplikacje mogą to wykorzystać do przerywania pobierania i uzyskiwania dostępu do"\n" informacji poufnych." + "Korzystanie z systemowej pamięci podręcznej." + "Umożliwia programowi bezpośredni dostęp do systemowej pamięci podręcznej, jej modyfikację oraz usuwanie. Szkodliwe programy mogą w ten sposób poważnie zakłócić pobieranie plików i działanie innych programów, a także uzyskać dostęp do prywatnych informacji." + "Wysyłanie powiadomień o pobraniu." + "Umożliwia programowi wysyłanie powiadomień o ukończeniu pobierania. Szkodliwe programy mogą korzystać z tego uprawnienia, aby zakłócić działanie innych programów pobierających pliki." + "<Bez nazwy>" + ", " + " i %d innych" + "Pobieranie zakończone." + "Pobieranie nie powiodło się" + diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml new file mode 100644 index 00000000..a76850f2 --- /dev/null +++ b/res/values-ru/strings.xml @@ -0,0 +1,31 @@ + + + + "Открывать диспетчер загрузок." + "Разрешает приложениям доступ к диспетчеру загрузок и его использование для загрузки файлов. Вредоносные приложения могут использовать это для прерывания загрузок и получения доступа к личной информации." + "Дополнительные функции диспетчера загрузок." + "Разрешает приложению доступ к дополнительным функциям диспетчера загрузок."\n" Вредоносное ПО может использовать это для прерывания загрузок и получения доступа"\n" к личной информации." + "Использовать кэш системы" + "Разрешает приложениям прямой доступ, изменение и удаление в системном кэше. Вредоносные приложения могут использовать это для прерывания загрузок и работы других приложений, а также для получения доступа к личной информации." + "Отправлять уведомления о загрузках." + "Разрешает приложениям отправлять уведомления о завершенных загрузках. Вредоносные приложения могут использовать это, чтобы передавать ложную информацию другим приложениям загрузки файлов." + "<Без названия>" + ", " + " и еще %d" + "Загрузка завершена" + "Загрузка не удалась" + diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml new file mode 100644 index 00000000..7802b9bd --- /dev/null +++ b/res/values-zh-rCN/strings.xml @@ -0,0 +1,31 @@ + + + + "访问下载管理程序。" + "允许应用程序访问下载管理程序以及将其用于下载文件。恶意应用程序可以使用该功能干扰下载,以及访问隐私信息。" + "高级下载管理程序功能。" + "允许应用程序访问下载管理程序高级功能。"\n" 恶意应用程序可能会使用此权限干扰下载,以及"\n" 访问隐私信息。" + "使用系统缓存。" + "允许应用程序直接访问、修改和删除系统缓存。恶意应用程序可以使用该功能严重干扰下载和其他应用程序,以及访问隐私数据。" + "发送下载通知。" + "允许应用程序发送关于已完成下载的通知。恶意应用程序可以使用该功能干扰其他下载文件的应用程序。" + "<未命名>" + "、 " + " 以及另外 %d 个" + "下载完成" + "下载不成功" + diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml new file mode 100644 index 00000000..0bf222bc --- /dev/null +++ b/res/values-zh-rTW/strings.xml @@ -0,0 +1,31 @@ + + + + "存取下載管理員。" + "允許應用程式存取下載管理員,並使用它下載檔案。惡意程式可使用此功能,影響下載並存取個人資料。" + "下載管理員進階功能。" + "允許應用程式存取下載管理員的進階功能。"\n" 惡意應用程式可能使用此功能讓下載發生錯誤並存取私人資訊。"\n + "使用系統快取。" + "允許應用程式直接存取、修改與刪除系統快取。惡意程式可使用此功能,嚴重影響下載與其他應用程式,並存取個人資料。" + "傳送下載通知。" + "下載完成時,允許應用程式送出通知。惡意程式可使用此功能干擾其他正在下載檔案的應用程式。" + "(未命名)" + ", " + " 還有 %d 項下載" + "下載已完成。" + "下載失敗" + diff --git a/res/values/strings.xml b/res/values/strings.xml new file mode 100644 index 00000000..3a8fa076 --- /dev/null +++ b/res/values/strings.xml @@ -0,0 +1,119 @@ + + + + + + Access download manager. + + Allows the application to + access the download manager and to use it to download files. + Malicious applications can use this to disrupt downloads and access + private information. + + + Advanced download + manager functions. + + Allows the application to + access the download manager's advanced functions. + Malicious applications can use this to disrupt downloads and access + private information. + + + Use system cache. + + Allows the application + to directly access, modify and delete the system cache. Malicious + applications can use this to severely disrupt downloads and + other applications, and to access private data. + + Send download + notifications. + + Allows the application + to send notifications about completed downloads. Malicious applications + can use this to confuse other applications that download + files. + + + <Untitled> + + + ", " + + + " and %d more" + + + Download complete + + + Download unsuccessful + + + diff --git a/src/com/android/providers/downloads/Constants.java b/src/com/android/providers/downloads/Constants.java new file mode 100644 index 00000000..cffda04a --- /dev/null +++ b/src/com/android/providers/downloads/Constants.java @@ -0,0 +1,151 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.providers.downloads; + +import android.util.Config; +import android.util.Log; + +/** + * Contains the internal constants that are used in the download manager. + * As a general rule, modifying these constants should be done with care. + */ +public class Constants { + + /** Tag used for debugging/logging */ + public static final String TAG = "DownloadManager"; + + /** The column that used to be used for the HTTP method of the request */ + public static final String RETRY_AFTER___REDIRECT_COUNT = "method"; + + /** The column that used to be used for the magic OTA update filename */ + public static final String OTA_UPDATE = "otaupdate"; + + /** The column that used to be used to reject system filetypes */ + public static final String NO_SYSTEM_FILES = "no_system"; + + /** The column that is used for the downloads's ETag */ + public static final String ETAG = "etag"; + + /** The column that is used for the initiating app's UID */ + public static final String UID = "uid"; + + /** The column that is used to remember whether the media scanner was invoked */ + public static final String MEDIA_SCANNED = "scanned"; + + /** The column that is used to count retries */ + public static final String FAILED_CONNECTIONS = "numfailed"; + + /** The intent that gets sent when the service must wake up for a retry */ + public static final String ACTION_RETRY = "android.intent.action.DOWNLOAD_WAKEUP"; + + /** the intent that gets sent when clicking a successful download */ + public static final String ACTION_OPEN = "android.intent.action.DOWNLOAD_OPEN"; + + /** the intent that gets sent when clicking an incomplete/failed download */ + public static final String ACTION_LIST = "android.intent.action.DOWNLOAD_LIST"; + + /** the intent that gets sent when deleting the notification of a completed download */ + public static final String ACTION_HIDE = "android.intent.action.DOWNLOAD_HIDE"; + + /** The default base name for downloaded files if we can't get one at the HTTP level */ + public static final String DEFAULT_DL_FILENAME = "downloadfile"; + + /** The default extension for html files if we can't get one at the HTTP level */ + public static final String DEFAULT_DL_HTML_EXTENSION = ".html"; + + /** The default extension for text files if we can't get one at the HTTP level */ + public static final String DEFAULT_DL_TEXT_EXTENSION = ".txt"; + + /** The default extension for binary files if we can't get one at the HTTP level */ + public static final String DEFAULT_DL_BINARY_EXTENSION = ".bin"; + + /** + * When a number has to be appended to the filename, this string is used to separate the + * base filename from the sequence number + */ + public static final String FILENAME_SEQUENCE_SEPARATOR = "-"; + + /** Where we store downloaded files on the external storage */ + public static final String DEFAULT_DL_SUBDIR = "/download"; + + /** A magic filename that is allowed to exist within the system cache */ + public static final String KNOWN_SPURIOUS_FILENAME = "lost+found"; + + /** A magic filename that is allowed to exist within the system cache */ + public static final String RECOVERY_DIRECTORY = "recovery"; + + /** The default user agent used for downloads */ + public static final String DEFAULT_USER_AGENT = "AndroidDownloadManager"; + + /** The MIME type of special DRM files */ + public static final String MIMETYPE_DRM_MESSAGE = + android.drm.mobile1.DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING; + + /** The MIME type of APKs */ + public static final String MIMETYPE_APK = "application/vnd.android.package"; + + /** The buffer size used to stream the data */ + public static final int BUFFER_SIZE = 4096; + + /** The minimum amount of progress that has to be done before the progress bar gets updated */ + public static final int MIN_PROGRESS_STEP = 4096; + + /** The minimum amount of time that has to elapse before the progress bar gets updated, in ms */ + public static final long MIN_PROGRESS_TIME = 1500; + + /** The maximum number of rows in the database (FIFO) */ + public static final int MAX_DOWNLOADS = 1000; + + /** + * The number of times that the download manager will retry its network + * operations when no progress is happening before it gives up. + */ + public static final int MAX_RETRIES = 5; + + /** + * The minimum amount of time that the download manager accepts for + * a Retry-After response header with a parameter in delta-seconds. + */ + public static final int MIN_RETRY_AFTER = 30; // 30s + + /** + * The maximum amount of time that the download manager accepts for + * a Retry-After response header with a parameter in delta-seconds. + */ + public static final int MAX_RETRY_AFTER = 24 * 60 * 60; // 24h + + /** + * The maximum number of redirects. + */ + public static final int MAX_REDIRECTS = 5; // can't be more than 7. + + /** + * The time between a failure and the first retry after an IOException. + * Each subsequent retry grows exponentially, doubling each time. + * The time is in seconds. + */ + public static final int RETRY_FIRST_DELAY = 30; + + /** Enable verbose logging - use with "setprop log.tag.DownloadManager VERBOSE" */ + private static final boolean LOCAL_LOGV = true; + public static final boolean LOGV = Config.LOGV + || (Config.LOGD && LOCAL_LOGV && Log.isLoggable(TAG, Log.VERBOSE)); + + /** Enable super-verbose logging */ + private static final boolean LOCAL_LOGVV = false; + public static final boolean LOGVV = LOCAL_LOGVV && LOGV; +} diff --git a/src/com/android/providers/downloads/DownloadFileInfo.java b/src/com/android/providers/downloads/DownloadFileInfo.java new file mode 100644 index 00000000..29cbd940 --- /dev/null +++ b/src/com/android/providers/downloads/DownloadFileInfo.java @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.providers.downloads; + +import java.io.FileOutputStream; + +/** + * Stores information about the file in which a download gets saved. + */ +public class DownloadFileInfo { + public DownloadFileInfo(String filename, FileOutputStream stream, int status) { + this.filename = filename; + this.stream = stream; + this.status = status; + } + + String filename; + FileOutputStream stream; + int status; +} diff --git a/src/com/android/providers/downloads/DownloadInfo.java b/src/com/android/providers/downloads/DownloadInfo.java new file mode 100644 index 00000000..e051f41a --- /dev/null +++ b/src/com/android/providers/downloads/DownloadInfo.java @@ -0,0 +1,212 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.providers.downloads; + +import android.net.Uri; +import android.content.Context; +import android.content.Intent; +import android.provider.Downloads; + +/** + * Stores information about an individual download. + */ +public class DownloadInfo { + public int id; + public String uri; + public boolean noIntegrity; + public String hint; + public String filename; + public String mimetype; + public int destination; + public int visibility; + public int control; + public int status; + public int numFailed; + public int retryAfter; + public int redirectCount; + public long lastMod; + public String pckg; + public String clazz; + public String extras; + public String cookies; + public String userAgent; + public String referer; + public int totalBytes; + public int currentBytes; + public String etag; + public boolean mediaScanned; + + public volatile boolean hasActiveThread; + + public DownloadInfo(int id, String uri, boolean noIntegrity, + String hint, String filename, + String mimetype, int destination, int visibility, int control, + int status, int numFailed, int retryAfter, int redirectCount, long lastMod, + String pckg, String clazz, String extras, String cookies, + String userAgent, String referer, int totalBytes, int currentBytes, String etag, + boolean mediaScanned) { + this.id = id; + this.uri = uri; + this.noIntegrity = noIntegrity; + this.hint = hint; + this.filename = filename; + this.mimetype = mimetype; + this.destination = destination; + this.visibility = visibility; + this.control = control; + this.status = status; + this.numFailed = numFailed; + this.retryAfter = retryAfter; + this.redirectCount = redirectCount; + this.lastMod = lastMod; + this.pckg = pckg; + this.clazz = clazz; + this.extras = extras; + this.cookies = cookies; + this.userAgent = userAgent; + this.referer = referer; + this.totalBytes = totalBytes; + this.currentBytes = currentBytes; + this.etag = etag; + this.mediaScanned = mediaScanned; + } + + public void sendIntentIfRequested(Uri contentUri, Context context) { + if (pckg != null && clazz != null) { + Intent intent = new Intent(Downloads.DOWNLOAD_COMPLETED_ACTION); + intent.setClassName(pckg, clazz); + if (extras != null) { + intent.putExtra(Downloads.NOTIFICATION_EXTRAS, extras); + } + // We only send the content: URI, for security reasons. Otherwise, malicious + // applications would have an easier time spoofing download results by + // sending spoofed intents. + intent.setData(contentUri); + context.sendBroadcast(intent); + } + } + + /** + * Returns the time when a download should be restarted. Must only + * be called when numFailed > 0. + */ + public long restartTime() { + if (retryAfter > 0) { + return lastMod + retryAfter; + } + return lastMod + + Constants.RETRY_FIRST_DELAY * + (1000 + Helpers.rnd.nextInt(1001)) * (1 << (numFailed - 1)); + } + + /** + * Returns whether this download (which the download manager hasn't seen yet) + * should be started. + */ + public boolean isReadyToStart(long now) { + if (control == Downloads.CONTROL_PAUSED) { + // the download is paused, so it's not going to start + return false; + } + if (status == 0) { + // status hasn't been initialized yet, this is a new download + return true; + } + if (status == Downloads.STATUS_PENDING) { + // download is explicit marked as ready to start + return true; + } + if (status == Downloads.STATUS_RUNNING) { + // download was interrupted (process killed, loss of power) while it was running, + // without a chance to update the database + return true; + } + if (status == Downloads.STATUS_RUNNING_PAUSED) { + if (numFailed == 0) { + // download is waiting for network connectivity to return before it can resume + return true; + } + if (restartTime() < now) { + // download was waiting for a delayed restart, and the delay has expired + return true; + } + } + return false; + } + + /** + * Returns whether this download (which the download manager has already seen + * and therefore potentially started) should be restarted. + * + * In a nutshell, this returns true if the download isn't already running + * but should be, and it can know whether the download is already running + * by checking the status. + */ + public boolean isReadyToRestart(long now) { + if (control == Downloads.CONTROL_PAUSED) { + // the download is paused, so it's not going to restart + return false; + } + if (status == 0) { + // download hadn't been initialized yet + return true; + } + if (status == Downloads.STATUS_PENDING) { + // download is explicit marked as ready to start + return true; + } + if (status == Downloads.STATUS_RUNNING_PAUSED) { + if (numFailed == 0) { + // download is waiting for network connectivity to return before it can resume + return true; + } + if (restartTime() < now) { + // download was waiting for a delayed restart, and the delay has expired + return true; + } + } + return false; + } + + /** + * Returns whether this download has a visible notification after + * completion. + */ + public boolean hasCompletionNotification() { + if (!Downloads.isStatusCompleted(status)) { + return false; + } + if (visibility == Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) { + return true; + } + return false; + } + + /** + * Returns whether this download is allowed to use the network. + */ + public boolean canUseNetwork(boolean available, boolean roaming) { + if (!available) { + return false; + } + if (destination == Downloads.DESTINATION_CACHE_PARTITION_NOROAMING) { + return !roaming; + } else { + return true; + } + } +} diff --git a/src/com/android/providers/downloads/DownloadNotification.java b/src/com/android/providers/downloads/DownloadNotification.java new file mode 100644 index 00000000..ed17ab7a --- /dev/null +++ b/src/com/android/providers/downloads/DownloadNotification.java @@ -0,0 +1,300 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.providers.downloads; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.provider.Downloads; +import android.widget.RemoteViews; + +import java.util.HashMap; + +/** + * This class handles the updating of the Notification Manager for the + * cases where there is an ongoing download. Once the download is complete + * (be it successful or unsuccessful) it is no longer the responsibility + * of this component to show the download in the notification manager. + * + */ +class DownloadNotification { + + Context mContext; + public NotificationManager mNotificationMgr; + HashMap mNotifications; + + static final String LOGTAG = "DownloadNotification"; + static final String WHERE_RUNNING = + "(" + Downloads.STATUS + " >= '100') AND (" + + Downloads.STATUS + " <= '199') AND (" + + Downloads.VISIBILITY + " IS NULL OR " + + Downloads.VISIBILITY + " == '" + Downloads.VISIBILITY_VISIBLE + "' OR " + + Downloads.VISIBILITY + " == '" + Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED + "')"; + static final String WHERE_COMPLETED = + Downloads.STATUS + " >= '200' AND " + + Downloads.VISIBILITY + " == '" + Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED + "'"; + + + /** + * This inner class is used to collate downloads that are owned by + * the same application. This is so that only one notification line + * item is used for all downloads of a given application. + * + */ + static class NotificationItem { + int id; // This first db _id for the download for the app + int totalCurrent = 0; + int totalTotal = 0; + int titleCount = 0; + String packageName; // App package name + String description; + String[] titles = new String[2]; // download titles. + + /* + * Add a second download to this notification item. + */ + void addItem(String title, int currentBytes, int totalBytes) { + totalCurrent += currentBytes; + if (totalBytes <= 0 || totalTotal == -1) { + totalTotal = -1; + } else { + totalTotal += totalBytes; + } + if (titleCount < 2) { + titles[titleCount] = title; + } + titleCount++; + } + } + + + /** + * Constructor + * @param ctx The context to use to obtain access to the + * Notification Service + */ + DownloadNotification(Context ctx) { + mContext = ctx; + mNotificationMgr = (NotificationManager) mContext + .getSystemService(Context.NOTIFICATION_SERVICE); + mNotifications = new HashMap(); + } + + /* + * Update the notification ui. + */ + public void updateNotification() { + updateActiveNotification(); + updateCompletedNotification(); + } + + private void updateActiveNotification() { + // Active downloads + Cursor c = mContext.getContentResolver().query( + Downloads.CONTENT_URI, new String [] { + Downloads._ID, Downloads.TITLE, Downloads.DESCRIPTION, + Downloads.NOTIFICATION_PACKAGE, + Downloads.NOTIFICATION_CLASS, + Downloads.CURRENT_BYTES, Downloads.TOTAL_BYTES, + Downloads.STATUS, Downloads._DATA + }, + WHERE_RUNNING, null, Downloads._ID); + + if (c == null) { + return; + } + + // Columns match projection in query above + final int idColumn = 0; + final int titleColumn = 1; + final int descColumn = 2; + final int ownerColumn = 3; + final int classOwnerColumn = 4; + final int currentBytesColumn = 5; + final int totalBytesColumn = 6; + final int statusColumn = 7; + final int filenameColumnId = 8; + + // Collate the notifications + mNotifications.clear(); + for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { + String packageName = c.getString(ownerColumn); + int max = c.getInt(totalBytesColumn); + int progress = c.getInt(currentBytesColumn); + String title = c.getString(titleColumn); + if (title == null || title.length() == 0) { + title = mContext.getResources().getString( + R.string.download_unknown_title); + } + if (mNotifications.containsKey(packageName)) { + mNotifications.get(packageName).addItem(title, progress, max); + } else { + NotificationItem item = new NotificationItem(); + item.id = c.getInt(idColumn); + item.packageName = packageName; + item.description = c.getString(descColumn); + String className = c.getString(classOwnerColumn); + item.addItem(title, progress, max); + mNotifications.put(packageName, item); + } + + } + c.close(); + + // Add the notifications + for (NotificationItem item : mNotifications.values()) { + // Build the notification object + Notification n = new Notification(); + n.icon = android.R.drawable.stat_sys_download; + + n.flags |= Notification.FLAG_ONGOING_EVENT; + + // Build the RemoteView object + RemoteViews expandedView = new RemoteViews( + "com.android.providers.downloads", + R.layout.status_bar_ongoing_event_progress_bar); + StringBuilder title = new StringBuilder(item.titles[0]); + if (item.titleCount > 1) { + title.append(mContext.getString(R.string.notification_filename_separator)); + title.append(item.titles[1]); + n.number = item.titleCount; + if (item.titleCount > 2) { + title.append(mContext.getString(R.string.notification_filename_extras, + new Object[] { Integer.valueOf(item.titleCount - 2) })); + } + } else { + expandedView.setTextViewText(R.id.description, + item.description); + } + expandedView.setTextViewText(R.id.title, title); + expandedView.setProgressBar(R.id.progress_bar, + item.totalTotal, + item.totalCurrent, + item.totalTotal == -1); + expandedView.setTextViewText(R.id.progress_text, + getDownloadingText(item.totalTotal, item.totalCurrent)); + expandedView.setImageViewResource(R.id.appIcon, + android.R.drawable.stat_sys_download); + n.contentView = expandedView; + + Intent intent = new Intent(Constants.ACTION_LIST); + intent.setClassName("com.android.providers.downloads", + DownloadReceiver.class.getName()); + intent.setData(Uri.parse(Downloads.CONTENT_URI + "/" + item.id)); + intent.putExtra("multiple", item.titleCount > 1); + + n.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); + + mNotificationMgr.notify(item.id, n); + + } + } + + private void updateCompletedNotification() { + // Completed downloads + Cursor c = mContext.getContentResolver().query( + Downloads.CONTENT_URI, new String [] { + Downloads._ID, Downloads.TITLE, Downloads.DESCRIPTION, + Downloads.NOTIFICATION_PACKAGE, + Downloads.NOTIFICATION_CLASS, + Downloads.CURRENT_BYTES, Downloads.TOTAL_BYTES, + Downloads.STATUS, Downloads._DATA, + Downloads.LAST_MODIFICATION, Downloads.DESTINATION + }, + WHERE_COMPLETED, null, Downloads._ID); + + if (c == null) { + return; + } + + // Columns match projection in query above + final int idColumn = 0; + final int titleColumn = 1; + final int descColumn = 2; + final int ownerColumn = 3; + final int classOwnerColumn = 4; + final int currentBytesColumn = 5; + final int totalBytesColumn = 6; + final int statusColumn = 7; + final int filenameColumnId = 8; + final int lastModColumnId = 9; + final int destinationColumnId = 10; + + for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { + // Add the notifications + Notification n = new Notification(); + n.icon = android.R.drawable.stat_sys_download_done; + + String title = c.getString(titleColumn); + if (title == null || title.length() == 0) { + title = mContext.getResources().getString( + R.string.download_unknown_title); + } + Uri contentUri = Uri.parse(Downloads.CONTENT_URI + "/" + c.getInt(idColumn)); + String caption; + Intent intent; + if (Downloads.isStatusError(c.getInt(statusColumn))) { + caption = mContext.getResources() + .getString(R.string.notification_download_failed); + intent = new Intent(Constants.ACTION_LIST); + } else { + caption = mContext.getResources() + .getString(R.string.notification_download_complete); + if (c.getInt(destinationColumnId) == Downloads.DESTINATION_EXTERNAL) { + intent = new Intent(Constants.ACTION_OPEN); + } else { + intent = new Intent(Constants.ACTION_LIST); + } + } + intent.setClassName("com.android.providers.downloads", + DownloadReceiver.class.getName()); + intent.setData(contentUri); + n.setLatestEventInfo(mContext, title, caption, + PendingIntent.getBroadcast(mContext, 0, intent, 0)); + + intent = new Intent(Constants.ACTION_HIDE); + intent.setClassName("com.android.providers.downloads", + DownloadReceiver.class.getName()); + intent.setData(contentUri); + n.deleteIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); + + n.when = c.getLong(lastModColumnId); + + mNotificationMgr.notify(c.getInt(idColumn), n); + } + c.close(); + } + + /* + * Helper function to build the downloading text. + */ + private String getDownloadingText(long totalBytes, long currentBytes) { + if (totalBytes <= 0) { + return ""; + } + long progress = currentBytes * 100 / totalBytes; + StringBuilder sb = new StringBuilder(); + sb.append(progress); + sb.append('%'); + return sb.toString(); + } + +} diff --git a/src/com/android/providers/downloads/DownloadProvider.java b/src/com/android/providers/downloads/DownloadProvider.java new file mode 100644 index 00000000..f7cdd51e --- /dev/null +++ b/src/com/android/providers/downloads/DownloadProvider.java @@ -0,0 +1,731 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.providers.downloads; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.content.UriMatcher; +import android.content.pm.PackageManager; +import android.database.CrossProcessCursor; +import android.database.Cursor; +import android.database.CursorWindow; +import android.database.CursorWrapper; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.database.sqlite.SQLiteQueryBuilder; +import android.database.SQLException; +import android.net.Uri; +import android.os.Binder; +import android.os.ParcelFileDescriptor; +import android.os.Process; +import android.provider.Downloads; +import android.util.Config; +import android.util.Log; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.HashSet; + + +/** + * Allows application to interact with the download manager. + */ +public final class DownloadProvider extends ContentProvider { + + /** Database filename */ + private static final String DB_NAME = "downloads.db"; + /** Current database version */ + private static final int DB_VERSION = 100; + /** Database version from which upgrading is a nop */ + private static final int DB_VERSION_NOP_UPGRADE_FROM = 31; + /** Database version to which upgrading is a nop */ + private static final int DB_VERSION_NOP_UPGRADE_TO = 100; + /** Name of table in the database */ + private static final String DB_TABLE = "downloads"; + + /** MIME type for the entire download list */ + private static final String DOWNLOAD_LIST_TYPE = "vnd.android.cursor.dir/download"; + /** MIME type for an individual download */ + private static final String DOWNLOAD_TYPE = "vnd.android.cursor.item/download"; + + /** URI matcher used to recognize URIs sent by applications */ + private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH); + /** URI matcher constant for the URI of the entire download list */ + private static final int DOWNLOADS = 1; + /** URI matcher constant for the URI of an individual download */ + private static final int DOWNLOADS_ID = 2; + static { + sURIMatcher.addURI("downloads", "download", DOWNLOADS); + sURIMatcher.addURI("downloads", "download/#", DOWNLOADS_ID); + } + + private static final String[] sAppReadableColumnsArray = new String[] { + Downloads._ID, + Downloads.APP_DATA, + Downloads._DATA, + Downloads.MIMETYPE, + Downloads.VISIBILITY, + Downloads.CONTROL, + Downloads.STATUS, + Downloads.LAST_MODIFICATION, + Downloads.NOTIFICATION_PACKAGE, + Downloads.NOTIFICATION_CLASS, + Downloads.TOTAL_BYTES, + Downloads.CURRENT_BYTES, + Downloads.TITLE, + Downloads.DESCRIPTION + }; + + private static HashSet sAppReadableColumnsSet; + static { + sAppReadableColumnsSet = new HashSet(); + for (int i = 0; i < sAppReadableColumnsArray.length; ++i) { + sAppReadableColumnsSet.add(sAppReadableColumnsArray[i]); + } + } + + /** The database that lies underneath this content provider */ + private SQLiteOpenHelper mOpenHelper = null; + + /** + * Creates and updated database on demand when opening it. + * Helper class to create database the first time the provider is + * initialized and upgrade it when a new version of the provider needs + * an updated version of the database. + */ + private final class DatabaseHelper extends SQLiteOpenHelper { + + public DatabaseHelper(final Context context) { + super(context, DB_NAME, null, DB_VERSION); + } + + /** + * Creates database the first time we try to open it. + */ + @Override + public void onCreate(final SQLiteDatabase db) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "populating new database"); + } + createTable(db); + } + + /* (not a javadoc comment) + * Checks data integrity when opening the database. + */ + /* + * @Override + * public void onOpen(final SQLiteDatabase db) { + * super.onOpen(db); + * } + */ + + /** + * Updates the database format when a content provider is used + * with a database that was created with a different format. + */ + // Note: technically, this could also be a downgrade, so if we want + // to gracefully handle upgrades we should be careful about + // what to do on downgrades. + @Override + public void onUpgrade(final SQLiteDatabase db, int oldV, final int newV) { + if (oldV == DB_VERSION_NOP_UPGRADE_FROM) { + if (newV == DB_VERSION_NOP_UPGRADE_TO) { // that's a no-op upgrade. + return; + } + // NOP_FROM and NOP_TO are identical, just in different codelines. Upgrading + // from NOP_FROM is the same as upgrading from NOP_TO. + oldV = DB_VERSION_NOP_UPGRADE_TO; + } + Log.i(Constants.TAG, "Upgrading downloads database from version " + oldV + " to " + newV + + ", which will destroy all old data"); + dropTable(db); + createTable(db); + } + } + + /** + * Initializes the content provider when it is created. + */ + @Override + public boolean onCreate() { + mOpenHelper = new DatabaseHelper(getContext()); + return true; + } + + /** + * Returns the content-provider-style MIME types of the various + * types accessible through this content provider. + */ + @Override + public String getType(final Uri uri) { + int match = sURIMatcher.match(uri); + switch (match) { + case DOWNLOADS: { + return DOWNLOAD_LIST_TYPE; + } + case DOWNLOADS_ID: { + return DOWNLOAD_TYPE; + } + default: { + if (Constants.LOGV) { + Log.v(Constants.TAG, "calling getType on an unknown URI: " + uri); + } + throw new IllegalArgumentException("Unknown URI: " + uri); + } + } + } + + /** + * Creates the table that'll hold the download information. + */ + private void createTable(SQLiteDatabase db) { + try { + db.execSQL("CREATE TABLE " + DB_TABLE + "(" + + Downloads._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + Downloads.URI + " TEXT, " + + Constants.RETRY_AFTER___REDIRECT_COUNT + " INTEGER, " + + Downloads.APP_DATA + " TEXT, " + + Downloads.NO_INTEGRITY + " BOOLEAN, " + + Downloads.FILENAME_HINT + " TEXT, " + + Constants.OTA_UPDATE + " BOOLEAN, " + + Downloads._DATA + " TEXT, " + + Downloads.MIMETYPE + " TEXT, " + + Downloads.DESTINATION + " INTEGER, " + + Constants.NO_SYSTEM_FILES + " BOOLEAN, " + + Downloads.VISIBILITY + " INTEGER, " + + Downloads.CONTROL + " INTEGER, " + + Downloads.STATUS + " INTEGER, " + + Constants.FAILED_CONNECTIONS + " INTEGER, " + + Downloads.LAST_MODIFICATION + " BIGINT, " + + Downloads.NOTIFICATION_PACKAGE + " TEXT, " + + Downloads.NOTIFICATION_CLASS + " TEXT, " + + Downloads.NOTIFICATION_EXTRAS + " TEXT, " + + Downloads.COOKIE_DATA + " TEXT, " + + Downloads.USER_AGENT + " TEXT, " + + Downloads.REFERER + " TEXT, " + + Downloads.TOTAL_BYTES + " INTEGER, " + + Downloads.CURRENT_BYTES + " INTEGER, " + + Constants.ETAG + " TEXT, " + + Constants.UID + " INTEGER, " + + Downloads.OTHER_UID + " INTEGER, " + + Downloads.TITLE + " TEXT, " + + Downloads.DESCRIPTION + " TEXT, " + + Constants.MEDIA_SCANNED + " BOOLEAN);"); + } catch (SQLException ex) { + Log.e(Constants.TAG, "couldn't create table in downloads database"); + throw ex; + } + } + + /** + * Deletes the table that holds the download information. + */ + private void dropTable(SQLiteDatabase db) { + try { + db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE); + } catch (SQLException ex) { + Log.e(Constants.TAG, "couldn't drop table in downloads database"); + throw ex; + } + } + + /** + * Inserts a row in the database + */ + @Override + public Uri insert(final Uri uri, final ContentValues values) { + SQLiteDatabase db = mOpenHelper.getWritableDatabase(); + + if (sURIMatcher.match(uri) != DOWNLOADS) { + if (Config.LOGD) { + Log.d(Constants.TAG, "calling insert on an unknown/invalid URI: " + uri); + } + throw new IllegalArgumentException("Unknown/Invalid URI " + uri); + } + + ContentValues filteredValues = new ContentValues(); + + copyString(Downloads.URI, values, filteredValues); + copyString(Downloads.APP_DATA, values, filteredValues); + copyBoolean(Downloads.NO_INTEGRITY, values, filteredValues); + copyString(Downloads.FILENAME_HINT, values, filteredValues); + copyString(Downloads.MIMETYPE, values, filteredValues); + Integer dest = values.getAsInteger(Downloads.DESTINATION); + if (dest != null) { + if (getContext().checkCallingPermission(Downloads.PERMISSION_ACCESS_ADVANCED) + != PackageManager.PERMISSION_GRANTED + && dest != Downloads.DESTINATION_EXTERNAL + && dest != Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE) { + throw new SecurityException("unauthorized destination code"); + } + filteredValues.put(Downloads.DESTINATION, dest); + } + Integer vis = values.getAsInteger(Downloads.VISIBILITY); + if (vis == null) { + if (dest == Downloads.DESTINATION_EXTERNAL) { + filteredValues.put(Downloads.VISIBILITY, + Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); + } else { + filteredValues.put(Downloads.VISIBILITY, Downloads.VISIBILITY_HIDDEN); + } + } else { + filteredValues.put(Downloads.VISIBILITY, vis); + } + copyInteger(Downloads.CONTROL, values, filteredValues); + filteredValues.put(Downloads.STATUS, Downloads.STATUS_PENDING); + filteredValues.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis()); + String pckg = values.getAsString(Downloads.NOTIFICATION_PACKAGE); + String clazz = values.getAsString(Downloads.NOTIFICATION_CLASS); + if (pckg != null && clazz != null) { + int uid = Binder.getCallingUid(); + try { + if (uid == 0 || + getContext().getPackageManager().getApplicationInfo(pckg, 0).uid == uid) { + filteredValues.put(Downloads.NOTIFICATION_PACKAGE, pckg); + filteredValues.put(Downloads.NOTIFICATION_CLASS, clazz); + } + } catch (PackageManager.NameNotFoundException ex) { + /* ignored for now */ + } + } + copyString(Downloads.NOTIFICATION_EXTRAS, values, filteredValues); + copyString(Downloads.COOKIE_DATA, values, filteredValues); + copyString(Downloads.USER_AGENT, values, filteredValues); + copyString(Downloads.REFERER, values, filteredValues); + if (getContext().checkCallingPermission(Downloads.PERMISSION_ACCESS_ADVANCED) + == PackageManager.PERMISSION_GRANTED) { + copyInteger(Downloads.OTHER_UID, values, filteredValues); + } + filteredValues.put(Constants.UID, Binder.getCallingUid()); + if (Binder.getCallingUid() == 0) { + copyInteger(Constants.UID, values, filteredValues); + } + copyString(Downloads.TITLE, values, filteredValues); + copyString(Downloads.DESCRIPTION, values, filteredValues); + + if (Constants.LOGVV) { + Log.v(Constants.TAG, "initiating download with UID " + + filteredValues.getAsInteger(Constants.UID)); + if (filteredValues.containsKey(Downloads.OTHER_UID)) { + Log.v(Constants.TAG, "other UID " + + filteredValues.getAsInteger(Downloads.OTHER_UID)); + } + } + + Context context = getContext(); + context.startService(new Intent(context, DownloadService.class)); + + long rowID = db.insert(DB_TABLE, null, filteredValues); + + Uri ret = null; + + if (rowID != -1) { + context.startService(new Intent(context, DownloadService.class)); + ret = Uri.parse(Downloads.CONTENT_URI + "/" + rowID); + context.getContentResolver().notifyChange(uri, null); + } else { + if (Config.LOGD) { + Log.d(Constants.TAG, "couldn't insert into downloads database"); + } + } + + return ret; + } + + /** + * Starts a database query + */ + @Override + public Cursor query(final Uri uri, String[] projection, + final String selection, final String[] selectionArgs, + final String sort) { + + Helpers.validateSelection(selection, sAppReadableColumnsSet); + + SQLiteDatabase db = mOpenHelper.getReadableDatabase(); + + SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); + + int match = sURIMatcher.match(uri); + boolean emptyWhere = true; + switch (match) { + case DOWNLOADS: { + qb.setTables(DB_TABLE); + break; + } + case DOWNLOADS_ID: { + qb.setTables(DB_TABLE); + qb.appendWhere(Downloads._ID + "="); + qb.appendWhere(uri.getPathSegments().get(1)); + emptyWhere = false; + break; + } + default: { + if (Constants.LOGV) { + Log.v(Constants.TAG, "querying unknown URI: " + uri); + } + throw new IllegalArgumentException("Unknown URI: " + uri); + } + } + + if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) { + if (!emptyWhere) { + qb.appendWhere(" AND "); + } + qb.appendWhere("( " + Constants.UID + "=" + Binder.getCallingUid() + " OR " + + Downloads.OTHER_UID + "=" + Binder.getCallingUid() + " )"); + emptyWhere = false; + + if (projection == null) { + projection = sAppReadableColumnsArray; + } else { + for (int i = 0; i < projection.length; ++i) { + if (!sAppReadableColumnsSet.contains(projection[i])) { + throw new IllegalArgumentException( + "column " + projection[i] + " is not allowed in queries"); + } + } + } + } + + if (Constants.LOGVV) { + java.lang.StringBuilder sb = new java.lang.StringBuilder(); + sb.append("starting query, database is "); + if (db != null) { + sb.append("not "); + } + sb.append("null; "); + if (projection == null) { + sb.append("projection is null; "); + } else if (projection.length == 0) { + sb.append("projection is empty; "); + } else { + for (int i = 0; i < projection.length; ++i) { + sb.append("projection["); + sb.append(i); + sb.append("] is "); + sb.append(projection[i]); + sb.append("; "); + } + } + sb.append("selection is "); + sb.append(selection); + sb.append("; "); + if (selectionArgs == null) { + sb.append("selectionArgs is null; "); + } else if (selectionArgs.length == 0) { + sb.append("selectionArgs is empty; "); + } else { + for (int i = 0; i < selectionArgs.length; ++i) { + sb.append("selectionArgs["); + sb.append(i); + sb.append("] is "); + sb.append(selectionArgs[i]); + sb.append("; "); + } + } + sb.append("sort is "); + sb.append(sort); + sb.append("."); + Log.v(Constants.TAG, sb.toString()); + } + + Cursor ret = qb.query(db, projection, selection, selectionArgs, + null, null, sort); + + if (ret != null) { + ret = new ReadOnlyCursorWrapper(ret); + } + + if (ret != null) { + ret.setNotificationUri(getContext().getContentResolver(), uri); + if (Constants.LOGVV) { + Log.v(Constants.TAG, + "created cursor " + ret + " on behalf of " + Binder.getCallingPid()); + } + } else { + if (Constants.LOGV) { + Log.v(Constants.TAG, "query failed in downloads database"); + } + } + + return ret; + } + + /** + * Updates a row in the database + */ + @Override + public int update(final Uri uri, final ContentValues values, + final String where, final String[] whereArgs) { + + Helpers.validateSelection(where, sAppReadableColumnsSet); + + SQLiteDatabase db = mOpenHelper.getWritableDatabase(); + + int count; + long rowId = 0; + boolean startService = false; + + ContentValues filteredValues; + if (Binder.getCallingPid() != Process.myPid()) { + filteredValues = new ContentValues(); + copyString(Downloads.APP_DATA, values, filteredValues); + copyInteger(Downloads.VISIBILITY, values, filteredValues); + Integer i = values.getAsInteger(Downloads.CONTROL); + if (i != null) { + filteredValues.put(Downloads.CONTROL, i); + startService = true; + } + copyInteger(Downloads.CONTROL, values, filteredValues); + copyString(Downloads.TITLE, values, filteredValues); + copyString(Downloads.DESCRIPTION, values, filteredValues); + } else { + filteredValues = values; + } + int match = sURIMatcher.match(uri); + switch (match) { + case DOWNLOADS: + case DOWNLOADS_ID: { + String myWhere; + if (where != null) { + if (match == DOWNLOADS) { + myWhere = "( " + where + " )"; + } else { + myWhere = "( " + where + " ) AND "; + } + } else { + myWhere = ""; + } + if (match == DOWNLOADS_ID) { + String segment = uri.getPathSegments().get(1); + rowId = Long.parseLong(segment); + myWhere += " ( " + Downloads._ID + " = " + rowId + " ) "; + } + if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) { + myWhere += " AND ( " + Constants.UID + "=" + Binder.getCallingUid() + " OR " + + Downloads.OTHER_UID + "=" + Binder.getCallingUid() + " )"; + } + if (filteredValues.size() > 0) { + count = db.update(DB_TABLE, filteredValues, myWhere, whereArgs); + } else { + count = 0; + } + break; + } + default: { + if (Config.LOGD) { + Log.d(Constants.TAG, "updating unknown/invalid URI: " + uri); + } + throw new UnsupportedOperationException("Cannot update URI: " + uri); + } + } + getContext().getContentResolver().notifyChange(uri, null); + if (startService) { + Context context = getContext(); + context.startService(new Intent(context, DownloadService.class)); + } + return count; + } + + /** + * Deletes a row in the database + */ + @Override + public int delete(final Uri uri, final String where, + final String[] whereArgs) { + + Helpers.validateSelection(where, sAppReadableColumnsSet); + + SQLiteDatabase db = mOpenHelper.getWritableDatabase(); + int count; + int match = sURIMatcher.match(uri); + switch (match) { + case DOWNLOADS: + case DOWNLOADS_ID: { + String myWhere; + if (where != null) { + if (match == DOWNLOADS) { + myWhere = "( " + where + " )"; + } else { + myWhere = "( " + where + " ) AND "; + } + } else { + myWhere = ""; + } + if (match == DOWNLOADS_ID) { + String segment = uri.getPathSegments().get(1); + long rowId = Long.parseLong(segment); + myWhere += " ( " + Downloads._ID + " = " + rowId + " ) "; + } + if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) { + myWhere += " AND ( " + Constants.UID + "=" + Binder.getCallingUid() + " OR " + + Downloads.OTHER_UID + "=" + Binder.getCallingUid() + " )"; + } + count = db.delete(DB_TABLE, myWhere, whereArgs); + break; + } + default: { + if (Config.LOGD) { + Log.d(Constants.TAG, "deleting unknown/invalid URI: " + uri); + } + throw new UnsupportedOperationException("Cannot delete URI: " + uri); + } + } + getContext().getContentResolver().notifyChange(uri, null); + return count; + } + + /** + * Remotely opens a file + */ + @Override + public ParcelFileDescriptor openFile(Uri uri, String mode) + throws FileNotFoundException { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "openFile uri: " + uri + ", mode: " + mode + + ", uid: " + Binder.getCallingUid()); + Cursor cursor = query(Downloads.CONTENT_URI, new String[] { "_id" }, null, null, "_id"); + if (cursor == null) { + Log.v(Constants.TAG, "null cursor in openFile"); + } else { + if (!cursor.moveToFirst()) { + Log.v(Constants.TAG, "empty cursor in openFile"); + } else { + do { + Log.v(Constants.TAG, "row " + cursor.getInt(0) + " available"); + } while(cursor.moveToNext()); + } + cursor.close(); + } + cursor = query(uri, new String[] { "_data" }, null, null, null); + if (cursor == null) { + Log.v(Constants.TAG, "null cursor in openFile"); + } else { + if (!cursor.moveToFirst()) { + Log.v(Constants.TAG, "empty cursor in openFile"); + } else { + String filename = cursor.getString(0); + Log.v(Constants.TAG, "filename in openFile: " + filename); + if (new java.io.File(filename).isFile()) { + Log.v(Constants.TAG, "file exists in openFile"); + } + } + cursor.close(); + } + } + + // This logic is mostly copied form openFileHelper. If openFileHelper eventually + // gets split into small bits (to extract the filename and the modebits), + // this code could use the separate bits and be deeply simplified. + Cursor c = query(uri, new String[]{"_data"}, null, null, null); + int count = (c != null) ? c.getCount() : 0; + if (count != 1) { + // If there is not exactly one result, throw an appropriate exception. + if (c != null) { + c.close(); + } + if (count == 0) { + throw new FileNotFoundException("No entry for " + uri); + } + throw new FileNotFoundException("Multiple items at " + uri); + } + + c.moveToFirst(); + String path = c.getString(0); + c.close(); + if (path == null) { + throw new FileNotFoundException("No filename found."); + } + if (!Helpers.isFilenameValid(path)) { + throw new FileNotFoundException("Invalid filename."); + } + + if (!"r".equals(mode)) { + throw new FileNotFoundException("Bad mode for " + uri + ": " + mode); + } + ParcelFileDescriptor ret = ParcelFileDescriptor.open(new File(path), + ParcelFileDescriptor.MODE_READ_ONLY); + + if (ret == null) { + if (Constants.LOGV) { + Log.v(Constants.TAG, "couldn't open file"); + } + throw new FileNotFoundException("couldn't open file"); + } else { + ContentValues values = new ContentValues(); + values.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis()); + update(uri, values, null, null); + } + return ret; + } + + private static final void copyInteger(String key, ContentValues from, ContentValues to) { + Integer i = from.getAsInteger(key); + if (i != null) { + to.put(key, i); + } + } + + private static final void copyBoolean(String key, ContentValues from, ContentValues to) { + Boolean b = from.getAsBoolean(key); + if (b != null) { + to.put(key, b); + } + } + + private static final void copyString(String key, ContentValues from, ContentValues to) { + String s = from.getAsString(key); + if (s != null) { + to.put(key, s); + } + } + + private class ReadOnlyCursorWrapper extends CursorWrapper implements CrossProcessCursor { + public ReadOnlyCursorWrapper(Cursor cursor) { + super(cursor); + mCursor = (CrossProcessCursor) cursor; + } + + public boolean deleteRow() { + throw new SecurityException("Download manager cursors are read-only"); + } + + public boolean commitUpdates() { + throw new SecurityException("Download manager cursors are read-only"); + } + + public void fillWindow(int pos, CursorWindow window) { + mCursor.fillWindow(pos, window); + } + + public CursorWindow getWindow() { + return mCursor.getWindow(); + } + + public boolean onMove(int oldPosition, int newPosition) { + return mCursor.onMove(oldPosition, newPosition); + } + + private CrossProcessCursor mCursor; + } + +} diff --git a/src/com/android/providers/downloads/DownloadReceiver.java b/src/com/android/providers/downloads/DownloadReceiver.java new file mode 100644 index 00000000..03a37186 --- /dev/null +++ b/src/com/android/providers/downloads/DownloadReceiver.java @@ -0,0 +1,159 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.providers.downloads; + +import android.app.NotificationManager; +import android.content.ActivityNotFoundException; +import android.content.BroadcastReceiver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.database.Cursor; +import android.provider.Downloads; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.net.Uri; +import android.util.Config; +import android.util.Log; + +import java.io.File; +import java.util.List; + +/** + * Receives system broadcasts (boot, network connectivity) + */ +public class DownloadReceiver extends BroadcastReceiver { + + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Receiver onBoot"); + } + context.startService(new Intent(context, DownloadService.class)); + } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Receiver onConnectivity"); + } + NetworkInfo info = (NetworkInfo) + intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); + if (info != null && info.isConnected()) { + context.startService(new Intent(context, DownloadService.class)); + } + } else if (intent.getAction().equals(Constants.ACTION_RETRY)) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Receiver retry"); + } + context.startService(new Intent(context, DownloadService.class)); + } else if (intent.getAction().equals(Constants.ACTION_OPEN) + || intent.getAction().equals(Constants.ACTION_LIST)) { + if (Constants.LOGVV) { + if (intent.getAction().equals(Constants.ACTION_OPEN)) { + Log.v(Constants.TAG, "Receiver open for " + intent.getData()); + } else { + Log.v(Constants.TAG, "Receiver list for " + intent.getData()); + } + } + Cursor cursor = context.getContentResolver().query( + intent.getData(), null, null, null, null); + if (cursor != null) { + if (cursor.moveToFirst()) { + int statusColumn = cursor.getColumnIndexOrThrow(Downloads.STATUS); + int status = cursor.getInt(statusColumn); + int visibilityColumn = cursor.getColumnIndexOrThrow(Downloads.VISIBILITY); + int visibility = cursor.getInt(visibilityColumn); + if (Downloads.isStatusCompleted(status) + && visibility == Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) { + ContentValues values = new ContentValues(); + values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE); + context.getContentResolver().update(intent.getData(), values, null, null); + } + + if (intent.getAction().equals(Constants.ACTION_OPEN)) { + int filenameColumn = cursor.getColumnIndexOrThrow(Downloads._DATA); + int mimetypeColumn = cursor.getColumnIndexOrThrow(Downloads.MIMETYPE); + String filename = cursor.getString(filenameColumn); + String mimetype = cursor.getString(mimetypeColumn); + Uri path = Uri.parse(filename); + // If there is no scheme, then it must be a file + if (path.getScheme() == null) { + path = Uri.fromFile(new File(filename)); + } + Intent activityIntent = new Intent(Intent.ACTION_VIEW); + activityIntent.setDataAndType(path, mimetype); + activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + try { + context.startActivity(activityIntent); + } catch (ActivityNotFoundException ex) { + if (Config.LOGD) { + Log.d(Constants.TAG, "no activity for " + mimetype, ex); + } + // nothing anyone can do about this, but we're in a clean state, + // swallow the exception entirely + } + } else { + int packageColumn = + cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_PACKAGE); + int classColumn = + cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_CLASS); + String pckg = cursor.getString(packageColumn); + String clazz = cursor.getString(classColumn); + if (pckg != null && clazz != null) { + Intent appIntent = new Intent(Downloads.NOTIFICATION_CLICKED_ACTION); + appIntent.setClassName(pckg, clazz); + if (intent.getBooleanExtra("multiple", true)) { + appIntent.setData(Downloads.CONTENT_URI); + } else { + appIntent.setData(intent.getData()); + } + context.sendBroadcast(appIntent); + } + } + } + cursor.close(); + } + NotificationManager notMgr = (NotificationManager) context + .getSystemService(Context.NOTIFICATION_SERVICE); + if (notMgr != null) { + notMgr.cancel((int) ContentUris.parseId(intent.getData())); + } + } else if (intent.getAction().equals(Constants.ACTION_HIDE)) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Receiver hide for " + intent.getData()); + } + Cursor cursor = context.getContentResolver().query( + intent.getData(), null, null, null, null); + if (cursor != null) { + if (cursor.moveToFirst()) { + int statusColumn = cursor.getColumnIndexOrThrow(Downloads.STATUS); + int status = cursor.getInt(statusColumn); + int visibilityColumn = cursor.getColumnIndexOrThrow(Downloads.VISIBILITY); + int visibility = cursor.getInt(visibilityColumn); + if (Downloads.isStatusCompleted(status) + && visibility == Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) { + ContentValues values = new ContentValues(); + values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE); + context.getContentResolver().update(intent.getData(), values, null, null); + } + } + cursor.close(); + } + } + } +} diff --git a/src/com/android/providers/downloads/DownloadService.java b/src/com/android/providers/downloads/DownloadService.java new file mode 100644 index 00000000..0600cfb6 --- /dev/null +++ b/src/com/android/providers/downloads/DownloadService.java @@ -0,0 +1,879 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.providers.downloads; + +import com.google.android.collect.Lists; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.app.Service; +import android.content.ComponentName; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.content.ServiceConnection; +import android.database.ContentObserver; +import android.database.Cursor; +import android.database.CharArrayBuffer; +import android.drm.mobile1.DrmRawContent; +import android.media.IMediaScannerService; +import android.net.Uri; +import android.os.RemoteException; +import android.os.Environment; +import android.os.Handler; +import android.os.IBinder; +import android.os.Process; +import android.provider.Downloads; +import android.util.Config; +import android.util.Log; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; + + +/** + * Performs the background downloads requested by applications that use the Downloads provider. + */ +public class DownloadService extends Service { + + /* ------------ Constants ------------ */ + + /* ------------ Members ------------ */ + + /** Observer to get notified when the content observer's data changes */ + private DownloadManagerContentObserver mObserver; + + /** Class to handle Notification Manager updates */ + private DownloadNotification mNotifier; + + /** + * The Service's view of the list of downloads. This is kept independently + * from the content provider, and the Service only initiates downloads + * based on this data, so that it can deal with situation where the data + * in the content provider changes or disappears. + */ + private ArrayList mDownloads; + + /** + * The thread that updates the internal download list from the content + * provider. + */ + private UpdateThread updateThread; + + /** + * Whether the internal download list should be updated from the content + * provider. + */ + private boolean pendingUpdate; + + /** + * The ServiceConnection object that tells us when we're connected to and disconnected from + * the Media Scanner + */ + private MediaScannerConnection mMediaScannerConnection; + + private boolean mMediaScannerConnecting; + + /** + * The IPC interface to the Media Scanner + */ + private IMediaScannerService mMediaScannerService; + + /** + * Array used when extracting strings from content provider + */ + private CharArrayBuffer oldChars; + + /** + * Array used when extracting strings from content provider + */ + private CharArrayBuffer newChars; + + /* ------------ Inner Classes ------------ */ + + /** + * Receives notifications when the data in the content provider changes + */ + private class DownloadManagerContentObserver extends ContentObserver { + + public DownloadManagerContentObserver() { + super(new Handler()); + } + + /** + * Receives notification when the data in the observed content + * provider changes. + */ + public void onChange(final boolean selfChange) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Service ContentObserver received notification"); + } + updateFromProvider(); + } + + } + + /** + * Gets called back when the connection to the media + * scanner is established or lost. + */ + public class MediaScannerConnection implements ServiceConnection { + public void onServiceConnected(ComponentName className, IBinder service) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Connected to Media Scanner"); + } + mMediaScannerConnecting = false; + synchronized (DownloadService.this) { + mMediaScannerService = IMediaScannerService.Stub.asInterface(service); + if (mMediaScannerService != null) { + updateFromProvider(); + } + } + } + + public void disconnectMediaScanner() { + synchronized (DownloadService.this) { + if (mMediaScannerService != null) { + mMediaScannerService = null; + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Disconnecting from Media Scanner"); + } + try { + unbindService(this); + } catch (IllegalArgumentException ex) { + if (Constants.LOGV) { + Log.v(Constants.TAG, "unbindService threw up: " + ex); + } + } + } + } + } + + public void onServiceDisconnected(ComponentName className) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Disconnected from Media Scanner"); + } + synchronized (DownloadService.this) { + mMediaScannerService = null; + } + } + } + + /* ------------ Methods ------------ */ + + /** + * Returns an IBinder instance when someone wants to connect to this + * service. Binding to this service is not allowed. + * + * @throws UnsupportedOperationException + */ + public IBinder onBind(Intent i) { + throw new UnsupportedOperationException("Cannot bind to Download Manager Service"); + } + + /** + * Initializes the service when it is first created + */ + public void onCreate() { + super.onCreate(); + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Service onCreate"); + } + + mDownloads = Lists.newArrayList(); + + mObserver = new DownloadManagerContentObserver(); + getContentResolver().registerContentObserver(Downloads.CONTENT_URI, + true, mObserver); + + mMediaScannerService = null; + mMediaScannerConnecting = false; + mMediaScannerConnection = new MediaScannerConnection(); + + mNotifier = new DownloadNotification(this); + mNotifier.mNotificationMgr.cancelAll(); + mNotifier.updateNotification(); + + trimDatabase(); + removeSpuriousFiles(); + updateFromProvider(); + } + + /** + * Responds to a call to startService + */ + public void onStart(Intent intent, int startId) { + super.onStart(intent, startId); + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Service onStart"); + } + + updateFromProvider(); + } + + /** + * Cleans up when the service is destroyed + */ + public void onDestroy() { + getContentResolver().unregisterContentObserver(mObserver); + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Service onDestroy"); + } + super.onDestroy(); + } + + /** + * Parses data from the content provider into private array + */ + private void updateFromProvider() { + synchronized (this) { + pendingUpdate = true; + if (updateThread == null) { + updateThread = new UpdateThread(); + updateThread.start(); + } + } + } + + private class UpdateThread extends Thread { + public UpdateThread() { + super("Download Service"); + } + + public void run() { + Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + + boolean keepService = false; + // for each update from the database, remember which download is + // supposed to get restarted soonest in the future + long wakeUp = Long.MAX_VALUE; + for (;;) { + synchronized (DownloadService.this) { + if (updateThread != this) { + throw new IllegalStateException( + "multiple UpdateThreads in DownloadService"); + } + if (!pendingUpdate) { + updateThread = null; + if (!keepService) { + stopSelf(); + } + if (wakeUp != Long.MAX_VALUE) { + AlarmManager alarms = + (AlarmManager) getSystemService(Context.ALARM_SERVICE); + if (alarms == null) { + Log.e(Constants.TAG, "couldn't get alarm manager"); + } else { + if (Constants.LOGV) { + Log.v(Constants.TAG, "scheduling retry in " + wakeUp + "ms"); + } + Intent intent = new Intent(Constants.ACTION_RETRY); + intent.setClassName("com.android.providers.downloads", + DownloadReceiver.class.getName()); + alarms.set( + AlarmManager.RTC_WAKEUP, + System.currentTimeMillis() + wakeUp, + PendingIntent.getBroadcast(DownloadService.this, 0, intent, + PendingIntent.FLAG_ONE_SHOT)); + } + } + oldChars = null; + newChars = null; + return; + } + pendingUpdate = false; + } + boolean networkAvailable = Helpers.isNetworkAvailable(DownloadService.this); + boolean networkRoaming = Helpers.isNetworkRoaming(DownloadService.this); + long now = System.currentTimeMillis(); + + Cursor cursor = getContentResolver().query(Downloads.CONTENT_URI, + null, null, null, Downloads._ID); + + if (cursor == null) { + return; + } + + cursor.moveToFirst(); + + int arrayPos = 0; + + boolean mustScan = false; + keepService = false; + wakeUp = Long.MAX_VALUE; + + boolean isAfterLast = cursor.isAfterLast(); + + int idColumn = cursor.getColumnIndexOrThrow(Downloads._ID); + + /* + * Walk the cursor and the local array to keep them in sync. The key + * to the algorithm is that the ids are unique and sorted both in + * the cursor and in the array, so that they can be processed in + * order in both sources at the same time: at each step, both + * sources point to the lowest id that hasn't been processed from + * that source, and the algorithm processes the lowest id from + * those two possibilities. + * At each step: + * -If the array contains an entry that's not in the cursor, remove the + * entry, move to next entry in the array. + * -If the array contains an entry that's in the cursor, nothing to do, + * move to next cursor row and next array entry. + * -If the cursor contains an entry that's not in the array, insert + * a new entry in the array, move to next cursor row and next + * array entry. + */ + while (!isAfterLast || arrayPos < mDownloads.size()) { + if (isAfterLast) { + // We're beyond the end of the cursor but there's still some + // stuff in the local array, which can only be junk + if (Constants.LOGVV) { + int arrayId = ((DownloadInfo) mDownloads.get(arrayPos)).id; + Log.v(Constants.TAG, "Array update: trimming " + + arrayId + " @ " + arrayPos); + } + if (shouldScanFile(arrayPos) && mediaScannerConnected()) { + scanFile(null, arrayPos); + } + deleteDownload(arrayPos); // this advances in the array + } else { + int id = cursor.getInt(idColumn); + + if (arrayPos == mDownloads.size()) { + insertDownload(cursor, arrayPos, networkAvailable, networkRoaming, now); + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Array update: inserting " + + id + " @ " + arrayPos); + } + if (shouldScanFile(arrayPos) + && (!mediaScannerConnected() || !scanFile(cursor, arrayPos))) { + mustScan = true; + keepService = true; + } + if (visibleNotification(arrayPos)) { + keepService = true; + } + long next = nextAction(arrayPos, now); + if (next == 0) { + keepService = true; + } else if (next > 0 && next < wakeUp) { + wakeUp = next; + } + ++arrayPos; + cursor.moveToNext(); + isAfterLast = cursor.isAfterLast(); + } else { + int arrayId = mDownloads.get(arrayPos).id; + + if (arrayId < id) { + // The array entry isn't in the cursor + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Array update: removing " + arrayId + + " @ " + arrayPos); + } + if (shouldScanFile(arrayPos) && mediaScannerConnected()) { + scanFile(null, arrayPos); + } + deleteDownload(arrayPos); // this advances in the array + } else if (arrayId == id) { + // This cursor row already exists in the stored array + updateDownload( + cursor, arrayPos, + networkAvailable, networkRoaming, now); + if (shouldScanFile(arrayPos) + && (!mediaScannerConnected() + || !scanFile(cursor, arrayPos))) { + mustScan = true; + keepService = true; + } + if (visibleNotification(arrayPos)) { + keepService = true; + } + long next = nextAction(arrayPos, now); + if (next == 0) { + keepService = true; + } else if (next > 0 && next < wakeUp) { + wakeUp = next; + } + ++arrayPos; + cursor.moveToNext(); + isAfterLast = cursor.isAfterLast(); + } else { + // This cursor entry didn't exist in the stored array + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Array update: appending " + + id + " @ " + arrayPos); + } + insertDownload( + cursor, arrayPos, + networkAvailable, networkRoaming, now); + if (shouldScanFile(arrayPos) + && (!mediaScannerConnected() + || !scanFile(cursor, arrayPos))) { + mustScan = true; + keepService = true; + } + if (visibleNotification(arrayPos)) { + keepService = true; + } + long next = nextAction(arrayPos, now); + if (next == 0) { + keepService = true; + } else if (next > 0 && next < wakeUp) { + wakeUp = next; + } + ++arrayPos; + cursor.moveToNext(); + isAfterLast = cursor.isAfterLast(); + } + } + } + } + + mNotifier.updateNotification(); + + if (mustScan) { + if (!mMediaScannerConnecting) { + Intent intent = new Intent(); + intent.setClassName("com.android.providers.media", + "com.android.providers.media.MediaScannerService"); + mMediaScannerConnecting = true; + bindService(intent, mMediaScannerConnection, BIND_AUTO_CREATE); + } + } else { + mMediaScannerConnection.disconnectMediaScanner(); + } + + cursor.close(); + } + } + } + + /** + * Removes files that may have been left behind in the cache directory + */ + private void removeSpuriousFiles() { + File[] files = Environment.getDownloadCacheDirectory().listFiles(); + if (files == null) { + // The cache folder doesn't appear to exist (this is likely the case + // when running the simulator). + return; + } + HashSet fileSet = new HashSet(); + for (int i = 0; i < files.length; i++) { + if (files[i].getName().equals(Constants.KNOWN_SPURIOUS_FILENAME)) { + continue; + } + if (files[i].getName().equalsIgnoreCase(Constants.RECOVERY_DIRECTORY)) { + continue; + } + fileSet.add(files[i].getPath()); + } + + Cursor cursor = getContentResolver().query(Downloads.CONTENT_URI, + new String[] { Downloads._DATA }, null, null, null); + if (cursor != null) { + if (cursor.moveToFirst()) { + do { + fileSet.remove(cursor.getString(0)); + } while (cursor.moveToNext()); + } + cursor.close(); + } + Iterator iterator = fileSet.iterator(); + while (iterator.hasNext()) { + String filename = iterator.next(); + if (Constants.LOGV) { + Log.v(Constants.TAG, "deleting spurious file " + filename); + } + new File(filename).delete(); + } + } + + /** + * Drops old rows from the database to prevent it from growing too large + */ + private void trimDatabase() { + Cursor cursor = getContentResolver().query(Downloads.CONTENT_URI, + new String[] { Downloads._ID }, + Downloads.STATUS + " >= '200'", null, + Downloads.LAST_MODIFICATION); + if (cursor == null) { + // This isn't good - if we can't do basic queries in our database, nothing's gonna work + Log.e(Constants.TAG, "null cursor in trimDatabase"); + return; + } + if (cursor.moveToFirst()) { + int numDelete = cursor.getCount() - Constants.MAX_DOWNLOADS; + int columnId = cursor.getColumnIndexOrThrow(Downloads._ID); + while (numDelete > 0) { + getContentResolver().delete( + ContentUris.withAppendedId(Downloads.CONTENT_URI, cursor.getLong(columnId)), + null, null); + if (!cursor.moveToNext()) { + break; + } + numDelete--; + } + } + cursor.close(); + } + + /** + * Keeps a local copy of the info about a download, and initiates the + * download if appropriate. + */ + private void insertDownload( + Cursor cursor, int arrayPos, + boolean networkAvailable, boolean networkRoaming, long now) { + int statusColumn = cursor.getColumnIndexOrThrow(Downloads.STATUS); + int failedColumn = cursor.getColumnIndexOrThrow(Constants.FAILED_CONNECTIONS); + int retryRedirect = + cursor.getInt(cursor.getColumnIndexOrThrow(Constants.RETRY_AFTER___REDIRECT_COUNT)); + DownloadInfo info = new DownloadInfo( + cursor.getInt(cursor.getColumnIndexOrThrow(Downloads._ID)), + cursor.getString(cursor.getColumnIndexOrThrow(Downloads.URI)), + cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.NO_INTEGRITY)) == 1, + cursor.getString(cursor.getColumnIndexOrThrow(Downloads.FILENAME_HINT)), + cursor.getString(cursor.getColumnIndexOrThrow(Downloads._DATA)), + cursor.getString(cursor.getColumnIndexOrThrow(Downloads.MIMETYPE)), + cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.DESTINATION)), + cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.VISIBILITY)), + cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.CONTROL)), + cursor.getInt(statusColumn), + cursor.getInt(failedColumn), + retryRedirect & 0xfffffff, + retryRedirect >> 28, + cursor.getLong(cursor.getColumnIndexOrThrow(Downloads.LAST_MODIFICATION)), + cursor.getString(cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_PACKAGE)), + cursor.getString(cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_CLASS)), + cursor.getString(cursor.getColumnIndexOrThrow(Downloads.NOTIFICATION_EXTRAS)), + cursor.getString(cursor.getColumnIndexOrThrow(Downloads.COOKIE_DATA)), + cursor.getString(cursor.getColumnIndexOrThrow(Downloads.USER_AGENT)), + cursor.getString(cursor.getColumnIndexOrThrow(Downloads.REFERER)), + cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.TOTAL_BYTES)), + cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.CURRENT_BYTES)), + cursor.getString(cursor.getColumnIndexOrThrow(Constants.ETAG)), + cursor.getInt(cursor.getColumnIndexOrThrow(Constants.MEDIA_SCANNED)) == 1); + + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Service adding new entry"); + Log.v(Constants.TAG, "ID : " + info.id); + Log.v(Constants.TAG, "URI : " + ((info.uri != null) ? "yes" : "no")); + Log.v(Constants.TAG, "NO_INTEG: " + info.noIntegrity); + Log.v(Constants.TAG, "HINT : " + info.hint); + Log.v(Constants.TAG, "FILENAME: " + info.filename); + Log.v(Constants.TAG, "MIMETYPE: " + info.mimetype); + Log.v(Constants.TAG, "DESTINAT: " + info.destination); + Log.v(Constants.TAG, "VISIBILI: " + info.visibility); + Log.v(Constants.TAG, "CONTROL : " + info.control); + Log.v(Constants.TAG, "STATUS : " + info.status); + Log.v(Constants.TAG, "FAILED_C: " + info.numFailed); + Log.v(Constants.TAG, "RETRY_AF: " + info.retryAfter); + Log.v(Constants.TAG, "REDIRECT: " + info.redirectCount); + Log.v(Constants.TAG, "LAST_MOD: " + info.lastMod); + Log.v(Constants.TAG, "PACKAGE : " + info.pckg); + Log.v(Constants.TAG, "CLASS : " + info.clazz); + Log.v(Constants.TAG, "COOKIES : " + ((info.cookies != null) ? "yes" : "no")); + Log.v(Constants.TAG, "AGENT : " + info.userAgent); + Log.v(Constants.TAG, "REFERER : " + ((info.referer != null) ? "yes" : "no")); + Log.v(Constants.TAG, "TOTAL : " + info.totalBytes); + Log.v(Constants.TAG, "CURRENT : " + info.currentBytes); + Log.v(Constants.TAG, "ETAG : " + info.etag); + Log.v(Constants.TAG, "SCANNED : " + info.mediaScanned); + } + + mDownloads.add(arrayPos, info); + + if (info.status == 0 + && (info.destination == Downloads.DESTINATION_EXTERNAL + || info.destination == Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE) + && info.mimetype != null + && !DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(info.mimetype)) { + // Check to see if we are allowed to download this file. Only files + // that can be handled by the platform can be downloaded. + // special case DRM files, which we should always allow downloading. + Intent mimetypeIntent = new Intent(Intent.ACTION_VIEW); + + // We can provide data as either content: or file: URIs, + // so allow both. (I think it would be nice if we just did + // everything as content: URIs) + // Actually, right now the download manager's UId restrictions + // prevent use from using content: so it's got to be file: or + // nothing + + mimetypeIntent.setDataAndType(Uri.fromParts("file", "", null), info.mimetype); + ResolveInfo ri = getPackageManager().resolveActivity(mimetypeIntent, + PackageManager.MATCH_DEFAULT_ONLY); + //Log.i(Constants.TAG, "*** QUERY " + mimetypeIntent + ": " + list); + + if (ri == null) { + if (Config.LOGD) { + Log.d(Constants.TAG, "no application to handle MIME type " + info.mimetype); + } + info.status = Downloads.STATUS_NOT_ACCEPTABLE; + + Uri uri = ContentUris.withAppendedId(Downloads.CONTENT_URI, info.id); + ContentValues values = new ContentValues(); + values.put(Downloads.STATUS, Downloads.STATUS_NOT_ACCEPTABLE); + getContentResolver().update(uri, values, null, null); + info.sendIntentIfRequested(uri, this); + return; + } + } + + if (info.canUseNetwork(networkAvailable, networkRoaming)) { + if (info.isReadyToStart(now)) { + if (Constants.LOGV) { + Log.v(Constants.TAG, "Service spawning thread to handle new download " + + info.id); + } + if (info.hasActiveThread) { + throw new IllegalStateException("Multiple threads on same download on insert"); + } + if (info.status != Downloads.STATUS_RUNNING) { + info.status = Downloads.STATUS_RUNNING; + ContentValues values = new ContentValues(); + values.put(Downloads.STATUS, info.status); + getContentResolver().update( + ContentUris.withAppendedId(Downloads.CONTENT_URI, info.id), + values, null, null); + } + DownloadThread downloader = new DownloadThread(this, info); + info.hasActiveThread = true; + downloader.start(); + } + } else { + if (info.status == 0 + || info.status == Downloads.STATUS_PENDING + || info.status == Downloads.STATUS_RUNNING) { + info.status = Downloads.STATUS_RUNNING_PAUSED; + Uri uri = ContentUris.withAppendedId(Downloads.CONTENT_URI, info.id); + ContentValues values = new ContentValues(); + values.put(Downloads.STATUS, Downloads.STATUS_RUNNING_PAUSED); + getContentResolver().update(uri, values, null, null); + } + } + } + + /** + * Updates the local copy of the info about a download. + */ + private void updateDownload( + Cursor cursor, int arrayPos, + boolean networkAvailable, boolean networkRoaming, long now) { + DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); + int statusColumn = cursor.getColumnIndexOrThrow(Downloads.STATUS); + int failedColumn = cursor.getColumnIndexOrThrow(Constants.FAILED_CONNECTIONS); + info.id = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads._ID)); + info.uri = stringFromCursor(info.uri, cursor, Downloads.URI); + info.noIntegrity = + cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.NO_INTEGRITY)) == 1; + info.hint = stringFromCursor(info.hint, cursor, Downloads.FILENAME_HINT); + info.filename = stringFromCursor(info.filename, cursor, Downloads._DATA); + info.mimetype = stringFromCursor(info.mimetype, cursor, Downloads.MIMETYPE); + info.destination = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.DESTINATION)); + int newVisibility = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.VISIBILITY)); + if (info.visibility == Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED + && newVisibility != Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED + && Downloads.isStatusCompleted(info.status)) { + mNotifier.mNotificationMgr.cancel(info.id); + } + info.visibility = newVisibility; + synchronized(info) { + info.control = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.CONTROL)); + } + int newStatus = cursor.getInt(statusColumn); + if (!Downloads.isStatusCompleted(info.status) && Downloads.isStatusCompleted(newStatus)) { + mNotifier.mNotificationMgr.cancel(info.id); + } + info.status = newStatus; + info.numFailed = cursor.getInt(failedColumn); + int retryRedirect = + cursor.getInt(cursor.getColumnIndexOrThrow(Constants.RETRY_AFTER___REDIRECT_COUNT)); + info.retryAfter = retryRedirect & 0xfffffff; + info.redirectCount = retryRedirect >> 28; + info.lastMod = cursor.getLong(cursor.getColumnIndexOrThrow(Downloads.LAST_MODIFICATION)); + info.pckg = stringFromCursor(info.pckg, cursor, Downloads.NOTIFICATION_PACKAGE); + info.clazz = stringFromCursor(info.clazz, cursor, Downloads.NOTIFICATION_CLASS); + info.cookies = stringFromCursor(info.cookies, cursor, Downloads.COOKIE_DATA); + info.userAgent = stringFromCursor(info.userAgent, cursor, Downloads.USER_AGENT); + info.referer = stringFromCursor(info.referer, cursor, Downloads.REFERER); + info.totalBytes = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.TOTAL_BYTES)); + info.currentBytes = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.CURRENT_BYTES)); + info.etag = stringFromCursor(info.etag, cursor, Constants.ETAG); + info.mediaScanned = + cursor.getInt(cursor.getColumnIndexOrThrow(Constants.MEDIA_SCANNED)) == 1; + + if (info.canUseNetwork(networkAvailable, networkRoaming)) { + if (info.isReadyToRestart(now)) { + if (Constants.LOGV) { + Log.v(Constants.TAG, "Service spawning thread to handle updated download " + + info.id); + } + if (info.hasActiveThread) { + throw new IllegalStateException("Multiple threads on same download on update"); + } + info.status = Downloads.STATUS_RUNNING; + ContentValues values = new ContentValues(); + values.put(Downloads.STATUS, info.status); + getContentResolver().update( + ContentUris.withAppendedId(Downloads.CONTENT_URI, info.id), + values, null, null); + DownloadThread downloader = new DownloadThread(this, info); + info.hasActiveThread = true; + downloader.start(); + } + } + } + + /** + * Returns a String that holds the current value of the column, + * optimizing for the case where the value hasn't changed. + */ + private String stringFromCursor(String old, Cursor cursor, String column) { + int index = cursor.getColumnIndexOrThrow(column); + if (old == null) { + return cursor.getString(index); + } + if (newChars == null) { + newChars = new CharArrayBuffer(128); + } + cursor.copyStringToBuffer(index, newChars); + int length = newChars.sizeCopied; + if (length != old.length()) { + return cursor.getString(index); + } + if (oldChars == null || oldChars.sizeCopied < length) { + oldChars = new CharArrayBuffer(length); + } + char[] oldArray = oldChars.data; + char[] newArray = newChars.data; + old.getChars(0, length, oldArray, 0); + for (int i = length - 1; i >= 0; --i) { + if (oldArray[i] != newArray[i]) { + return new String(newArray, 0, length); + } + } + return old; + } + + /** + * Removes the local copy of the info about a download. + */ + private void deleteDownload(int arrayPos) { + DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); + if (info.status == Downloads.STATUS_RUNNING) { + info.status = Downloads.STATUS_CANCELED; + } else if (info.destination != Downloads.DESTINATION_EXTERNAL && info.filename != null) { + new File(info.filename).delete(); + } + mNotifier.mNotificationMgr.cancel(info.id); + + mDownloads.remove(arrayPos); + } + + /** + * Returns the amount of time (as measured from the "now" parameter) + * at which a download will be active. + * 0 = immediately - service should stick around to handle this download. + * -1 = never - service can go away without ever waking up. + * positive value - service must wake up in the future, as specified in ms from "now" + */ + private long nextAction(int arrayPos, long now) { + DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); + if (Downloads.isStatusCompleted(info.status)) { + return -1; + } + if (info.status != Downloads.STATUS_RUNNING_PAUSED) { + return 0; + } + if (info.numFailed == 0) { + return 0; + } + long when = info.restartTime(); + if (when <= now) { + return 0; + } + return when - now; + } + + /** + * Returns whether there's a visible notification for this download + */ + private boolean visibleNotification(int arrayPos) { + DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); + return info.hasCompletionNotification(); + } + + /** + * Returns whether a file should be scanned + */ + private boolean shouldScanFile(int arrayPos) { + DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); + return !info.mediaScanned + && info.destination == Downloads.DESTINATION_EXTERNAL + && Downloads.isStatusSuccess(info.status) + && !DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(info.mimetype); + } + + /** + * Returns whether we have a live connection to the Media Scanner + */ + private boolean mediaScannerConnected() { + return mMediaScannerService != null; + } + + /** + * Attempts to scan the file if necessary. + * Returns true if the file has been properly scanned. + */ + private boolean scanFile(Cursor cursor, int arrayPos) { + DownloadInfo info = (DownloadInfo) mDownloads.get(arrayPos); + synchronized (this) { + if (mMediaScannerService != null) { + try { + if (Constants.LOGV) { + Log.v(Constants.TAG, "Scanning file " + info.filename); + } + mMediaScannerService.scanFile(info.filename, info.mimetype); + if (cursor != null) { + ContentValues values = new ContentValues(); + values.put(Constants.MEDIA_SCANNED, 1); + getContentResolver().update( + ContentUris.withAppendedId(Downloads.CONTENT_URI, + cursor.getLong(cursor.getColumnIndexOrThrow(Downloads._ID))), + values, null, null); + } + return true; + } catch (RemoteException e) { + if (Config.LOGD) { + Log.d(Constants.TAG, "Failed to scan file " + info.filename); + } + } + } + } + return false; + } + +} diff --git a/src/com/android/providers/downloads/DownloadThread.java b/src/com/android/providers/downloads/DownloadThread.java new file mode 100644 index 00000000..923e36d1 --- /dev/null +++ b/src/com/android/providers/downloads/DownloadThread.java @@ -0,0 +1,710 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.providers.downloads; + +import org.apache.http.client.methods.AbortableHttpRequest; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.HttpClient; +import org.apache.http.entity.StringEntity; +import org.apache.http.Header; +import org.apache.http.HttpResponse; + +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.drm.mobile1.DrmRawContent; +import android.net.http.AndroidHttpClient; +import android.net.Uri; +import android.os.FileUtils; +import android.os.PowerManager; +import android.os.Process; +import android.provider.Downloads; +import android.provider.DrmStore; +import android.util.Config; +import android.util.Log; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URI; + +/** + * Runs an actual download + */ +public class DownloadThread extends Thread { + + private Context mContext; + private DownloadInfo mInfo; + + public DownloadThread(Context context, DownloadInfo info) { + mContext = context; + mInfo = info; + } + + /** + * Returns the user agent provided by the initiating app, or use the default one + */ + private String userAgent() { + String userAgent = mInfo.userAgent; + if (userAgent != null) { + } + if (userAgent == null) { + userAgent = Constants.DEFAULT_USER_AGENT; + } + return userAgent; + } + + /** + * Executes the download in a separate thread + */ + public void run() { + Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + + int finalStatus = Downloads.STATUS_UNKNOWN_ERROR; + boolean countRetry = false; + int retryAfter = 0; + int redirectCount = mInfo.redirectCount; + String newUri = null; + boolean gotData = false; + String filename = null; + String mimeType = mInfo.mimetype; + FileOutputStream stream = null; + AndroidHttpClient client = null; + PowerManager.WakeLock wakeLock = null; + Uri contentUri = Uri.parse(Downloads.CONTENT_URI + "/" + mInfo.id); + + try { + boolean continuingDownload = false; + String headerAcceptRanges = null; + String headerContentDisposition = null; + String headerContentLength = null; + String headerContentLocation = null; + String headerETag = null; + String headerTransferEncoding = null; + + byte data[] = new byte[Constants.BUFFER_SIZE]; + + int bytesSoFar = 0; + + PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); + wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); + wakeLock.acquire(); + + filename = mInfo.filename; + if (filename != null) { + if (!Helpers.isFilenameValid(filename)) { + finalStatus = Downloads.STATUS_FILE_ERROR; + notifyDownloadCompleted( + finalStatus, false, 0, 0, false, filename, null, mInfo.mimetype); + return; + } + // We're resuming a download that got interrupted + File f = new File(filename); + if (f.exists()) { + long fileLength = f.length(); + if (fileLength == 0) { + // The download hadn't actually started, we can restart from scratch + f.delete(); + filename = null; + } else if (mInfo.etag == null && !mInfo.noIntegrity) { + // Tough luck, that's not a resumable download + if (Config.LOGD) { + Log.d(Constants.TAG, + "can't resume interrupted non-resumable download"); + } + f.delete(); + finalStatus = Downloads.STATUS_PRECONDITION_FAILED; + notifyDownloadCompleted( + finalStatus, false, 0, 0, false, filename, null, mInfo.mimetype); + return; + } else { + // All right, we'll be able to resume this download + stream = new FileOutputStream(filename, true); + bytesSoFar = (int) fileLength; + if (mInfo.totalBytes != -1) { + headerContentLength = Integer.toString(mInfo.totalBytes); + } + headerETag = mInfo.etag; + continuingDownload = true; + } + } + } + + int bytesNotified = bytesSoFar; + // starting with MIN_VALUE means that the first write will commit + // progress to the database + long timeLastNotification = 0; + + client = AndroidHttpClient.newInstance(userAgent()); + + if (stream != null && mInfo.destination == Downloads.DESTINATION_EXTERNAL + && !DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING + .equalsIgnoreCase(mimeType)) { + try { + stream.close(); + stream = null; + } catch (IOException ex) { + if (Constants.LOGV) { + Log.v(Constants.TAG, "exception when closing the file before download : " + + ex); + } + // nothing can really be done if the file can't be closed + } + } + + /* + * This loop is run once for every individual HTTP request that gets sent. + * The very first HTTP request is a "virgin" request, while every subsequent + * request is done with the original ETag and a byte-range. + */ +http_request_loop: + while (true) { + // Prepares the request and fires it. + HttpGet request = new HttpGet(mInfo.uri); + + if (Constants.LOGV) { + Log.v(Constants.TAG, "initiating download for " + mInfo.uri); + } + + if (mInfo.cookies != null) { + request.addHeader("Cookie", mInfo.cookies); + } + if (mInfo.referer != null) { + request.addHeader("Referer", mInfo.referer); + } + if (continuingDownload) { + if (headerETag != null) { + request.addHeader("If-Match", headerETag); + } + request.addHeader("Range", "bytes=" + bytesSoFar + "-"); + } + + HttpResponse response; + try { + response = client.execute(request); + } catch (IllegalArgumentException ex) { + if (Constants.LOGV) { + Log.d(Constants.TAG, "Arg exception trying to execute request for " + + mInfo.uri + " : " + ex); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "Arg exception trying to execute request for " + + mInfo.id + " : " + ex); + } + finalStatus = Downloads.STATUS_BAD_REQUEST; + request.abort(); + break http_request_loop; + } catch (IOException ex) { + if (!Helpers.isNetworkAvailable(mContext)) { + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + } else if (mInfo.numFailed < Constants.MAX_RETRIES) { + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + countRetry = true; + } else { + if (Constants.LOGV) { + Log.d(Constants.TAG, "IOException trying to execute request for " + + mInfo.uri + " : " + ex); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "IOException trying to execute request for " + + mInfo.id + " : " + ex); + } + finalStatus = Downloads.STATUS_HTTP_DATA_ERROR; + } + request.abort(); + break http_request_loop; + } + + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode == 503 && mInfo.numFailed < Constants.MAX_RETRIES) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "got HTTP response code 503"); + } + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + countRetry = true; + Header header = response.getFirstHeader("Retry-After"); + if (header != null) { + try { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Retry-After :" + header.getValue()); + } + retryAfter = Integer.parseInt(header.getValue()); + if (retryAfter < 0) { + retryAfter = 0; + } else { + if (retryAfter < Constants.MIN_RETRY_AFTER) { + retryAfter = Constants.MIN_RETRY_AFTER; + } else if (retryAfter > Constants.MAX_RETRY_AFTER) { + retryAfter = Constants.MAX_RETRY_AFTER; + } + retryAfter += Helpers.rnd.nextInt(Constants.MIN_RETRY_AFTER + 1); + retryAfter *= 1000; + } + } catch (NumberFormatException ex) { + // ignored - retryAfter stays 0 in this case. + } + } + request.abort(); + break http_request_loop; + } + if (statusCode == 301 || + statusCode == 302 || + statusCode == 303 || + statusCode == 307) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "got HTTP redirect " + statusCode); + } + if (redirectCount >= Constants.MAX_REDIRECTS) { + if (Constants.LOGV) { + Log.d(Constants.TAG, "too many redirects for download " + mInfo.id + + " at " + mInfo.uri); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "too many redirects for download " + mInfo.id); + } + finalStatus = Downloads.STATUS_TOO_MANY_REDIRECTS; + request.abort(); + break http_request_loop; + } + Header header = response.getFirstHeader("Location"); + if (header != null) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Location :" + header.getValue()); + } + newUri = new URI(mInfo.uri).resolve(new URI(header.getValue())).toString(); + ++redirectCount; + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + request.abort(); + break http_request_loop; + } + } + if ((!continuingDownload && statusCode != Downloads.STATUS_SUCCESS) + || (continuingDownload && statusCode != 206)) { + if (Constants.LOGV) { + Log.d(Constants.TAG, "http error " + statusCode + " for " + mInfo.uri); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "http error " + statusCode + " for download " + + mInfo.id); + } + if (Downloads.isStatusError(statusCode)) { + finalStatus = statusCode; + } else if (statusCode >= 300 && statusCode < 400) { + finalStatus = Downloads.STATUS_UNHANDLED_REDIRECT; + } else if (continuingDownload && statusCode == Downloads.STATUS_SUCCESS) { + finalStatus = Downloads.STATUS_PRECONDITION_FAILED; + } else { + finalStatus = Downloads.STATUS_UNHANDLED_HTTP_CODE; + } + request.abort(); + break http_request_loop; + } else { + // Handles the response, saves the file + if (Constants.LOGV) { + Log.v(Constants.TAG, "received response for " + mInfo.uri); + } + + if (!continuingDownload) { + Header header = response.getFirstHeader("Accept-Ranges"); + if (header != null) { + headerAcceptRanges = header.getValue(); + } + header = response.getFirstHeader("Content-Disposition"); + if (header != null) { + headerContentDisposition = header.getValue(); + } + header = response.getFirstHeader("Content-Location"); + if (header != null) { + headerContentLocation = header.getValue(); + } + if (mimeType == null) { + header = response.getFirstHeader("Content-Type"); + if (header != null) { + mimeType = header.getValue(); + final int semicolonIndex = mimeType.indexOf(';'); + if (semicolonIndex != -1) { + mimeType = mimeType.substring(0, semicolonIndex); + } + } + } + header = response.getFirstHeader("ETag"); + if (header != null) { + headerETag = header.getValue(); + } + header = response.getFirstHeader("Transfer-Encoding"); + if (header != null) { + headerTransferEncoding = header.getValue(); + } + if (headerTransferEncoding == null) { + header = response.getFirstHeader("Content-Length"); + if (header != null) { + headerContentLength = header.getValue(); + } + } else { + // Ignore content-length with transfer-encoding - 2616 4.4 3 + if (Constants.LOGVV) { + Log.v(Constants.TAG, + "ignoring content-length because of xfer-encoding"); + } + } + if (Constants.LOGVV) { + Log.v(Constants.TAG, "Accept-Ranges: " + headerAcceptRanges); + Log.v(Constants.TAG, "Content-Disposition: " + + headerContentDisposition); + Log.v(Constants.TAG, "Content-Length: " + headerContentLength); + Log.v(Constants.TAG, "Content-Location: " + headerContentLocation); + Log.v(Constants.TAG, "Content-Type: " + mimeType); + Log.v(Constants.TAG, "ETag: " + headerETag); + Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding); + } + + if (!mInfo.noIntegrity && headerContentLength == null && + (headerTransferEncoding == null + || !headerTransferEncoding.equalsIgnoreCase("chunked")) + ) { + if (Config.LOGD) { + Log.d(Constants.TAG, "can't know size of download, giving up"); + } + finalStatus = Downloads.STATUS_LENGTH_REQUIRED; + request.abort(); + break http_request_loop; + } + + DownloadFileInfo fileInfo = Helpers.generateSaveFile( + mContext, + mInfo.uri, + mInfo.hint, + headerContentDisposition, + headerContentLocation, + mimeType, + mInfo.destination, + (headerContentLength != null) ? + Integer.parseInt(headerContentLength) : 0); + if (fileInfo.filename == null) { + finalStatus = fileInfo.status; + request.abort(); + break http_request_loop; + } + filename = fileInfo.filename; + stream = fileInfo.stream; + if (Constants.LOGV) { + Log.v(Constants.TAG, "writing " + mInfo.uri + " to " + filename); + } + + ContentValues values = new ContentValues(); + values.put(Downloads._DATA, filename); + if (headerETag != null) { + values.put(Constants.ETAG, headerETag); + } + if (mimeType != null) { + values.put(Downloads.MIMETYPE, mimeType); + } + int contentLength = -1; + if (headerContentLength != null) { + contentLength = Integer.parseInt(headerContentLength); + } + values.put(Downloads.TOTAL_BYTES, contentLength); + mContext.getContentResolver().update(contentUri, values, null, null); + } + + InputStream entityStream; + try { + entityStream = response.getEntity().getContent(); + } catch (IOException ex) { + if (!Helpers.isNetworkAvailable(mContext)) { + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + } else if (mInfo.numFailed < Constants.MAX_RETRIES) { + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + countRetry = true; + } else { + if (Constants.LOGV) { + Log.d(Constants.TAG, "IOException getting entity for " + mInfo.uri + + " : " + ex); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "IOException getting entity for download " + + mInfo.id + " : " + ex); + } + finalStatus = Downloads.STATUS_HTTP_DATA_ERROR; + } + request.abort(); + break http_request_loop; + } + for (;;) { + int bytesRead; + try { + bytesRead = entityStream.read(data); + } catch (IOException ex) { + ContentValues values = new ContentValues(); + values.put(Downloads.CURRENT_BYTES, bytesSoFar); + mContext.getContentResolver().update(contentUri, values, null, null); + if (!mInfo.noIntegrity && headerETag == null) { + if (Constants.LOGV) { + Log.v(Constants.TAG, "download IOException for " + mInfo.uri + + " : " + ex); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "download IOException for download " + + mInfo.id + " : " + ex); + } + if (Config.LOGD) { + Log.d(Constants.TAG, + "can't resume interrupted download with no ETag"); + } + finalStatus = Downloads.STATUS_PRECONDITION_FAILED; + } else if (!Helpers.isNetworkAvailable(mContext)) { + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + } else if (mInfo.numFailed < Constants.MAX_RETRIES) { + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + countRetry = true; + } else { + if (Constants.LOGV) { + Log.v(Constants.TAG, "download IOException for " + mInfo.uri + + " : " + ex); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "download IOException for download " + + mInfo.id + " : " + ex); + } + finalStatus = Downloads.STATUS_HTTP_DATA_ERROR; + } + request.abort(); + break http_request_loop; + } + if (bytesRead == -1) { // success + ContentValues values = new ContentValues(); + values.put(Downloads.CURRENT_BYTES, bytesSoFar); + if (headerContentLength == null) { + values.put(Downloads.TOTAL_BYTES, bytesSoFar); + } + mContext.getContentResolver().update(contentUri, values, null, null); + if ((headerContentLength != null) + && (bytesSoFar + != Integer.parseInt(headerContentLength))) { + if (!mInfo.noIntegrity && headerETag == null) { + if (Constants.LOGV) { + Log.d(Constants.TAG, "mismatched content length " + + mInfo.uri); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "mismatched content length for " + + mInfo.id); + } + finalStatus = Downloads.STATUS_LENGTH_REQUIRED; + } else if (!Helpers.isNetworkAvailable(mContext)) { + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + } else if (mInfo.numFailed < Constants.MAX_RETRIES) { + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + countRetry = true; + } else { + if (Constants.LOGV) { + Log.v(Constants.TAG, "closed socket for " + mInfo.uri); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "closed socket for download " + + mInfo.id); + } + finalStatus = Downloads.STATUS_HTTP_DATA_ERROR; + } + break http_request_loop; + } + break; + } + gotData = true; + for (;;) { + try { + if (stream == null) { + stream = new FileOutputStream(filename, true); + } + stream.write(data, 0, bytesRead); + if (mInfo.destination == Downloads.DESTINATION_EXTERNAL + && !DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING + .equalsIgnoreCase(mimeType)) { + try { + stream.close(); + stream = null; + } catch (IOException ex) { + if (Constants.LOGV) { + Log.v(Constants.TAG, + "exception when closing the file " + + "during download : " + ex); + } + // nothing can really be done if the file can't be closed + } + } + break; + } catch (IOException ex) { + if (!Helpers.discardPurgeableFiles( + mContext, Constants.BUFFER_SIZE)) { + finalStatus = Downloads.STATUS_FILE_ERROR; + break http_request_loop; + } + } + } + bytesSoFar += bytesRead; + long now = System.currentTimeMillis(); + if (bytesSoFar - bytesNotified > Constants.MIN_PROGRESS_STEP + && now - timeLastNotification + > Constants.MIN_PROGRESS_TIME) { + ContentValues values = new ContentValues(); + values.put(Downloads.CURRENT_BYTES, bytesSoFar); + mContext.getContentResolver().update( + contentUri, values, null, null); + bytesNotified = bytesSoFar; + timeLastNotification = now; + } + + if (Constants.LOGVV) { + Log.v(Constants.TAG, "downloaded " + bytesSoFar + " for " + mInfo.uri); + } + synchronized(mInfo) { + if (mInfo.control == Downloads.CONTROL_PAUSED) { + if (Constants.LOGV) { + Log.v(Constants.TAG, "paused " + mInfo.uri); + } + finalStatus = Downloads.STATUS_RUNNING_PAUSED; + request.abort(); + break http_request_loop; + } + } + if (mInfo.status == Downloads.STATUS_CANCELED) { + if (Constants.LOGV) { + Log.d(Constants.TAG, "canceled " + mInfo.uri); + } else if (Config.LOGD) { + // Log.d(Constants.TAG, "canceled id " + mInfo.id); + } + finalStatus = Downloads.STATUS_CANCELED; + break http_request_loop; + } + } + if (Constants.LOGV) { + Log.v(Constants.TAG, "download completed for " + mInfo.uri); + } + finalStatus = Downloads.STATUS_SUCCESS; + } + break; + } + } catch (FileNotFoundException ex) { + if (Config.LOGD) { + Log.d(Constants.TAG, "FileNotFoundException for " + filename + " : " + ex); + } + finalStatus = Downloads.STATUS_FILE_ERROR; + // falls through to the code that reports an error + } catch (Exception ex) { //sometimes the socket code throws unchecked exceptions + if (Constants.LOGV) { + Log.d(Constants.TAG, "Exception for " + mInfo.uri, ex); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "Exception for id " + mInfo.id, ex); + } + finalStatus = Downloads.STATUS_UNKNOWN_ERROR; + // falls through to the code that reports an error + } finally { + mInfo.hasActiveThread = false; + if (wakeLock != null) { + wakeLock.release(); + wakeLock = null; + } + if (client != null) { + client.close(); + client = null; + } + try { + // close the file + if (stream != null) { + stream.close(); + } + } catch (IOException ex) { + if (Constants.LOGV) { + Log.v(Constants.TAG, "exception when closing the file after download : " + ex); + } + // nothing can really be done if the file can't be closed + } + if (filename != null) { + // if the download wasn't successful, delete the file + if (Downloads.isStatusError(finalStatus)) { + new File(filename).delete(); + filename = null; + } else if (Downloads.isStatusSuccess(finalStatus) && + DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING + .equalsIgnoreCase(mimeType)) { + // transfer the file to the DRM content provider + File file = new File(filename); + Intent item = DrmStore.addDrmFile(mContext.getContentResolver(), file, null); + if (item == null) { + Log.w(Constants.TAG, "unable to add file " + filename + " to DrmProvider"); + finalStatus = Downloads.STATUS_UNKNOWN_ERROR; + } else { + filename = item.getDataString(); + mimeType = item.getType(); + } + + file.delete(); + } else if (Downloads.isStatusSuccess(finalStatus)) { + // make sure the file is readable + FileUtils.setPermissions(filename, 0644, -1, -1); + } + } + notifyDownloadCompleted(finalStatus, countRetry, retryAfter, redirectCount, + gotData, filename, newUri, mimeType); + } + } + + /** + * Stores information about the completed download, and notifies the initiating application. + */ + private void notifyDownloadCompleted( + int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData, + String filename, String uri, String mimeType) { + notifyThroughDatabase( + status, countRetry, retryAfter, redirectCount, gotData, filename, uri, mimeType); + if (Downloads.isStatusCompleted(status)) { + notifyThroughIntent(); + } + } + + private void notifyThroughDatabase( + int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData, + String filename, String uri, String mimeType) { + ContentValues values = new ContentValues(); + values.put(Downloads.STATUS, status); + values.put(Downloads._DATA, filename); + if (uri != null) { + values.put(Downloads.URI, uri); + } + values.put(Downloads.MIMETYPE, mimeType); + values.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis()); + values.put(Constants.RETRY_AFTER___REDIRECT_COUNT, retryAfter + (redirectCount << 28)); + if (!countRetry) { + values.put(Constants.FAILED_CONNECTIONS, 0); + } else if (gotData) { + values.put(Constants.FAILED_CONNECTIONS, 1); + } else { + values.put(Constants.FAILED_CONNECTIONS, mInfo.numFailed + 1); + } + + mContext.getContentResolver().update( + ContentUris.withAppendedId(Downloads.CONTENT_URI, mInfo.id), values, null, null); + } + + /** + * Notifies the initiating app if it requested it. That way, it can know that the + * download completed even if it's not actively watching the cursor. + */ + private void notifyThroughIntent() { + Uri uri = Uri.parse(Downloads.CONTENT_URI + "/" + mInfo.id); + mInfo.sendIntentIfRequested(uri, mContext); + } + +} diff --git a/src/com/android/providers/downloads/Helpers.java b/src/com/android/providers/downloads/Helpers.java new file mode 100644 index 00000000..7c6070f3 --- /dev/null +++ b/src/com/android/providers/downloads/Helpers.java @@ -0,0 +1,793 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.providers.downloads; + +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.database.Cursor; +import android.drm.mobile1.DrmRawContent; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.net.Uri; +import android.os.Environment; +import android.os.StatFs; +import android.os.SystemClock; +import android.provider.Downloads; +import android.telephony.TelephonyManager; +import android.util.Config; +import android.util.Log; +import android.webkit.MimeTypeMap; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.List; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.Set; + +/** + * Some helper functions for the download manager + */ +public class Helpers { + + public static Random rnd = new Random(SystemClock.uptimeMillis()); + + /** Regex used to parse content-disposition headers */ + private static final Pattern CONTENT_DISPOSITION_PATTERN = + Pattern.compile("attachment;\\s*filename\\s*=\\s*\"([^\"]*)\""); + + private Helpers() { + } + + /* + * Parse the Content-Disposition HTTP Header. The format of the header + * is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html + * This header provides a filename for content that is going to be + * downloaded to the file system. We only support the attachment type. + */ + private static String parseContentDisposition(String contentDisposition) { + try { + Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition); + if (m.find()) { + return m.group(1); + } + } catch (IllegalStateException ex) { + // This function is defined as returning null when it can't parse the header + } + return null; + } + + /** + * Creates a filename (where the file should be saved) from a uri. + */ + public static DownloadFileInfo generateSaveFile( + Context context, + String url, + String hint, + String contentDisposition, + String contentLocation, + String mimeType, + int destination, + int contentLength) throws FileNotFoundException { + + /* + * Don't download files that we won't be able to handle + */ + if (destination == Downloads.DESTINATION_EXTERNAL + || destination == Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE) { + if (mimeType == null) { + if (Config.LOGD) { + Log.d(Constants.TAG, "external download with no mime type not allowed"); + } + return new DownloadFileInfo(null, null, Downloads.STATUS_NOT_ACCEPTABLE); + } + if (!DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(mimeType)) { + // Check to see if we are allowed to download this file. Only files + // that can be handled by the platform can be downloaded. + // special case DRM files, which we should always allow downloading. + Intent intent = new Intent(Intent.ACTION_VIEW); + + // We can provide data as either content: or file: URIs, + // so allow both. (I think it would be nice if we just did + // everything as content: URIs) + // Actually, right now the download manager's UId restrictions + // prevent use from using content: so it's got to be file: or + // nothing + + PackageManager pm = context.getPackageManager(); + intent.setDataAndType(Uri.fromParts("file", "", null), mimeType); + ResolveInfo ri = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); + //Log.i(Constants.TAG, "*** FILENAME QUERY " + intent + ": " + list); + + if (ri == null) { + if (Config.LOGD) { + Log.d(Constants.TAG, "no handler found for type " + mimeType); + } + return new DownloadFileInfo(null, null, Downloads.STATUS_NOT_ACCEPTABLE); + } + } + } + String filename = chooseFilename( + url, hint, contentDisposition, contentLocation, destination); + + // Split filename between base and extension + // Add an extension if filename does not have one + String extension = null; + int dotIndex = filename.indexOf('.'); + if (dotIndex < 0) { + extension = chooseExtensionFromMimeType(mimeType, true); + } else { + extension = chooseExtensionFromFilename( + mimeType, destination, filename, dotIndex); + filename = filename.substring(0, dotIndex); + } + + /* + * Locate the directory where the file will be saved + */ + + File base = null; + StatFs stat = null; + // DRM messages should be temporarily stored internally and then passed to + // the DRM content provider + if (destination == Downloads.DESTINATION_CACHE_PARTITION + || destination == Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE + || destination == Downloads.DESTINATION_CACHE_PARTITION_NOROAMING + || DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(mimeType)) { + base = Environment.getDownloadCacheDirectory(); + stat = new StatFs(base.getPath()); + + /* + * Check whether there's enough space on the target filesystem to save the file. + * Put a bit of margin (in case creating the file grows the system by a few blocks). + */ + int blockSize = stat.getBlockSize(); + for (;;) { + int availableBlocks = stat.getAvailableBlocks(); + if (blockSize * ((long) availableBlocks - 4) >= contentLength) { + break; + } + if (!discardPurgeableFiles(context, + contentLength - blockSize * ((long) availableBlocks - 4))) { + if (Config.LOGD) { + Log.d(Constants.TAG, + "download aborted - not enough free space in internal storage"); + } + return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); + } + stat.restat(base.getPath()); + } + + } else { + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + String root = Environment.getExternalStorageDirectory().getPath(); + base = new File(root + Constants.DEFAULT_DL_SUBDIR); + if (!base.isDirectory() && !base.mkdir()) { + if (Config.LOGD) { + Log.d(Constants.TAG, "download aborted - can't create base directory " + + base.getPath()); + } + return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); + } + stat = new StatFs(base.getPath()); + } else { + if (Config.LOGD) { + Log.d(Constants.TAG, "download aborted - no external storage"); + } + return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); + } + + /* + * Check whether there's enough space on the target filesystem to save the file. + * Put a bit of margin (in case creating the file grows the system by a few blocks). + */ + if (stat.getBlockSize() * ((long) stat.getAvailableBlocks() - 4) < contentLength) { + if (Config.LOGD) { + Log.d(Constants.TAG, "download aborted - not enough free space"); + } + return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); + } + + } + + boolean recoveryDir = Constants.RECOVERY_DIRECTORY.equalsIgnoreCase(filename + extension); + + filename = base.getPath() + File.separator + filename; + + /* + * Generate a unique filename, create the file, return it. + */ + if (Constants.LOGVV) { + Log.v(Constants.TAG, "target file: " + filename + extension); + } + + String fullFilename = chooseUniqueFilename( + destination, filename, extension, recoveryDir); + if (fullFilename != null) { + return new DownloadFileInfo(fullFilename, new FileOutputStream(fullFilename), 0); + } else { + return new DownloadFileInfo(null, null, Downloads.STATUS_FILE_ERROR); + } + } + + private static String chooseFilename(String url, String hint, String contentDisposition, + String contentLocation, int destination) { + String filename = null; + + // First, try to use the hint from the application, if there's one + if (filename == null && hint != null && !hint.endsWith("/")) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "getting filename from hint"); + } + int index = hint.lastIndexOf('/') + 1; + if (index > 0) { + filename = hint.substring(index); + } else { + filename = hint; + } + } + + // If we couldn't do anything with the hint, move toward the content disposition + if (filename == null && contentDisposition != null) { + filename = parseContentDisposition(contentDisposition); + if (filename != null) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "getting filename from content-disposition"); + } + int index = filename.lastIndexOf('/') + 1; + if (index > 0) { + filename = filename.substring(index); + } + } + } + + // If we still have nothing at this point, try the content location + if (filename == null && contentLocation != null) { + String decodedContentLocation = Uri.decode(contentLocation); + if (decodedContentLocation != null + && !decodedContentLocation.endsWith("/") + && decodedContentLocation.indexOf('?') < 0) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "getting filename from content-location"); + } + int index = decodedContentLocation.lastIndexOf('/') + 1; + if (index > 0) { + filename = decodedContentLocation.substring(index); + } else { + filename = decodedContentLocation; + } + } + } + + // If all the other http-related approaches failed, use the plain uri + if (filename == null) { + String decodedUrl = Uri.decode(url); + if (decodedUrl != null + && !decodedUrl.endsWith("/") && decodedUrl.indexOf('?') < 0) { + int index = decodedUrl.lastIndexOf('/') + 1; + if (index > 0) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "getting filename from uri"); + } + filename = decodedUrl.substring(index); + } + } + } + + // Finally, if couldn't get filename from URI, get a generic filename + if (filename == null) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "using default filename"); + } + filename = Constants.DEFAULT_DL_FILENAME; + } + + filename = filename.replaceAll("[^a-zA-Z0-9\\.\\-_]+", "_"); + + + return filename; + } + + private static String chooseExtensionFromMimeType(String mimeType, boolean useDefaults) { + String extension = null; + if (mimeType != null) { + extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); + if (extension != null) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "adding extension from type"); + } + extension = "." + extension; + } else { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "couldn't find extension for " + mimeType); + } + } + } + if (extension == null) { + if (mimeType != null && mimeType.toLowerCase().startsWith("text/")) { + if (mimeType.equalsIgnoreCase("text/html")) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "adding default html extension"); + } + extension = Constants.DEFAULT_DL_HTML_EXTENSION; + } else if (useDefaults) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "adding default text extension"); + } + extension = Constants.DEFAULT_DL_TEXT_EXTENSION; + } + } else if (useDefaults) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "adding default binary extension"); + } + extension = Constants.DEFAULT_DL_BINARY_EXTENSION; + } + } + return extension; + } + + private static String chooseExtensionFromFilename(String mimeType, int destination, + String filename, int dotIndex) { + String extension = null; + if (mimeType != null) { + // Compare the last segment of the extension against the mime type. + // If there's a mismatch, discard the entire extension. + int lastDotIndex = filename.lastIndexOf('.'); + String typeFromExt = MimeTypeMap.getSingleton().getMimeTypeFromExtension( + filename.substring(lastDotIndex + 1)); + if (typeFromExt == null || !typeFromExt.equalsIgnoreCase(mimeType)) { + extension = chooseExtensionFromMimeType(mimeType, false); + if (extension != null) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "substituting extension from type"); + } + } else { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "couldn't find extension for " + mimeType); + } + } + } + } + if (extension == null) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "keeping extension"); + } + extension = filename.substring(dotIndex); + } + return extension; + } + + private static String chooseUniqueFilename(int destination, String filename, + String extension, boolean recoveryDir) { + String fullFilename = filename + extension; + if (!new File(fullFilename).exists() + && (!recoveryDir || + (destination != Downloads.DESTINATION_CACHE_PARTITION && + destination != Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE && + destination != Downloads.DESTINATION_CACHE_PARTITION_NOROAMING))) { + return fullFilename; + } + filename = filename + Constants.FILENAME_SEQUENCE_SEPARATOR; + /* + * This number is used to generate partially randomized filenames to avoid + * collisions. + * It starts at 1. + * The next 9 iterations increment it by 1 at a time (up to 10). + * The next 9 iterations increment it by 1 to 10 (random) at a time. + * The next 9 iterations increment it by 1 to 100 (random) at a time. + * ... Up to the point where it increases by 100000000 at a time. + * (the maximum value that can be reached is 1000000000) + * As soon as a number is reached that generates a filename that doesn't exist, + * that filename is used. + * If the filename coming in is [base].[ext], the generated filenames are + * [base]-[sequence].[ext]. + */ + int sequence = 1; + for (int magnitude = 1; magnitude < 1000000000; magnitude *= 10) { + for (int iteration = 0; iteration < 9; ++iteration) { + fullFilename = filename + sequence + extension; + if (!new File(fullFilename).exists()) { + return fullFilename; + } + if (Constants.LOGVV) { + Log.v(Constants.TAG, "file with sequence number " + sequence + " exists"); + } + sequence += rnd.nextInt(magnitude) + 1; + } + } + return null; + } + + /** + * Deletes purgeable files from the cache partition. This also deletes + * the matching database entries. Files are deleted in LRU order until + * the total byte size is greater than targetBytes. + */ + public static final boolean discardPurgeableFiles(Context context, long targetBytes) { + Cursor cursor = context.getContentResolver().query( + Downloads.CONTENT_URI, + null, + "( " + + Downloads.STATUS + " = " + Downloads.STATUS_SUCCESS + " AND " + + Downloads.DESTINATION + " = " + Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE + + " )", + null, + Downloads.LAST_MODIFICATION); + if (cursor == null) { + return false; + } + long totalFreed = 0; + try { + cursor.moveToFirst(); + while (!cursor.isAfterLast() && totalFreed < targetBytes) { + File file = new File(cursor.getString(cursor.getColumnIndex(Downloads._DATA))); + if (Constants.LOGVV) { + Log.v(Constants.TAG, "purging " + file.getAbsolutePath() + " for " + + file.length() + " bytes"); + } + totalFreed += file.length(); + file.delete(); + long id = cursor.getLong(cursor.getColumnIndex(Downloads._ID)); + context.getContentResolver().delete( + ContentUris.withAppendedId(Downloads.CONTENT_URI, id), null, null); + cursor.moveToNext(); + } + } finally { + cursor.close(); + } + if (Constants.LOGV) { + if (totalFreed > 0) { + Log.v(Constants.TAG, "Purged files, freed " + totalFreed + " for " + + targetBytes + " requested"); + } + } + return totalFreed > 0; + } + + /** + * Returns whether the network is available + */ + public static boolean isNetworkAvailable(Context context) { + ConnectivityManager connectivity = + (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + if (connectivity == null) { + Log.w(Constants.TAG, "couldn't get connectivity manager"); + } else { + NetworkInfo[] info = connectivity.getAllNetworkInfo(); + if (info != null) { + for (int i = 0; i < info.length; i++) { + if (info[i].getState() == NetworkInfo.State.CONNECTED) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "network is available"); + } + return true; + } + } + } + } + if (Constants.LOGVV) { + Log.v(Constants.TAG, "network is not available"); + } + return false; + } + + /** + * Returns whether the network is roaming + */ + public static boolean isNetworkRoaming(Context context) { + ConnectivityManager connectivity = + (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + if (connectivity == null) { + Log.w(Constants.TAG, "couldn't get connectivity manager"); + } else { + NetworkInfo info = connectivity.getActiveNetworkInfo(); + if (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE) { + if (TelephonyManager.getDefault().isNetworkRoaming()) { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "network is roaming"); + } + return true; + } else { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "network is not roaming"); + } + } + } else { + if (Constants.LOGVV) { + Log.v(Constants.TAG, "not using mobile network"); + } + } + } + return false; + } + + /** + * Checks whether the filename looks legitimate + */ + public static boolean isFilenameValid(String filename) { + File dir = new File(filename).getParentFile(); + return dir.equals(Environment.getDownloadCacheDirectory()) + || dir.equals(new File(Environment.getExternalStorageDirectory() + + Constants.DEFAULT_DL_SUBDIR)); + } + + /** + * Checks whether this looks like a legitimate selection parameter + */ + public static void validateSelection(String selection, Set allowedColumns) { + try { + if (selection == null) { + return; + } + Lexer lexer = new Lexer(selection, allowedColumns); + parseExpression(lexer); + if (lexer.currentToken() != Lexer.TOKEN_END) { + throw new IllegalArgumentException("syntax error"); + } + } catch (RuntimeException ex) { + if (Constants.LOGV) { + Log.d(Constants.TAG, "invalid selection [" + selection + "] triggered " + ex); + } else if (Config.LOGD) { + Log.d(Constants.TAG, "invalid selection triggered " + ex); + } + throw ex; + } + + } + + // expression <- ( expression ) | statement [AND_OR ( expression ) | statement] * + // | statement [AND_OR expression]* + private static void parseExpression(Lexer lexer) { + for (;;) { + // ( expression ) + if (lexer.currentToken() == Lexer.TOKEN_OPEN_PAREN) { + lexer.advance(); + parseExpression(lexer); + if (lexer.currentToken() != Lexer.TOKEN_CLOSE_PAREN) { + throw new IllegalArgumentException("syntax error, unmatched parenthese"); + } + lexer.advance(); + } else { + // statement + parseStatement(lexer); + } + if (lexer.currentToken() != Lexer.TOKEN_AND_OR) { + break; + } + lexer.advance(); + } + } + + // statement <- COLUMN COMPARE VALUE + // | COLUMN IS NULL + private static void parseStatement(Lexer lexer) { + // both possibilities start with COLUMN + if (lexer.currentToken() != Lexer.TOKEN_COLUMN) { + throw new IllegalArgumentException("syntax error, expected column name"); + } + lexer.advance(); + + // statement <- COLUMN COMPARE VALUE + if (lexer.currentToken() == Lexer.TOKEN_COMPARE) { + lexer.advance(); + if (lexer.currentToken() != Lexer.TOKEN_VALUE) { + throw new IllegalArgumentException("syntax error, expected quoted string"); + } + lexer.advance(); + return; + } + + // statement <- COLUMN IS NULL + if (lexer.currentToken() == Lexer.TOKEN_IS) { + lexer.advance(); + if (lexer.currentToken() != Lexer.TOKEN_NULL) { + throw new IllegalArgumentException("syntax error, expected NULL"); + } + lexer.advance(); + return; + } + + // didn't get anything good after COLUMN + throw new IllegalArgumentException("syntax error after column name"); + } + + /** + * A simple lexer that recognizes the words of our restricted subset of SQL where clauses + */ + private static class Lexer { + public static final int TOKEN_START = 0; + public static final int TOKEN_OPEN_PAREN = 1; + public static final int TOKEN_CLOSE_PAREN = 2; + public static final int TOKEN_AND_OR = 3; + public static final int TOKEN_COLUMN = 4; + public static final int TOKEN_COMPARE = 5; + public static final int TOKEN_VALUE = 6; + public static final int TOKEN_IS = 7; + public static final int TOKEN_NULL = 8; + public static final int TOKEN_END = 9; + + private final String mSelection; + private final Set mAllowedColumns; + private int mOffset = 0; + private int mCurrentToken = TOKEN_START; + private final char[] mChars; + + public Lexer(String selection, Set allowedColumns) { + mSelection = selection; + mAllowedColumns = allowedColumns; + mChars = new char[mSelection.length()]; + mSelection.getChars(0, mChars.length, mChars, 0); + advance(); + } + + public int currentToken() { + return mCurrentToken; + } + + public void advance() { + char[] chars = mChars; + + // consume whitespace + while (mOffset < chars.length && chars[mOffset] == ' ') { + ++mOffset; + } + + // end of input + if (mOffset == chars.length) { + mCurrentToken = TOKEN_END; + return; + } + + // "(" + if (chars[mOffset] == '(') { + ++mOffset; + mCurrentToken = TOKEN_OPEN_PAREN; + return; + } + + // ")" + if (chars[mOffset] == ')') { + ++mOffset; + mCurrentToken = TOKEN_CLOSE_PAREN; + return; + } + + // "?" + if (chars[mOffset] == '?') { + ++mOffset; + mCurrentToken = TOKEN_VALUE; + return; + } + + // "=" and "==" + if (chars[mOffset] == '=') { + ++mOffset; + mCurrentToken = TOKEN_COMPARE; + if (mOffset < chars.length && chars[mOffset] == '=') { + ++mOffset; + } + return; + } + + // ">" and ">=" + if (chars[mOffset] == '>') { + ++mOffset; + mCurrentToken = TOKEN_COMPARE; + if (mOffset < chars.length && chars[mOffset] == '=') { + ++mOffset; + } + return; + } + + // "<", "<=" and "<>" + if (chars[mOffset] == '<') { + ++mOffset; + mCurrentToken = TOKEN_COMPARE; + if (mOffset < chars.length && (chars[mOffset] == '=' || chars[mOffset] == '>')) { + ++mOffset; + } + return; + } + + // "!=" + if (chars[mOffset] == '!') { + ++mOffset; + mCurrentToken = TOKEN_COMPARE; + if (mOffset < chars.length && chars[mOffset] == '=') { + ++mOffset; + return; + } + throw new IllegalArgumentException("Unexpected character after !"); + } + + // columns and keywords + // first look for anything that looks like an identifier or a keyword + // and then recognize the individual words. + // no attempt is made at discarding sequences of underscores with no alphanumeric + // characters, even though it's not clear that they'd be legal column names. + if (isIdentifierStart(chars[mOffset])) { + int startOffset = mOffset; + ++mOffset; + while (mOffset < chars.length && isIdentifierChar(chars[mOffset])) { + ++mOffset; + } + String word = mSelection.substring(startOffset, mOffset); + if (mOffset - startOffset <= 4) { + if (word.equals("IS")) { + mCurrentToken = TOKEN_IS; + return; + } + if (word.equals("OR") || word.equals("AND")) { + mCurrentToken = TOKEN_AND_OR; + return; + } + if (word.equals("NULL")) { + mCurrentToken = TOKEN_NULL; + return; + } + } + if (mAllowedColumns.contains(word)) { + mCurrentToken = TOKEN_COLUMN; + return; + } + throw new IllegalArgumentException("unrecognized column or keyword"); + } + + // quoted strings + if (chars[mOffset] == '\'') { + ++mOffset; + while(mOffset < chars.length) { + if (chars[mOffset] == '\'') { + if (mOffset + 1 < chars.length && chars[mOffset + 1] == '\'') { + ++mOffset; + } else { + break; + } + } + ++mOffset; + } + if (mOffset == chars.length) { + throw new IllegalArgumentException("unterminated string"); + } + ++mOffset; + mCurrentToken = TOKEN_VALUE; + return; + } + + // anything we don't recognize + throw new IllegalArgumentException("illegal character"); + } + + private static final boolean isIdentifierStart(char c) { + return c == '_' || + (c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z'); + } + + private static final boolean isIdentifierChar(char c) { + return c == '_' || + (c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9'); + } + } +} -- cgit v1.2.3 From d311b453a4ea32dcc01e766da972c6837b7705ec Mon Sep 17 00:00:00 2001 From: The Android Open Source Project Date: Mon, 9 Mar 2009 11:52:14 -0700 Subject: auto import from //branches/cupcake/...@137197 --- Android.mk | 2 -- 1 file changed, 2 deletions(-) diff --git a/Android.mk b/Android.mk index 82f0d585..ee7dca29 100644 --- a/Android.mk +++ b/Android.mk @@ -1,8 +1,6 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := user development - LOCAL_SRC_FILES := $(call all-subdir-java-files) LOCAL_PACKAGE_NAME := DownloadProvider -- cgit v1.2.3