blob: 455bd36e5a3e797ec044d5ddebcca25be22be8c6 [file] [log] [blame]
Steve Howarda2709362010-07-02 17:12:48 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net;
18
19import android.content.ContentResolver;
20import android.content.ContentValues;
21import android.database.Cursor;
22import android.database.CursorWrapper;
23import android.os.ParcelFileDescriptor;
24import android.provider.Downloads;
Steve Howarda2709362010-07-02 17:12:48 -070025
Steve Howardadcb6972010-07-12 17:09:25 -070026import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070027import java.io.FileNotFoundException;
28import java.util.ArrayList;
29import java.util.Arrays;
30import java.util.HashMap;
31import java.util.HashSet;
32import java.util.List;
33import java.util.Map;
34import java.util.Set;
35
36/**
37 * The download manager is a system service that handles long-running HTTP downloads. Clients may
38 * request that a URI be downloaded to a particular destination file. The download manager will
39 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
40 * after failures or across connectivity changes and system reboots.
41 *
42 * Instances of this class should be obtained through
43 * {@link android.content.Context#getSystemService(String)} by passing
44 * {@link android.content.Context#DOWNLOAD_SERVICE}.
45 *
46 * @hide
47 */
48public class DownloadManager {
49 /**
50 * An identifier for a particular download, unique across the system. Clients use this ID to
51 * make subsequent calls related to the download.
52 */
53 public final static String COLUMN_ID = "id";
54
55 /**
56 * The client-supplied title for this download. This will be displayed in system notifications,
57 * if enabled.
58 */
59 public final static String COLUMN_TITLE = "title";
60
61 /**
62 * The client-supplied description of this download. This will be displayed in system
63 * notifications, if enabled.
64 */
65 public final static String COLUMN_DESCRIPTION = "description";
66
67 /**
68 * URI to be downloaded.
69 */
70 public final static String COLUMN_URI = "uri";
71
72 /**
73 * Internet Media Type of the downloaded file. This will be filled in based on the server's
74 * response once the download has started.
75 *
76 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
77 */
78 public final static String COLUMN_MEDIA_TYPE = "media_type";
79
80 /**
81 * Total size of the download in bytes. This will be filled in once the download starts.
82 */
83 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
84
85 /**
86 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
87 * will be used here. Otherwise, the value will be filled in with a generated URI once the
88 * download has started.
89 */
90 public final static String COLUMN_LOCAL_URI = "local_uri";
91
92 /**
93 * Current status of the download, as one of the STATUS_* constants.
94 */
95 public final static String COLUMN_STATUS = "status";
96
97 /**
98 * Indicates the type of error that occurred, when {@link #COLUMN_STATUS} is
99 * {@link #STATUS_FAILED}. If an HTTP error occurred, this will hold the HTTP status code as
100 * defined in RFC 2616. Otherwise, it will hold one of the ERROR_* constants.
101 *
102 * If {@link #COLUMN_STATUS} is not {@link #STATUS_FAILED}, this column's value is undefined.
103 *
104 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
105 * status codes</a>
106 */
107 public final static String COLUMN_ERROR_CODE = "error_code";
108
109 /**
110 * Number of bytes download so far.
111 */
112 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
113
114 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700115 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700116 * System.currentTimeMillis()} (wall clock time in UTC).
117 */
Steve Howardadcb6972010-07-12 17:09:25 -0700118 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700119
120
121 /**
122 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
123 */
124 public final static int STATUS_PENDING = 1 << 0;
125
126 /**
127 * Value of {@link #COLUMN_STATUS} when the download is currently running.
128 */
129 public final static int STATUS_RUNNING = 1 << 1;
130
131 /**
132 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
133 */
134 public final static int STATUS_PAUSED = 1 << 2;
135
136 /**
137 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
138 */
139 public final static int STATUS_SUCCESSFUL = 1 << 3;
140
141 /**
142 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
143 */
144 public final static int STATUS_FAILED = 1 << 4;
145
146
147 /**
148 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
149 * under any other error code.
150 */
151 public final static int ERROR_UNKNOWN = 1000;
152
153 /**
154 * Value of {@link #COLUMN_ERROR_CODE} when a storage issue arises which doesn't fit under any
155 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
156 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
157 */
158 public final static int ERROR_FILE_ERROR = 1001;
159
160 /**
161 * Value of {@link #COLUMN_ERROR_CODE} when an HTTP code was received that download manager
162 * can't handle.
163 */
164 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
165
166 /**
167 * Value of {@link #COLUMN_ERROR_CODE} when an error receiving or processing data occurred at
168 * the HTTP level.
169 */
170 public final static int ERROR_HTTP_DATA_ERROR = 1004;
171
172 /**
173 * Value of {@link #COLUMN_ERROR_CODE} when there were too many redirects.
174 */
175 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
176
177 /**
178 * Value of {@link #COLUMN_ERROR_CODE} when there was insufficient storage space. Typically,
179 * this is because the SD card is full.
180 */
181 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
182
183 /**
184 * Value of {@link #COLUMN_ERROR_CODE} when no external storage device was found. Typically,
185 * this is because the SD card is not mounted.
186 */
187 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
188
Steve Howardb8e07a52010-07-21 14:53:21 -0700189 /**
190 * Broadcast intent action sent by the download manager when a download completes.
191 */
192 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
193
194 /**
195 * Broadcast intent action sent by the download manager when a running download notification is
196 * clicked.
197 */
198 public final static String ACTION_NOTIFICATION_CLICKED =
199 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
200
201 /**
202 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
203 * long) of the download that just completed.
204 */
205 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700206
207 // this array must contain all public columns
208 private static final String[] COLUMNS = new String[] {
209 COLUMN_ID,
210 COLUMN_TITLE,
211 COLUMN_DESCRIPTION,
212 COLUMN_URI,
213 COLUMN_MEDIA_TYPE,
214 COLUMN_TOTAL_SIZE_BYTES,
215 COLUMN_LOCAL_URI,
216 COLUMN_STATUS,
217 COLUMN_ERROR_CODE,
218 COLUMN_BYTES_DOWNLOADED_SO_FAR,
Steve Howardadcb6972010-07-12 17:09:25 -0700219 COLUMN_LAST_MODIFIED_TIMESTAMP
Steve Howarda2709362010-07-02 17:12:48 -0700220 };
221
222 // columns to request from DownloadProvider
223 private static final String[] UNDERLYING_COLUMNS = new String[] {
224 Downloads.Impl._ID,
225 Downloads.COLUMN_TITLE,
226 Downloads.COLUMN_DESCRIPTION,
227 Downloads.COLUMN_URI,
228 Downloads.COLUMN_MIME_TYPE,
229 Downloads.COLUMN_TOTAL_BYTES,
230 Downloads._DATA,
231 Downloads.COLUMN_STATUS,
Steve Howardadcb6972010-07-12 17:09:25 -0700232 Downloads.COLUMN_CURRENT_BYTES,
233 Downloads.COLUMN_LAST_MODIFICATION,
Steve Howarda2709362010-07-02 17:12:48 -0700234 };
235
236 private static final Set<String> LONG_COLUMNS = new HashSet<String>(
237 Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_ERROR_CODE,
Steve Howardadcb6972010-07-12 17:09:25 -0700238 COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP));
Steve Howarda2709362010-07-02 17:12:48 -0700239
240 /**
241 * This class contains all the information necessary to request a new download. The URI is the
242 * only required parameter.
243 */
244 public static class Request {
245 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700246 * Bit flag for {@link #setShowNotification} indicating a notification should be created
247 * while the download is running.
Steve Howarda2709362010-07-02 17:12:48 -0700248 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700249 public static final int NOTIFICATION_WHEN_RUNNING = 1;
Steve Howarda2709362010-07-02 17:12:48 -0700250
Steve Howardb8e07a52010-07-21 14:53:21 -0700251 /**
252 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
253 * {@link ConnectivityManager#TYPE_MOBILE}.
254 */
255 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700256
Steve Howardb8e07a52010-07-21 14:53:21 -0700257 /**
258 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
259 * {@link ConnectivityManager#TYPE_WIFI}.
260 */
261 public static final int NETWORK_WIFI = 1 << 1;
262
263 /**
264 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
265 * {@link ConnectivityManager#TYPE_WIMAX}.
266 */
267 public static final int NETWORK_WIMAX = 1 << 2;
268
269 private Uri mUri;
270 private Uri mDestinationUri;
271 private Map<String, String> mRequestHeaders = new HashMap<String, String>();
272 private String mTitle;
273 private String mDescription;
274 private int mNotificationFlags = 0;
Steve Howarda2709362010-07-02 17:12:48 -0700275 private String mMediaType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700276 private boolean mRoamingAllowed = true;
277 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Steve Howarda2709362010-07-02 17:12:48 -0700278
279 /**
280 * @param uri the HTTP URI to download.
281 */
282 public Request(Uri uri) {
283 if (uri == null) {
284 throw new NullPointerException();
285 }
286 String scheme = uri.getScheme();
287 if (scheme == null || !scheme.equals("http")) {
288 throw new IllegalArgumentException("Can only download HTTP URIs: " + uri);
289 }
290 mUri = uri;
291 }
292
293 /**
294 * Set the local destination for the downloaded data. Must be a file URI to a path on
295 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
296 * permission.
297 *
298 * By default, downloads are saved to a generated file in the download cache and may be
299 * deleted by the download manager at any time.
300 *
301 * @return this object
302 */
303 public Request setDestinationUri(Uri uri) {
304 mDestinationUri = uri;
305 return this;
306 }
307
308 /**
309 * Set an HTTP header to be included with the download request.
310 * @param header HTTP header name
311 * @param value header value
312 * @return this object
313 */
314 public Request setRequestHeader(String header, String value) {
315 mRequestHeaders.put(header, value);
316 return this;
317 }
318
319 /**
320 * Set the title of this download, to be displayed in notifications (if enabled)
321 * @return this object
322 */
323 public Request setTitle(String title) {
324 mTitle = title;
325 return this;
326 }
327
328 /**
329 * Set a description of this download, to be displayed in notifications (if enabled)
330 * @return this object
331 */
332 public Request setDescription(String description) {
333 mDescription = description;
334 return this;
335 }
336
337 /**
338 * Set the Internet Media Type of this download. This will override the media type declared
339 * in the server's response.
340 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
341 * @return this object
342 */
343 public Request setMediaType(String mediaType) {
344 mMediaType = mediaType;
345 return this;
346 }
347
348 /**
349 * Control system notifications posted by the download manager for this download. If
350 * enabled, the download manager posts notifications about downloads through the system
Steve Howardb8e07a52010-07-21 14:53:21 -0700351 * {@link android.app.NotificationManager}. By default, no notification is shown.
Steve Howarda2709362010-07-02 17:12:48 -0700352 *
353 * @param flags any combination of the NOTIFICATION_* bit flags
354 * @return this object
355 */
356 public Request setShowNotification(int flags) {
357 mNotificationFlags = flags;
358 return this;
359 }
360
Steve Howardb8e07a52010-07-21 14:53:21 -0700361 /**
362 * Restrict the types of networks over which this download may proceed. By default, all
363 * network types are allowed.
364 * @param flags any combination of the NETWORK_* bit flags.
365 * @return this object
366 */
Steve Howarda2709362010-07-02 17:12:48 -0700367 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700368 mAllowedNetworkTypes = flags;
369 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700370 }
371
Steve Howardb8e07a52010-07-21 14:53:21 -0700372 /**
373 * Set whether this download may proceed over a roaming connection. By default, roaming is
374 * allowed.
375 * @param allowed whether to allow a roaming connection to be used
376 * @return this object
377 */
Steve Howarda2709362010-07-02 17:12:48 -0700378 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700379 mRoamingAllowed = allowed;
380 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700381 }
382
383 /**
384 * @return ContentValues to be passed to DownloadProvider.insert()
385 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700386 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700387 ContentValues values = new ContentValues();
388 assert mUri != null;
389 values.put(Downloads.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700390 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
391 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700392
393 if (mDestinationUri != null) {
Steve Howardadcb6972010-07-12 17:09:25 -0700394 values.put(Downloads.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
395 values.put(Downloads.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700396 } else {
397 values.put(Downloads.COLUMN_DESTINATION,
398 Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE);
399 }
400
401 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700402 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700403 }
404
405 putIfNonNull(values, Downloads.COLUMN_TITLE, mTitle);
406 putIfNonNull(values, Downloads.COLUMN_DESCRIPTION, mDescription);
407 putIfNonNull(values, Downloads.COLUMN_MIME_TYPE, mMediaType);
408
409 int visibility = Downloads.VISIBILITY_HIDDEN;
410 if ((mNotificationFlags & NOTIFICATION_WHEN_RUNNING) != 0) {
411 visibility = Downloads.VISIBILITY_VISIBLE;
412 }
413 values.put(Downloads.COLUMN_VISIBILITY, visibility);
414
Steve Howardb8e07a52010-07-21 14:53:21 -0700415 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
416 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
417
Steve Howarda2709362010-07-02 17:12:48 -0700418 return values;
419 }
420
Steve Howardea9147d2010-07-13 19:02:45 -0700421 private void encodeHttpHeaders(ContentValues values) {
422 int index = 0;
423 for (Map.Entry<String, String> entry : mRequestHeaders.entrySet()) {
424 String headerString = entry.getKey() + ": " + entry.getValue();
425 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
426 index++;
427 }
428 }
429
Steve Howarda2709362010-07-02 17:12:48 -0700430 private void putIfNonNull(ContentValues contentValues, String key, String value) {
431 if (value != null) {
432 contentValues.put(key, value);
433 }
434 }
435 }
436
437 /**
438 * This class may be used to filter download manager queries.
439 */
440 public static class Query {
441 private Long mId;
442 private Integer mStatusFlags = null;
443
444 /**
445 * Include only the download with the given ID.
446 * @return this object
447 */
448 public Query setFilterById(long id) {
449 mId = id;
450 return this;
451 }
452
453 /**
454 * Include only downloads with status matching any the given status flags.
455 * @param flags any combination of the STATUS_* bit flags
456 * @return this object
457 */
458 public Query setFilterByStatus(int flags) {
459 mStatusFlags = flags;
460 return this;
461 }
462
463 /**
464 * Run this query using the given ContentResolver.
465 * @param projection the projection to pass to ContentResolver.query()
466 * @return the Cursor returned by ContentResolver.query()
467 */
468 Cursor runQuery(ContentResolver resolver, String[] projection) {
469 Uri uri = Downloads.CONTENT_URI;
470 String selection = null;
471
472 if (mId != null) {
473 uri = Uri.withAppendedPath(uri, mId.toString());
474 }
475
476 if (mStatusFlags != null) {
477 List<String> parts = new ArrayList<String>();
478 if ((mStatusFlags & STATUS_PENDING) != 0) {
479 parts.add(statusClause("=", Downloads.STATUS_PENDING));
480 }
481 if ((mStatusFlags & STATUS_RUNNING) != 0) {
482 parts.add(statusClause("=", Downloads.STATUS_RUNNING));
483 }
484 if ((mStatusFlags & STATUS_PAUSED) != 0) {
485 parts.add(statusClause("=", Downloads.STATUS_PENDING_PAUSED));
486 parts.add(statusClause("=", Downloads.STATUS_RUNNING_PAUSED));
487 }
488 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
489 parts.add(statusClause("=", Downloads.STATUS_SUCCESS));
490 }
491 if ((mStatusFlags & STATUS_FAILED) != 0) {
492 parts.add("(" + statusClause(">=", 400)
493 + " AND " + statusClause("<", 600) + ")");
494 }
495 selection = joinStrings(" OR ", parts);
Steve Howarda2709362010-07-02 17:12:48 -0700496 }
Steve Howardadcb6972010-07-12 17:09:25 -0700497 String orderBy = Downloads.COLUMN_LAST_MODIFICATION + " DESC";
498 return resolver.query(uri, projection, selection, null, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700499 }
500
501 private String joinStrings(String joiner, Iterable<String> parts) {
502 StringBuilder builder = new StringBuilder();
503 boolean first = true;
504 for (String part : parts) {
505 if (!first) {
506 builder.append(joiner);
507 }
508 builder.append(part);
509 first = false;
510 }
511 return builder.toString();
512 }
513
514 private String statusClause(String operator, int value) {
515 return Downloads.COLUMN_STATUS + operator + "'" + value + "'";
516 }
517 }
518
519 private ContentResolver mResolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700520 private String mPackageName;
Steve Howarda2709362010-07-02 17:12:48 -0700521
522 /**
523 * @hide
524 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700525 public DownloadManager(ContentResolver resolver, String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700526 mResolver = resolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700527 mPackageName = packageName;
Steve Howarda2709362010-07-02 17:12:48 -0700528 }
529
530 /**
531 * Enqueue a new download. The download will start automatically once the download manager is
532 * ready to execute it and connectivity is available.
533 *
534 * @param request the parameters specifying this download
535 * @return an ID for the download, unique across the system. This ID is used to make future
536 * calls related to this download.
537 */
538 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700539 ContentValues values = request.toContentValues(mPackageName);
Steve Howarda2709362010-07-02 17:12:48 -0700540 Uri downloadUri = mResolver.insert(Downloads.CONTENT_URI, values);
541 long id = Long.parseLong(downloadUri.getLastPathSegment());
542 return id;
543 }
544
545 /**
546 * Cancel a download and remove it from the download manager. The download will be stopped if
547 * it was running, and it will no longer be accessible through the download manager. If a file
548 * was already downloaded, it will not be deleted.
549 *
550 * @param id the ID of the download
551 */
552 public void remove(long id) {
553 int numDeleted = mResolver.delete(getDownloadUri(id), null, null);
554 if (numDeleted == 0) {
555 throw new IllegalArgumentException("Download " + id + " does not exist");
556 }
557 }
558
559 /**
560 * Query the download manager about downloads that have been requested.
561 * @param query parameters specifying filters for this query
562 * @return a Cursor over the result set of downloads, with columns consisting of all the
563 * COLUMN_* constants.
564 */
565 public Cursor query(Query query) {
566 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS);
567 return new CursorTranslator(underlyingCursor);
568 }
569
570 /**
571 * Open a downloaded file for reading. The download must have completed.
572 * @param id the ID of the download
573 * @return a read-only {@link ParcelFileDescriptor}
574 * @throws FileNotFoundException if the destination file does not already exist
575 */
576 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
577 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
578 }
579
580 /**
581 * Get the DownloadProvider URI for the download with the given ID.
582 */
583 private Uri getDownloadUri(long id) {
584 Uri downloadUri = Uri.withAppendedPath(Downloads.CONTENT_URI, Long.toString(id));
585 return downloadUri;
586 }
587
588 /**
589 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
590 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
591 * Some columns correspond directly to underlying values while others are computed from
592 * underlying data.
593 */
594 private static class CursorTranslator extends CursorWrapper {
595 public CursorTranslator(Cursor cursor) {
596 super(cursor);
597 }
598
599 @Override
600 public int getColumnIndex(String columnName) {
601 return Arrays.asList(COLUMNS).indexOf(columnName);
602 }
603
604 @Override
605 public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
606 int index = getColumnIndex(columnName);
607 if (index == -1) {
608 throw new IllegalArgumentException();
609 }
610 return index;
611 }
612
613 @Override
614 public String getColumnName(int columnIndex) {
615 int numColumns = COLUMNS.length;
616 if (columnIndex < 0 || columnIndex >= numColumns) {
617 throw new IllegalArgumentException("Invalid column index " + columnIndex + ", "
618 + numColumns + " columns exist");
619 }
620 return COLUMNS[columnIndex];
621 }
622
623 @Override
624 public String[] getColumnNames() {
625 String[] returnColumns = new String[COLUMNS.length];
626 System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length);
627 return returnColumns;
628 }
629
630 @Override
631 public int getColumnCount() {
632 return COLUMNS.length;
633 }
634
635 @Override
636 public byte[] getBlob(int columnIndex) {
637 throw new UnsupportedOperationException();
638 }
639
640 @Override
641 public double getDouble(int columnIndex) {
642 return getLong(columnIndex);
643 }
644
645 private boolean isLongColumn(String column) {
646 return LONG_COLUMNS.contains(column);
647 }
648
649 @Override
650 public float getFloat(int columnIndex) {
651 return (float) getDouble(columnIndex);
652 }
653
654 @Override
655 public int getInt(int columnIndex) {
656 return (int) getLong(columnIndex);
657 }
658
659 @Override
660 public long getLong(int columnIndex) {
661 return translateLong(getColumnName(columnIndex));
662 }
663
664 @Override
665 public short getShort(int columnIndex) {
666 return (short) getLong(columnIndex);
667 }
668
669 @Override
670 public String getString(int columnIndex) {
671 return translateString(getColumnName(columnIndex));
672 }
673
674 private String translateString(String column) {
675 if (isLongColumn(column)) {
676 return Long.toString(translateLong(column));
677 }
678 if (column.equals(COLUMN_TITLE)) {
679 return getUnderlyingString(Downloads.COLUMN_TITLE);
680 }
681 if (column.equals(COLUMN_DESCRIPTION)) {
682 return getUnderlyingString(Downloads.COLUMN_DESCRIPTION);
683 }
684 if (column.equals(COLUMN_URI)) {
685 return getUnderlyingString(Downloads.COLUMN_URI);
686 }
687 if (column.equals(COLUMN_MEDIA_TYPE)) {
688 return getUnderlyingString(Downloads.COLUMN_MIME_TYPE);
689 }
690 assert column.equals(COLUMN_LOCAL_URI);
Steve Howardadcb6972010-07-12 17:09:25 -0700691 return Uri.fromFile(new File(getUnderlyingString(Downloads._DATA))).toString();
Steve Howarda2709362010-07-02 17:12:48 -0700692 }
693
694 private long translateLong(String column) {
695 if (!isLongColumn(column)) {
696 // mimic behavior of underlying cursor -- most likely, throw NumberFormatException
697 return Long.valueOf(translateString(column));
698 }
699
700 if (column.equals(COLUMN_ID)) {
701 return getUnderlyingLong(Downloads.Impl._ID);
702 }
703 if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
704 return getUnderlyingLong(Downloads.COLUMN_TOTAL_BYTES);
705 }
706 if (column.equals(COLUMN_STATUS)) {
707 return translateStatus((int) getUnderlyingLong(Downloads.COLUMN_STATUS));
708 }
709 if (column.equals(COLUMN_ERROR_CODE)) {
710 return translateErrorCode((int) getUnderlyingLong(Downloads.COLUMN_STATUS));
711 }
712 if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) {
713 return getUnderlyingLong(Downloads.COLUMN_CURRENT_BYTES);
714 }
Steve Howardadcb6972010-07-12 17:09:25 -0700715 assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP);
716 return getUnderlyingLong(Downloads.COLUMN_LAST_MODIFICATION);
Steve Howarda2709362010-07-02 17:12:48 -0700717 }
718
719 private long translateErrorCode(int status) {
720 if (translateStatus(status) != STATUS_FAILED) {
721 return 0; // arbitrary value when status is not an error
722 }
723 if ((400 <= status && status < 490) || (500 <= status && status < 600)) {
724 // HTTP status code
725 return status;
726 }
727
728 switch (status) {
729 case Downloads.STATUS_FILE_ERROR:
730 return ERROR_FILE_ERROR;
731
732 case Downloads.STATUS_UNHANDLED_HTTP_CODE:
733 case Downloads.STATUS_UNHANDLED_REDIRECT:
734 return ERROR_UNHANDLED_HTTP_CODE;
735
736 case Downloads.STATUS_HTTP_DATA_ERROR:
737 return ERROR_HTTP_DATA_ERROR;
738
739 case Downloads.STATUS_TOO_MANY_REDIRECTS:
740 return ERROR_TOO_MANY_REDIRECTS;
741
742 case Downloads.STATUS_INSUFFICIENT_SPACE_ERROR:
743 return ERROR_INSUFFICIENT_SPACE;
744
745 case Downloads.STATUS_DEVICE_NOT_FOUND_ERROR:
746 return ERROR_DEVICE_NOT_FOUND;
747
748 default:
749 return ERROR_UNKNOWN;
750 }
751 }
752
753 private long getUnderlyingLong(String column) {
754 return super.getLong(super.getColumnIndex(column));
755 }
756
757 private String getUnderlyingString(String column) {
758 return super.getString(super.getColumnIndex(column));
759 }
760
761 private long translateStatus(int status) {
762 switch (status) {
763 case Downloads.STATUS_PENDING:
764 return STATUS_PENDING;
765
766 case Downloads.STATUS_RUNNING:
767 return STATUS_RUNNING;
768
769 case Downloads.STATUS_PENDING_PAUSED:
770 case Downloads.STATUS_RUNNING_PAUSED:
771 return STATUS_PAUSED;
772
773 case Downloads.STATUS_SUCCESS:
774 return STATUS_SUCCESSFUL;
775
776 default:
777 assert Downloads.isStatusError(status);
778 return STATUS_FAILED;
779 }
780 }
781 }
782}