summaryrefslogtreecommitdiffstats
path: root/src/com/android/providers/downloads/DownloadInfo.java
blob: eb9ac4bdfe9de15c25afe747796ece446201d8fb (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
/*
 * 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.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.drm.mobile1.DrmRawContent;
import android.net.ConnectivityManager;
import android.net.DownloadManager;
import android.net.Uri;
import android.provider.Downloads;
import android.provider.Downloads.Impl;
import android.util.Log;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Stores information about an individual download.
 */
public class DownloadInfo {
    public static class Reader {
        private ContentResolver mResolver;
        private Cursor mCursor;
        private CharArrayBuffer mOldChars;
        private CharArrayBuffer mNewChars;

        public Reader(ContentResolver resolver, Cursor cursor) {
            mResolver = resolver;
            mCursor = cursor;
        }

        public DownloadInfo newDownloadInfo(Context context, SystemFacade systemFacade) {
            DownloadInfo info = new DownloadInfo(context, systemFacade);
            updateFromDatabase(info);
            readRequestHeaders(info);
            return info;
        }

        public void updateFromDatabase(DownloadInfo info) {
            info.mId = getLong(Downloads.Impl._ID);
            info.mUri = getString(info.mUri, Downloads.Impl.COLUMN_URI);
            info.mNoIntegrity = getInt(Downloads.Impl.COLUMN_NO_INTEGRITY) == 1;
            info.mHint = getString(info.mHint, Downloads.Impl.COLUMN_FILE_NAME_HINT);
            info.mFileName = getString(info.mFileName, Downloads.Impl._DATA);
            info.mMimeType = getString(info.mMimeType, Downloads.Impl.COLUMN_MIME_TYPE);
            info.mDestination = getInt(Downloads.Impl.COLUMN_DESTINATION);
            info.mVisibility = getInt(Downloads.Impl.COLUMN_VISIBILITY);
            info.mStatus = getInt(Downloads.Impl.COLUMN_STATUS);
            info.mNumFailed = getInt(Constants.FAILED_CONNECTIONS);
            int retryRedirect = getInt(Constants.RETRY_AFTER_X_REDIRECT_COUNT);
            info.mRetryAfter = retryRedirect & 0xfffffff;
            info.mRedirectCount = retryRedirect >> 28;
            info.mLastMod = getLong(Downloads.Impl.COLUMN_LAST_MODIFICATION);
            info.mPackage = getString(info.mPackage, Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE);
            info.mClass = getString(info.mClass, Downloads.Impl.COLUMN_NOTIFICATION_CLASS);
            info.mExtras = getString(info.mExtras, Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS);
            info.mCookies = getString(info.mCookies, Downloads.Impl.COLUMN_COOKIE_DATA);
            info.mUserAgent = getString(info.mUserAgent, Downloads.Impl.COLUMN_USER_AGENT);
            info.mReferer = getString(info.mReferer, Downloads.Impl.COLUMN_REFERER);
            info.mTotalBytes = getLong(Downloads.Impl.COLUMN_TOTAL_BYTES);
            info.mCurrentBytes = getLong(Downloads.Impl.COLUMN_CURRENT_BYTES);
            info.mETag = getString(info.mETag, Constants.ETAG);
            info.mMediaScanned = getInt(Constants.MEDIA_SCANNED) == 1;
            info.mIsPublicApi = getInt(Downloads.Impl.COLUMN_IS_PUBLIC_API) != 0;
            info.mAllowedNetworkTypes = getInt(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES);
            info.mAllowRoaming = getInt(Downloads.Impl.COLUMN_ALLOW_ROAMING) != 0;
            info.mTitle = getString(info.mTitle, Downloads.Impl.COLUMN_TITLE);
            info.mDescription = getString(info.mDescription, Downloads.Impl.COLUMN_DESCRIPTION);

            synchronized (this) {
                info.mControl = getInt(Downloads.Impl.COLUMN_CONTROL);
            }
        }

        private void readRequestHeaders(DownloadInfo info) {
            info.mRequestHeaders.clear();
            Uri headerUri = Uri.withAppendedPath(
                    info.getAllDownloadsUri(), Downloads.Impl.RequestHeaders.URI_SEGMENT);
            Cursor cursor = mResolver.query(headerUri, null, null, null, null);
            try {
                int headerIndex =
                        cursor.getColumnIndexOrThrow(Downloads.Impl.RequestHeaders.COLUMN_HEADER);
                int valueIndex =
                        cursor.getColumnIndexOrThrow(Downloads.Impl.RequestHeaders.COLUMN_VALUE);
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    info.mRequestHeaders.put(
                            cursor.getString(headerIndex), cursor.getString(valueIndex));
                }
            } finally {
                cursor.close();
            }

            if (info.mCookies != null) {
                info.mRequestHeaders.put("Cookie", info.mCookies);
            }
            if (info.mReferer != null) {
                info.mRequestHeaders.put("Referer", info.mReferer);
            }
        }

        /**
         * Returns a String that holds the current value of the column, optimizing for the case
         * where the value hasn't changed.
         */
        private String getString(String old, String column) {
            int index = mCursor.getColumnIndexOrThrow(column);
            if (old == null) {
                return mCursor.getString(index);
            }
            if (mNewChars == null) {
                mNewChars = new CharArrayBuffer(128);
            }
            mCursor.copyStringToBuffer(index, mNewChars);
            int length = mNewChars.sizeCopied;
            if (length != old.length()) {
                return new String(mNewChars.data, 0, length);
            }
            if (mOldChars == null || mOldChars.sizeCopied < length) {
                mOldChars = new CharArrayBuffer(length);
            }
            char[] oldArray = mOldChars.data;
            char[] newArray = mNewChars.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;
        }

        private Integer getInt(String column) {
            return mCursor.getInt(mCursor.getColumnIndexOrThrow(column));
        }

        private Long getLong(String column) {
            return mCursor.getLong(mCursor.getColumnIndexOrThrow(column));
        }
    }

    public long mId;
    public String mUri;
    public boolean mNoIntegrity;
    public String mHint;
    public String mFileName;
    public String mMimeType;
    public int mDestination;
    public int mVisibility;
    public int mControl;
    public int mStatus;
    public int mNumFailed;
    public int mRetryAfter;
    public int mRedirectCount;
    public long mLastMod;
    public String mPackage;
    public String mClass;
    public String mExtras;
    public String mCookies;
    public String mUserAgent;
    public String mReferer;
    public long mTotalBytes;
    public long mCurrentBytes;
    public String mETag;
    public boolean mMediaScanned;
    public boolean mIsPublicApi;
    public int mAllowedNetworkTypes;
    public boolean mAllowRoaming;
    public String mTitle;
    public String mDescription;
    public String mPausedReason;

    public int mFuzz;

    public volatile boolean mHasActiveThread;

    private Map<String, String> mRequestHeaders = new HashMap<String, String>();
    private SystemFacade mSystemFacade;
    private Context mContext;

    private DownloadInfo(Context context, SystemFacade systemFacade) {
        mContext = context;
        mSystemFacade = systemFacade;
        mFuzz = Helpers.sRandom.nextInt(1001);
    }

    public Map<String, String> getHeaders() {
        return Collections.unmodifiableMap(mRequestHeaders);
    }

    public void sendIntentIfRequested() {
        if (mPackage == null) {
            return;
        }

        Intent intent;
        if (mIsPublicApi) {
            intent = new Intent(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            intent.setPackage(mPackage);
            intent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, mId);
        } else { // legacy behavior
            if (mClass == null) {
                return;
            }
            intent = new Intent(Downloads.Impl.ACTION_DOWNLOAD_COMPLETED);
            intent.setClassName(mPackage, mClass);
            if (mExtras != null) {
                intent.putExtra(Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS, mExtras);
            }
            // 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(getMyDownloadsUri());
        }
        mSystemFacade.sendBroadcast(intent);
    }

    /**
     * Returns the time when a download should be restarted. Must only
     * be called when numFailed > 0.
     */
    public long restartTime() {
        if (mRetryAfter > 0) {
            return mLastMod + mRetryAfter;
        }
        return mLastMod +
                Constants.RETRY_FIRST_DELAY *
                    (1000 + mFuzz) * (1 << (mNumFailed - 1));
    }

    /**
     * Returns whether this download (which the download manager hasn't seen yet)
     * should be started.
     */
    public boolean isReadyToStart(long now) {
        if (mControl == Downloads.Impl.CONTROL_PAUSED) {
            // the download is paused, so it's not going to start
            return false;
        }
        if (mStatus == 0) {
            // status hasn't been initialized yet, this is a new download
            return true;
        }
        if (mStatus == Downloads.Impl.STATUS_PENDING) {
            // download is explicit marked as ready to start
            return true;
        }
        if (mStatus == Downloads.Impl.STATUS_RUNNING) {
            // download was interrupted (process killed, loss of power) while it was running,
            //     without a chance to update the database
            return true;
        }
        if (mStatus == Downloads.Impl.STATUS_RUNNING_PAUSED) {
            if (mNumFailed == 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 (mControl == Downloads.Impl.CONTROL_PAUSED) {
            // the download is paused, so it's not going to restart
            return false;
        }
        if (mStatus == 0) {
            // download hadn't been initialized yet
            return true;
        }
        if (mStatus == Downloads.Impl.STATUS_PENDING) {
            // download is explicit marked as ready to start
            return true;
        }
        if (mStatus == Downloads.Impl.STATUS_RUNNING_PAUSED) {
            if (mNumFailed == 0) {
                // download is waiting for network connectivity to return before it can resume
                return canUseNetwork();
            }
            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.Impl.isStatusCompleted(mStatus)) {
            return false;
        }
        if (mVisibility == Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) {
            return true;
        }
        return false;
    }

    /**
     * Returns whether this download is allowed to use the network.
     */
    public boolean canUseNetwork() {
        Integer networkType = mSystemFacade.getActiveNetworkType();
        if (networkType == null) {
            return false;
        }
        if (!isNetworkTypeAllowed(networkType)) {
            return false;
        }
        if (!isRoamingAllowed() && mSystemFacade.isNetworkRoaming()) {
            return false;
        }
        return true;
    }

    private boolean isRoamingAllowed() {
        if (mIsPublicApi) {
            return mAllowRoaming;
        } else { // legacy behavior
            return mDestination != Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING;
        }
    }

    /**
     * Check if this download can proceed over the given network type.
     * @param networkType a constant from ConnectivityManager.TYPE_*.
     */
    private boolean isNetworkTypeAllowed(int networkType) {
        if (mIsPublicApi) {
            int flag = translateNetworkTypeToApiFlag(networkType);
            if ((flag & mAllowedNetworkTypes) == 0) {
                return false;
            }
        }
        if (!isSizeAllowedForNetwork(networkType)) {
            mPausedReason = mContext.getResources().getString(
                    R.string.notification_need_wifi_for_size);
            return false;
        }
        return true;
    }

    /**
     * Translate a ConnectivityManager.TYPE_* constant to the corresponding
     * DownloadManager.Request.NETWORK_* bit flag.
     */
    private int translateNetworkTypeToApiFlag(int networkType) {
        switch (networkType) {
            case ConnectivityManager.TYPE_MOBILE:
                return DownloadManager.Request.NETWORK_MOBILE;

            case ConnectivityManager.TYPE_WIFI:
                return DownloadManager.Request.NETWORK_WIFI;

            case ConnectivityManager.TYPE_WIMAX:
                return DownloadManager.Request.NETWORK_WIMAX;

            default:
                return 0;
        }
    }

    /**
     * Check if the download's size prohibits it from running over the current network.
     */
    private boolean isSizeAllowedForNetwork(int networkType) {
        if (mTotalBytes <= 0) {
            return true; // we don't know the size yet
        }
        if (networkType == ConnectivityManager.TYPE_WIFI) {
            return true; // anything goes over wifi
        }
        Long maxBytesOverMobile = mSystemFacade.getMaxBytesOverMobile();
        if (maxBytesOverMobile == null) {
            return true; // no limit
        }
        return mTotalBytes <= maxBytesOverMobile;
    }

    void start(long now) {
        if (Constants.LOGV) {
            Log.v(Constants.TAG, "Service spawning thread to handle download " + mId);
        }
        if (mHasActiveThread) {
            throw new IllegalStateException("Multiple threads on same download");
        }
        if (mStatus != Impl.STATUS_RUNNING) {
            mStatus = Impl.STATUS_RUNNING;
            ContentValues values = new ContentValues();
            values.put(Impl.COLUMN_STATUS, mStatus);
            mContext.getContentResolver().update(getAllDownloadsUri(), values, null, null);
        }
        DownloadThread downloader = new DownloadThread(mContext, mSystemFacade, this);
        mHasActiveThread = true;
        mSystemFacade.startThread(downloader);
    }

    public boolean isOnCache() {
        return (mDestination == Downloads.Impl.DESTINATION_CACHE_PARTITION
                || mDestination == Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING
                || mDestination == Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
    }

    public Uri getMyDownloadsUri() {
        return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, mId);
    }

    public Uri getAllDownloadsUri() {
        return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, mId);
    }


    public void logVerboseInfo() {
        Log.v(Constants.TAG, "Service adding new entry");
        Log.v(Constants.TAG, "ID      : " + mId);
        Log.v(Constants.TAG, "URI     : " + ((mUri != null) ? "yes" : "no"));
        Log.v(Constants.TAG, "NO_INTEG: " + mNoIntegrity);
        Log.v(Constants.TAG, "HINT    : " + mHint);
        Log.v(Constants.TAG, "FILENAME: " + mFileName);
        Log.v(Constants.TAG, "MIMETYPE: " + mMimeType);
        Log.v(Constants.TAG, "DESTINAT: " + mDestination);
        Log.v(Constants.TAG, "VISIBILI: " + mVisibility);
        Log.v(Constants.TAG, "CONTROL : " + mControl);
        Log.v(Constants.TAG, "STATUS  : " + mStatus);
        Log.v(Constants.TAG, "FAILED_C: " + mNumFailed);
        Log.v(Constants.TAG, "RETRY_AF: " + mRetryAfter);
        Log.v(Constants.TAG, "REDIRECT: " + mRedirectCount);
        Log.v(Constants.TAG, "LAST_MOD: " + mLastMod);
        Log.v(Constants.TAG, "PACKAGE : " + mPackage);
        Log.v(Constants.TAG, "CLASS   : " + mClass);
        Log.v(Constants.TAG, "COOKIES : " + ((mCookies != null) ? "yes" : "no"));
        Log.v(Constants.TAG, "AGENT   : " + mUserAgent);
        Log.v(Constants.TAG, "REFERER : " + ((mReferer != null) ? "yes" : "no"));
        Log.v(Constants.TAG, "TOTAL   : " + mTotalBytes);
        Log.v(Constants.TAG, "CURRENT : " + mCurrentBytes);
        Log.v(Constants.TAG, "ETAG    : " + mETag);
        Log.v(Constants.TAG, "SCANNED : " + mMediaScanned);
    }

    /**
     * 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"
     */
    long nextAction(long now) {
        if (Downloads.Impl.isStatusCompleted(mStatus)) {
            return -1;
        }
        if (mStatus != Downloads.Impl.STATUS_RUNNING_PAUSED) {
            return 0;
        }
        if (mNumFailed == 0) {
            return 0;
        }
        long when = restartTime();
        if (when <= now) {
            return 0;
        }
        return when - now;
    }

    /**
     * Returns whether a file should be scanned
     */
    boolean shouldScanFile() {
        return !mMediaScanned
                && mDestination == Downloads.Impl.DESTINATION_EXTERNAL
                && Downloads.Impl.isStatusSuccess(mStatus)
                && !DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(mMimeType);
    }
}