1/*
2 * Copyright (C) 2012 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 com.android.providers.downloads;
18
19import static android.app.DownloadManager.COLUMN_LOCAL_FILENAME;
20import static android.app.DownloadManager.COLUMN_LOCAL_URI;
21import static android.app.DownloadManager.COLUMN_MEDIA_TYPE;
22import static android.app.DownloadManager.COLUMN_URI;
23import static android.provider.Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
24import static com.android.providers.downloads.Constants.TAG;
25
26import android.app.DownloadManager;
27import android.content.ActivityNotFoundException;
28import android.content.ContentUris;
29import android.content.Context;
30import android.content.Intent;
31import android.database.Cursor;
32import android.net.Uri;
33import android.provider.Downloads.Impl.RequestHeaders;
34import android.util.Log;
35
36import java.io.File;
37
38public class OpenHelper {
39    /**
40     * Build and start an {@link Intent} to view the download with given ID,
41     * handling subtleties around installing packages.
42     */
43    public static boolean startViewIntent(Context context, long id, int intentFlags) {
44        final Intent intent = OpenHelper.buildViewIntent(context, id);
45        if (intent == null) {
46            Log.w(TAG, "No intent built for " + id);
47            return false;
48        }
49
50        intent.addFlags(intentFlags);
51        try {
52            context.startActivity(intent);
53            return true;
54        } catch (ActivityNotFoundException e) {
55            Log.w(TAG, "Failed to start " + intent + ": " + e);
56            return false;
57        }
58    }
59
60    /**
61     * Build an {@link Intent} to view the download with given ID, handling
62     * subtleties around installing packages.
63     */
64    private static Intent buildViewIntent(Context context, long id) {
65        final DownloadManager downManager = (DownloadManager) context.getSystemService(
66                Context.DOWNLOAD_SERVICE);
67        downManager.setAccessAllDownloads(true);
68
69        final Cursor cursor = downManager.query(new DownloadManager.Query().setFilterById(id));
70        try {
71            if (!cursor.moveToFirst()) {
72                return null;
73            }
74
75            final Uri localUri = getCursorUri(cursor, COLUMN_LOCAL_URI);
76            final File file = getCursorFile(cursor, COLUMN_LOCAL_FILENAME);
77            String mimeType = getCursorString(cursor, COLUMN_MEDIA_TYPE);
78            mimeType = DownloadDrmHelper.getOriginalMimeType(context, file, mimeType);
79
80            final Intent intent = new Intent(Intent.ACTION_VIEW);
81
82            if ("application/vnd.android.package-archive".equals(mimeType)) {
83                // PackageInstaller doesn't like content URIs, so open file
84                intent.setDataAndType(localUri, mimeType);
85
86                // Also splice in details about where it came from
87                final Uri remoteUri = getCursorUri(cursor, COLUMN_URI);
88                intent.putExtra(Intent.EXTRA_ORIGINATING_URI, remoteUri);
89                intent.putExtra(Intent.EXTRA_REFERRER, getRefererUri(context, id));
90                intent.putExtra(Intent.EXTRA_ORIGINATING_UID, getOriginatingUid(context, id));
91            } else if ("file".equals(localUri.getScheme())) {
92                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
93                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
94                intent.setDataAndType(
95                        ContentUris.withAppendedId(ALL_DOWNLOADS_CONTENT_URI, id), mimeType);
96            } else {
97                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
98                intent.setDataAndType(localUri, mimeType);
99            }
100
101            return intent;
102        } finally {
103            cursor.close();
104        }
105    }
106
107    private static Uri getRefererUri(Context context, long id) {
108        final Uri headersUri = Uri.withAppendedPath(
109                ContentUris.withAppendedId(ALL_DOWNLOADS_CONTENT_URI, id),
110                RequestHeaders.URI_SEGMENT);
111        final Cursor headers = context.getContentResolver()
112                .query(headersUri, null, null, null, null);
113        try {
114            while (headers.moveToNext()) {
115                final String header = getCursorString(headers, RequestHeaders.COLUMN_HEADER);
116                if ("Referer".equalsIgnoreCase(header)) {
117                    return getCursorUri(headers, RequestHeaders.COLUMN_VALUE);
118                }
119            }
120        } finally {
121            headers.close();
122        }
123        return null;
124    }
125
126    private static int getOriginatingUid(Context context, long id) {
127        final Uri uri = ContentUris.withAppendedId(ALL_DOWNLOADS_CONTENT_URI, id);
128        final Cursor cursor = context.getContentResolver().query(uri, new String[]{Constants.UID},
129                null, null, null);
130        if (cursor != null) {
131            try {
132                if (cursor.moveToFirst()) {
133                    return cursor.getInt(cursor.getColumnIndexOrThrow(Constants.UID));
134                }
135            } finally {
136                cursor.close();
137            }
138        }
139        return -1;
140    }
141
142    private static String getCursorString(Cursor cursor, String column) {
143        return cursor.getString(cursor.getColumnIndexOrThrow(column));
144    }
145
146    private static Uri getCursorUri(Cursor cursor, String column) {
147        return Uri.parse(getCursorString(cursor, column));
148    }
149
150    private static File getCursorFile(Cursor cursor, String column) {
151        return new File(cursor.getString(cursor.getColumnIndexOrThrow(column)));
152    }
153}
154