blob: 84e67c0900764ad8128e9c4256f2c09854ca31e7 [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -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 com.android.browser;
18
19import android.app.Activity;
20import android.app.AlertDialog;
21import android.app.DownloadManager;
22import android.content.ActivityNotFoundException;
23import android.content.ComponentName;
Michael Kolb8233fac2010-10-26 16:08:53 -070024import android.content.Context;
25import android.content.Intent;
26import android.content.pm.PackageManager;
27import android.content.pm.ResolveInfo;
28import android.net.Uri;
29import android.net.WebAddress;
30import android.os.Environment;
LuK13372be2de92015-12-17 21:32:46 +080031import android.support.v4.app.ActivityCompat;
32import android.support.v4.content.ContextCompat;
Leon Scroggins63c02662010-11-18 15:16:27 -050033import android.text.TextUtils;
Michael Kolb8233fac2010-10-26 16:08:53 -070034import android.util.Log;
35import android.webkit.CookieManager;
36import android.webkit.URLUtil;
37import android.widget.Toast;
38
39/**
40 * Handle download requests
41 */
42public class DownloadHandler {
43
44 private static final boolean LOGD_ENABLED =
45 com.android.browser.Browser.LOGD_ENABLED;
46
47 private static final String LOGTAG = "DLHandler";
48
LuK13372be2de92015-12-17 21:32:46 +080049 //Singleton to hold the information about any pending downloads
50 private static PendingDownloadBundle pendingDownloadBundle;
51
52 private static class PendingDownloadBundle {
53 String url;
54 String userAgent;
55 String contentDisposition;
56 String mimetype;
57 String referer;
58 boolean privateBrowsing;
59
60 public static PendingDownloadBundle create(String url, String userAgent,
61 String contentDisposition, String mimetype, String referer,
62 boolean privateBrowsing) {
63 PendingDownloadBundle pdb = new PendingDownloadBundle();
64 pdb.url = url;
65 pdb.userAgent = userAgent;
66 pdb.contentDisposition = contentDisposition;
67 pdb.mimetype = mimetype;
68 pdb.referer = referer;
69 pdb.privateBrowsing = privateBrowsing;
70 return pdb;
71 }
72 }
73
74 /**
75 * Check if there is any pending download and start the download automatically in case
76 * there is one.
77 * @param activity Activity requesting the download.
78 */
79 public static void checkPendingDownloads(Activity activity) {
80 if (pendingDownloadBundle != null) {
81 onDownloadStartNoStream(activity, pendingDownloadBundle.url,
82 pendingDownloadBundle.userAgent, pendingDownloadBundle.contentDisposition,
83 pendingDownloadBundle.mimetype, pendingDownloadBundle.referer,
84 pendingDownloadBundle.privateBrowsing);
85 pendingDownloadBundle = null;
86 }
87 }
88
Michael Kolb8233fac2010-10-26 16:08:53 -070089 /**
90 * Notify the host application a download should be done, or that
91 * the data should be streamed if a streaming viewer is available.
Leon Scroggins63c02662010-11-18 15:16:27 -050092 * @param activity Activity requesting the download.
Michael Kolb8233fac2010-10-26 16:08:53 -070093 * @param url The full url to the content that should be downloaded
Leon Scroggins63c02662010-11-18 15:16:27 -050094 * @param userAgent User agent of the downloading application.
95 * @param contentDisposition Content-disposition http header, if present.
Michael Kolb8233fac2010-10-26 16:08:53 -070096 * @param mimetype The mimetype of the content reported by the server
Selim Gurun0b3d66f2012-08-29 13:08:13 -070097 * @param referer The referer associated with the downloaded url
Kristian Monsenbc5cc752011-03-02 13:14:03 +000098 * @param privateBrowsing If the request is coming from a private browsing tab.
Michael Kolb8233fac2010-10-26 16:08:53 -070099 */
Leon Scroggins63c02662010-11-18 15:16:27 -0500100 public static void onDownloadStart(Activity activity, String url,
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000101 String userAgent, String contentDisposition, String mimetype,
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700102 String referer, boolean privateBrowsing) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700103 // if we're dealing wih A/V content that's not explicitly marked
104 // for download, check if it's streamable.
105 if (contentDisposition == null
106 || !contentDisposition.regionMatches(
107 true, 0, "attachment", 0, 10)) {
108 // query the package manager to see if there's a registered handler
109 // that matches.
110 Intent intent = new Intent(Intent.ACTION_VIEW);
111 intent.setDataAndType(Uri.parse(url), mimetype);
Leon Scroggins63c02662010-11-18 15:16:27 -0500112 ResolveInfo info = activity.getPackageManager().resolveActivity(intent,
Michael Kolb8233fac2010-10-26 16:08:53 -0700113 PackageManager.MATCH_DEFAULT_ONLY);
114 if (info != null) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500115 ComponentName myName = activity.getComponentName();
Michael Kolb8233fac2010-10-26 16:08:53 -0700116 // If we resolved to ourselves, we don't want to attempt to
117 // load the url only to try and download it again.
118 if (!myName.getPackageName().equals(
119 info.activityInfo.packageName)
120 || !myName.getClassName().equals(
121 info.activityInfo.name)) {
122 // someone (other than us) knows how to handle this mime
123 // type with this scheme, don't download.
124 try {
Leon Scroggins63c02662010-11-18 15:16:27 -0500125 activity.startActivity(intent);
Michael Kolb8233fac2010-10-26 16:08:53 -0700126 return;
127 } catch (ActivityNotFoundException ex) {
128 if (LOGD_ENABLED) {
129 Log.d(LOGTAG, "activity not found for " + mimetype
130 + " over " + Uri.parse(url).getScheme(),
131 ex);
132 }
133 // Best behavior is to fall back to a download in this
134 // case
135 }
136 }
137 }
138 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500139 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700140 mimetype, referer, privateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -0700141 }
142
143 // This is to work around the fact that java.net.URI throws Exceptions
144 // instead of just encoding URL's properly
145 // Helper method for onDownloadStartNoStream
146 private static String encodePath(String path) {
147 char[] chars = path.toCharArray();
148
149 boolean needed = false;
150 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700151 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700152 needed = true;
153 break;
154 }
155 }
156 if (needed == false) {
157 return path;
158 }
159
160 StringBuilder sb = new StringBuilder("");
161 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700162 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700163 sb.append('%');
164 sb.append(Integer.toHexString(c));
165 } else {
166 sb.append(c);
167 }
168 }
169
170 return sb.toString();
171 }
172
173 /**
174 * Notify the host application a download should be done, even if there
LuK13372be2de92015-12-17 21:32:46 +0800175 * is a streaming viewer available for this type.
Leon Scroggins63c02662010-11-18 15:16:27 -0500176 * @param activity Activity requesting the download.
Michael Kolb8233fac2010-10-26 16:08:53 -0700177 * @param url The full url to the content that should be downloaded
Leon Scroggins63c02662010-11-18 15:16:27 -0500178 * @param userAgent User agent of the downloading application.
179 * @param contentDisposition Content-disposition http header, if present.
Michael Kolb8233fac2010-10-26 16:08:53 -0700180 * @param mimetype The mimetype of the content reported by the server
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700181 * @param referer The referer associated with the downloaded url
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000182 * @param privateBrowsing If the request is coming from a private browsing tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700183 */
Leon Scroggins63c02662010-11-18 15:16:27 -0500184 /*package */ static void onDownloadStartNoStream(Activity activity,
185 String url, String userAgent, String contentDisposition,
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700186 String mimetype, String referer, boolean privateBrowsing) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700187
LuK13372be2de92015-12-17 21:32:46 +0800188 // Check permissions first when download will be start.
189 int permissionCheck = ContextCompat.checkSelfPermission(activity,
190 android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
191 if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
192 onDownloadNoStreamImpl(activity, url, userAgent, contentDisposition,
193 mimetype, referer, privateBrowsing);
194 } else {
195 pendingDownloadBundle = PendingDownloadBundle.create(url, userAgent,
196 contentDisposition, mimetype, referer, privateBrowsing);
197 // Permission not granted, request it from the user
198 ActivityCompat.requestPermissions(activity,
199 new String[] {android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
200 BrowserActivity.PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
201 }
202 }
203
204 private static void onDownloadNoStreamImpl(Activity activity,
205 String url, String userAgent, String contentDisposition,
206 String mimetype, String referer, boolean privateBrowsing) {
207
Michael Kolb8233fac2010-10-26 16:08:53 -0700208 String filename = URLUtil.guessFileName(url,
209 contentDisposition, mimetype);
210
211 // Check to see if we have an SDCard
212 String status = Environment.getExternalStorageState();
213 if (!status.equals(Environment.MEDIA_MOUNTED)) {
214 int title;
215 String msg;
216
217 // Check to see if the SDCard is busy, same as the music app
218 if (status.equals(Environment.MEDIA_SHARED)) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500219 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
Michael Kolb8233fac2010-10-26 16:08:53 -0700220 title = R.string.download_sdcard_busy_dlg_title;
221 } else {
Leon Scroggins63c02662010-11-18 15:16:27 -0500222 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700223 title = R.string.download_no_sdcard_dlg_title;
224 }
225
Leon Scroggins63c02662010-11-18 15:16:27 -0500226 new AlertDialog.Builder(activity)
Michael Kolb8233fac2010-10-26 16:08:53 -0700227 .setTitle(title)
Björn Lundén2aa8ba22012-05-31 23:05:56 +0200228 .setIconAttribute(android.R.attr.alertDialogIcon)
Michael Kolb8233fac2010-10-26 16:08:53 -0700229 .setMessage(msg)
230 .setPositiveButton(R.string.ok, null)
231 .show();
232 return;
233 }
234
235 // java.net.URI is a lot stricter than KURL so we have to encode some
236 // extra characters. Fix for b 2538060 and b 1634719
237 WebAddress webAddress;
238 try {
239 webAddress = new WebAddress(url);
240 webAddress.setPath(encodePath(webAddress.getPath()));
241 } catch (Exception e) {
242 // This only happens for very bad urls, we want to chatch the
243 // exception here
244 Log.e(LOGTAG, "Exception trying to parse url:" + url);
245 return;
246 }
247
248 String addressString = webAddress.toString();
249 Uri uri = Uri.parse(addressString);
Leon Scroggins11e309c2011-02-01 13:37:14 -0500250 final DownloadManager.Request request;
251 try {
252 request = new DownloadManager.Request(uri);
253 } catch (IllegalArgumentException e) {
254 Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
255 return;
256 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700257 request.setMimeType(mimetype);
Vasu Noric2df8342010-12-18 20:15:46 -0800258 // set downloaded file destination to /sdcard/Download.
259 // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
Filip Matusiakc499ca92012-08-23 15:05:05 +0200260 try {
261 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
262 } catch (IllegalStateException ex) {
263 // This only happens when directory Downloads can't be created or it isn't a directory
264 // this is most commonly due to temporary problems with sdcard so show appropriate string
265 Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
266 Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title,
267 Toast.LENGTH_SHORT).show();
268 return;
269 }
270 // let this downloaded file be scanned by MediaScanner - so that it can
Michael Kolb8233fac2010-10-26 16:08:53 -0700271 // show up in Gallery app, for example.
272 request.allowScanningByMediaScanner();
273 request.setDescription(webAddress.getHost());
Leon Scroggins63c02662010-11-18 15:16:27 -0500274 // XXX: Have to use the old url since the cookies were stored using the
275 // old percent-encoded url.
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000276 String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
Michael Kolb8233fac2010-10-26 16:08:53 -0700277 request.addRequestHeader("cookie", cookies);
Patrik Stenkilssond0fc5892012-02-14 09:33:24 +0100278 request.addRequestHeader("User-Agent", userAgent);
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700279 request.addRequestHeader("Referer", referer);
Michael Kolb8233fac2010-10-26 16:08:53 -0700280 request.setNotificationVisibility(
281 DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
282 if (mimetype == null) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500283 if (TextUtils.isEmpty(addressString)) {
284 return;
285 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700286 // We must have long pressed on a link or image to download it. We
287 // are not sure of the mimetype in this case, so do a head request
Leon Scroggins63c02662010-11-18 15:16:27 -0500288 new FetchUrlMimeType(activity, request, addressString, cookies,
289 userAgent).start();
Michael Kolb8233fac2010-10-26 16:08:53 -0700290 } else {
Leon Scroggins63c02662010-11-18 15:16:27 -0500291 final DownloadManager manager
292 = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
293 new Thread("Browser download") {
294 public void run() {
295 manager.enqueue(request);
296 }
297 }.start();
Michael Kolb8233fac2010-10-26 16:08:53 -0700298 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500299 Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT)
Michael Kolb8233fac2010-10-26 16:08:53 -0700300 .show();
301 }
302
303}