summaryrefslogtreecommitdiffstats
path: root/core/java/android/net/Downloads.java
blob: 72106c8f524dd8baa61fa60203326c15a896a3a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/*
 * 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 android.net;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.os.SystemClock;
import android.provider.BaseColumns;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.InputStream;

/**
 * The Download Manager
 *
 *
 */
public final class Downloads {


    /**
     * Download status codes
     */

    /**
     * This download hasn't started yet
     */
    public static final int STATUS_PENDING = 190;

    /**
     * This download has started
     */
    public static final int STATUS_RUNNING = 192;

    /**
     * This download has successfully completed.
     * Warning: there might be other status values that indicate success
     * in the future.
     * Use isSucccess() to capture the entire category.
     */
    public static final int STATUS_SUCCESS = 200;

    /**
     * This download can't be performed because the content type cannot be
     * handled.
     */
    public static final int STATUS_NOT_ACCEPTABLE = 406;

    /**
     * This download has completed with an error.
     * Warning: there will be other status values that indicate errors in
     * the future. Use isStatusError() to capture the entire category.
     */
    public static final int STATUS_UNKNOWN_ERROR = 491;

    /**
     * This download couldn't be completed because of an HTTP
     * redirect response that the download manager couldn't
     * handle.
     */
    public static final int STATUS_UNHANDLED_REDIRECT = 493;

    /**
     * This download couldn't be completed due to insufficient storage
     * space.  Typically, this is because the SD card is full.
     */
    public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498;

    /**
     * This download couldn't be completed because no external storage
     * device was found.  Typically, this is because the SD card is not
     * mounted.
     */
    public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499;

    /**
     * Returns whether the status is a success (i.e. 2xx).
     */
    public static boolean isStatusSuccess(int status) {
        return (status >= 200 && status < 300);
    }

    /**
     * Returns whether the status is an error (i.e. 4xx or 5xx).
     */
    public static boolean isStatusError(int status) {
        return (status >= 400 && status < 600);
    }

    /**
     * Download destinations
     */

    /**
     * This download will be saved to the external storage. This is the
     * default behavior, and should be used for any file that the user
     * can freely access, copy, delete. Even with that destination,
     * unencrypted DRM files are saved in secure internal storage.
     * Downloads to the external destination only write files for which
     * there is a registered handler. The resulting files are accessible
     * by filename to all applications.
     */
    public static final int DOWNLOAD_DESTINATION_EXTERNAL = 1;

    /**
     * This download will be saved to the download manager's private
     * partition. This is the behavior used by applications that want to
     * download private files that are used and deleted soon after they
     * get downloaded. All file types are allowed, and only the initiating
     * application can access the file (indirectly through a content
     * provider). This requires the
     * android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED permission.
     */
    public static final int DOWNLOAD_DESTINATION_CACHE = 2;

    /**
     * This download will be saved to the download manager's private
     * partition and will be purged as necessary to make space. This is
     * for private files (similar to CACHE_PARTITION) that aren't deleted
     * immediately after they are used, and are kept around by the download
     * manager as long as space is available.
     */
    public static final int DOWNLOAD_DESTINATION_CACHE_PURGEABLE = 3;


    /**
     * An invalid download id
     */
    public static final long DOWNLOAD_ID_INVALID = -1;


    /**
     * Broadcast Action: this is sent by the download manager to the app
     * that had initiated a download when that download completes. The
     * download's content: uri is specified in the intent's data.
     */
    public static final String ACTION_DOWNLOAD_COMPLETED =
            "android.intent.action.DOWNLOAD_COMPLETED";

    /**
     * If extras are specified when requesting a download they will be provided in the intent that
     * is sent to the specified class and package when a download has finished.
     * <P>Type: TEXT</P>
     * <P>Owner can Init</P>
     */
    public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras";


    /**
     * Status class for a download
     */
    public static final class StatusInfo {
        public boolean completed = false;
        /** The filename of the active download. */
        public String filename = null;
        /** An opaque id for the download */
        public long id = DOWNLOAD_ID_INVALID;
        /** An opaque status code for the download */
        public int statusCode = -1;
        /** Approximate number of bytes downloaded so far, for debugging purposes. */
        public long bytesSoFar = -1;

        /**
         * Returns whether the download is completed
         * @return a boolean whether the download is complete.
         */
        public boolean isComplete() {
            return android.provider.Downloads.Impl.isStatusCompleted(statusCode);
        }

        /**
         * Returns whether the download is successful
         * @return a boolean whether the download is successful.
         */
        public boolean isSuccessful() {
            return android.provider.Downloads.Impl.isStatusCompleted(statusCode);
        }
    }

    /**
     * Class to access initiate and query download by server uri
     */
    public static final class ByUri extends DownloadBase {
        /** @hide */
        private ByUri() {}

        /**
         * Query where clause by app data.
         * @hide
         */
        private static final String QUERY_WHERE_APP_DATA_CLAUSE =
                android.provider.Downloads.Impl.COLUMN_APP_DATA + "=?";

        /**
         * Gets a Cursor pointing to the download(s) of the current system update.
         * @hide
         */
        private static final Cursor getCurrentOtaDownloads(Context context, String url) {
            return context.getContentResolver().query(
                    android.provider.Downloads.Impl.CONTENT_URI,
                    DOWNLOADS_PROJECTION,
                    QUERY_WHERE_APP_DATA_CLAUSE,
                    new String[] {url},
                    null);
        }

        /**
         * Returns a StatusInfo with the result of trying to download the
         * given URL.  Returns null if no attempts have been made.
         */
        public static final StatusInfo getStatus(
                Context context,
                String url,
                long redownload_threshold) {
            StatusInfo result = null;
            boolean hasFailedDownload = false;
            long failedDownloadModificationTime = 0;
            Cursor c = getCurrentOtaDownloads(context, url);
            try {
                while (c != null && c.moveToNext()) {
                    if (result == null) {
                        result = new StatusInfo();
                    }
                    int status = getStatusOfDownload(c, redownload_threshold);
                    if (status == STATUS_DOWNLOADING_UPDATE ||
                        status == STATUS_DOWNLOADED_UPDATE) {
                        result.completed = (status == STATUS_DOWNLOADED_UPDATE);
                        result.filename = c.getString(DOWNLOADS_COLUMN_FILENAME);
                        result.id = c.getLong(DOWNLOADS_COLUMN_ID);
                        result.statusCode = c.getInt(DOWNLOADS_COLUMN_STATUS);
                        result.bytesSoFar = c.getLong(DOWNLOADS_COLUMN_CURRENT_BYTES);
                        return result;
                    }

                    long modTime = c.getLong(DOWNLOADS_COLUMN_LAST_MODIFICATION);
                    if (hasFailedDownload &&
                        modTime < failedDownloadModificationTime) {
                        // older than the one already in result; skip it.
                        continue;
                    }

                    hasFailedDownload = true;
                    failedDownloadModificationTime = modTime;
                    result.statusCode = c.getInt(DOWNLOADS_COLUMN_STATUS);
                    result.bytesSoFar = c.getLong(DOWNLOADS_COLUMN_CURRENT_BYTES);
                }
            } finally {
                if (c != null) {
                    c.close();
                }
            }
            return result;
        }

        /**
         * Query where clause for general querying.
         */
        private static final String QUERY_WHERE_CLAUSE =
                android.provider.Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE + "=? AND " +
                android.provider.Downloads.Impl.COLUMN_NOTIFICATION_CLASS + "=?";

        /**
         * Delete all the downloads for a package/class pair.
         */
        public static final void removeAllDownloadsByPackage(
                Context context,
                String notification_package,
                String notification_class) {
            context.getContentResolver().delete(
                    android.provider.Downloads.Impl.CONTENT_URI,
                    QUERY_WHERE_CLAUSE,
                    new String[] { notification_package, notification_class });
        }

        /**
         * The column for the id in the Cursor returned by
         * getProgressCursor()
         */
        public static final int getProgressColumnId() {
            return 0;
        }

        /**
         * The column for the current byte count in the Cursor returned by
         * getProgressCursor()
         */
        public static final int getProgressColumnCurrentBytes() {
            return 1;
        }

        /**
         * The column for the total byte count in the Cursor returned by
         * getProgressCursor()
         */
        public static final int getProgressColumnTotalBytes() {
            return 2;
        }

        /** @hide */
        private static final String[] PROJECTION = {
            BaseColumns._ID,
            android.provider.Downloads.Impl.COLUMN_CURRENT_BYTES,
            android.provider.Downloads.Impl.COLUMN_TOTAL_BYTES
        };

        /**
         * Returns a Cursor representing the progress of the download identified by the ID.
         */
        public static final Cursor getProgressCursor(Context context, long id) {
            Uri downloadUri = Uri.withAppendedPath(android.provider.Downloads.Impl.CONTENT_URI,
                    String.valueOf(id));
            return context.getContentResolver().query(downloadUri, PROJECTION, null, null, null);
        }
    }

    /**
     * Class to access downloads by opaque download id
     */
    public static final class ById extends DownloadBase {
        /** @hide */
        private ById() {}

        /**
         * Get the mime tupe of the download specified by the download id
         */
        public static String getMimeTypeForId(Context context, long downloadId) {
            ContentResolver cr = context.getContentResolver();

            String mimeType = null;
            Cursor downloadCursor = null;

            try {
                Uri downloadUri = getDownloadUri(downloadId);

                downloadCursor = cr.query(
                        downloadUri, new String[]{android.provider.Downloads.Impl.COLUMN_MIME_TYPE},
                        null, null, null);
                if (downloadCursor.moveToNext()) {
                    mimeType = downloadCursor.getString(0);
                }
            } finally {
                if (downloadCursor != null) downloadCursor.close();
            }
            return mimeType;
        }

        /**
         * Delete a download by Id
         */
        public static void deleteDownload(Context context, long downloadId) {
            ContentResolver cr = context.getContentResolver();

            String mimeType = null;

            Uri downloadUri = getDownloadUri(downloadId);

            cr.delete(downloadUri, null, null);
        }

        /**
         * Open a filedescriptor to a particular download
         */
        public static ParcelFileDescriptor openDownload(
                Context context, long downloadId, String mode)
            throws FileNotFoundException
        {
            ContentResolver cr = context.getContentResolver();

            String mimeType = null;

            Uri downloadUri = getDownloadUri(downloadId);

            return cr.openFileDescriptor(downloadUri, mode);
        }

        /**
         * Open a stream to a particular download
         */
        public static InputStream openDownloadStream(Context context, long downloadId)
                throws FileNotFoundException, IOException
        {
            ContentResolver cr = context.getContentResolver();

            String mimeType = null;

            Uri downloadUri = getDownloadUri(downloadId);

            return cr.openInputStream(downloadUri);
        }

        private static Uri getDownloadUri(long downloadId) {
            return Uri.parse(android.provider.Downloads.Impl.CONTENT_URI + "/" + downloadId);
        }

        /**
         * Returns a StatusInfo with the result of trying to download the
         * given URL.  Returns null if no attempts have been made.
         */
        public static final StatusInfo getStatus(
                Context context,
                long downloadId) {
            StatusInfo result = null;
            boolean hasFailedDownload = false;
            long failedDownloadModificationTime = 0;

            Uri downloadUri = getDownloadUri(downloadId);

            ContentResolver cr = context.getContentResolver();

            Cursor c = cr.query(
                    downloadUri, DOWNLOADS_PROJECTION, null /* selection */, null /* selection args */,
                    null /* sort order */);
            try {
                if (!c.moveToNext()) {
                    return result;
                }

                if (result == null) {
                    result = new StatusInfo();
                }
                int status = getStatusOfDownload(c,0);
                if (status == STATUS_DOWNLOADING_UPDATE ||
                        status == STATUS_DOWNLOADED_UPDATE) {
                    result.completed = (status == STATUS_DOWNLOADED_UPDATE);
                    result.filename = c.getString(DOWNLOADS_COLUMN_FILENAME);
                    result.id = c.getLong(DOWNLOADS_COLUMN_ID);
                    result.statusCode = c.getInt(DOWNLOADS_COLUMN_STATUS);
                    result.bytesSoFar = c.getLong(DOWNLOADS_COLUMN_CURRENT_BYTES);
                    return result;
                }

                long modTime = c.getLong(DOWNLOADS_COLUMN_LAST_MODIFICATION);

                result.statusCode = c.getInt(DOWNLOADS_COLUMN_STATUS);
                result.bytesSoFar = c.getLong(DOWNLOADS_COLUMN_CURRENT_BYTES);
            } finally {
                if (c != null) {
                    c.close();
                }
            }
            return result;
        }
    }


    /**
     * Base class with common functionality for the various download classes
     */
    private static class DownloadBase {
        /** @hide */
        DownloadBase() {}

        /**
          * Initiate a download where the download will be tracked by its URI.
          */
        public static long startDownloadByUri(
                Context context,
                String url,
                String cookieData,
                boolean showDownload,
                int downloadDestination,
                boolean allowRoaming,
                boolean skipIntegrityCheck,
                String title,
                String notification_package,
                String notification_class,
                String notification_extras) {
            ContentResolver cr = context.getContentResolver();

            // Tell download manager to start downloading update.
            ContentValues values = new ContentValues();
            values.put(android.provider.Downloads.Impl.COLUMN_URI, url);
            values.put(android.provider.Downloads.Impl.COLUMN_COOKIE_DATA, cookieData);
            values.put(android.provider.Downloads.Impl.COLUMN_VISIBILITY,
                       showDownload ? android.provider.Downloads.Impl.VISIBILITY_VISIBLE
                       : android.provider.Downloads.Impl.VISIBILITY_HIDDEN);
            if (title != null) {
                values.put(android.provider.Downloads.Impl.COLUMN_TITLE, title);
            }
            values.put(android.provider.Downloads.Impl.COLUMN_APP_DATA, url);


            // NOTE:  destination should be seperated from whether the download
            // can happen when roaming
            int destination = android.provider.Downloads.Impl.DESTINATION_EXTERNAL;
            switch (downloadDestination) {
                case DOWNLOAD_DESTINATION_EXTERNAL:
                    destination = android.provider.Downloads.Impl.DESTINATION_EXTERNAL;
                    break;
                case DOWNLOAD_DESTINATION_CACHE:
                    if (allowRoaming) {
                        destination = android.provider.Downloads.Impl.DESTINATION_CACHE_PARTITION;
                    } else {
                        destination =
                                android.provider.Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING;
                    }
                    break;
                case DOWNLOAD_DESTINATION_CACHE_PURGEABLE:
                    destination =
                            android.provider.Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE;
                    break;
            }
            values.put(android.provider.Downloads.Impl.COLUMN_DESTINATION, destination);
            values.put(android.provider.Downloads.Impl.COLUMN_NO_INTEGRITY,
                    skipIntegrityCheck);  // Don't check ETag
            if (notification_package != null && notification_class != null) {
                values.put(android.provider.Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
                        notification_package);
                values.put(android.provider.Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
                        notification_class);

                if (notification_extras != null) {
                    values.put(android.provider.Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS,
                            notification_extras);
                }
            }

            Uri downloadUri = cr.insert(android.provider.Downloads.Impl.CONTENT_URI, values);

            long downloadId = DOWNLOAD_ID_INVALID;
            if (downloadUri != null) {
                downloadId = Long.parseLong(downloadUri.getLastPathSegment());
            }
            return downloadId;
        }
    }

    /** @hide */
    private static final int STATUS_INVALID = 0;
    /** @hide */
    private static final int STATUS_DOWNLOADING_UPDATE = 3;
    /** @hide */
    private static final int STATUS_DOWNLOADED_UPDATE = 4;

    /**
     * Column projection for the query to the download manager. This must match
     * with the constants DOWNLOADS_COLUMN_*.
     * @hide
     */
    private static final String[] DOWNLOADS_PROJECTION = {
            BaseColumns._ID,
            android.provider.Downloads.Impl.COLUMN_APP_DATA,
            android.provider.Downloads.Impl.COLUMN_STATUS,
            android.provider.Downloads.Impl._DATA,
            android.provider.Downloads.Impl.COLUMN_LAST_MODIFICATION,
            android.provider.Downloads.Impl.COLUMN_CURRENT_BYTES,
    };

    /**
     * The column index for the ID.
     * @hide
     */
    private static final int DOWNLOADS_COLUMN_ID = 0;
    /**
     * The column index for the URI.
     * @hide
     */
    private static final int DOWNLOADS_COLUMN_URI = 1;
    /**
     * The column index for the status code.
     * @hide
     */
    private static final int DOWNLOADS_COLUMN_STATUS = 2;
    /**
     * The column index for the filename.
     * @hide
     */
    private static final int DOWNLOADS_COLUMN_FILENAME = 3;
    /**
     * The column index for the last modification time.
     * @hide
     */
    private static final int DOWNLOADS_COLUMN_LAST_MODIFICATION = 4;
    /**
     * The column index for the number of bytes downloaded so far.
     * @hide
     */
    private static final int DOWNLOADS_COLUMN_CURRENT_BYTES = 5;

    /**
     * Gets the status of a download.
     *
     * @param c A Cursor pointing to a download.  The URL column is assumed to be valid.
     * @return The status of the download.
     * @hide
     */
    private static final int getStatusOfDownload( Cursor c, long redownload_threshold) {
        int status = c.getInt(DOWNLOADS_COLUMN_STATUS);
        long realtime = SystemClock.elapsedRealtime();

        // TODO(dougz): special handling of 503, 404?  (eg, special
        // explanatory messages to user)

        if (!android.provider.Downloads.Impl.isStatusCompleted(status)) {
            // Check if it's stuck
            long modified = c.getLong(DOWNLOADS_COLUMN_LAST_MODIFICATION);
            long now = System.currentTimeMillis();
            if (now < modified || now - modified > redownload_threshold) {
                return STATUS_INVALID;
            }

            return STATUS_DOWNLOADING_UPDATE;
        }

        if (android.provider.Downloads.Impl.isStatusError(status)) {
            return STATUS_INVALID;
        }

        String filename = c.getString(DOWNLOADS_COLUMN_FILENAME);
        if (filename == null) {
            return STATUS_INVALID;
        }

        return STATUS_DOWNLOADED_UPDATE;
    }


    /**
     * @hide
     */
    private Downloads() {}
}