blob: 3562f809a262b3f97eebd0db046c4c1c40bdabe8 [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
Bijan Amirzada41242f22014-03-21 12:12:18 -070017package com.android.browser;
Michael Kolb8233fac2010-10-26 16:08:53 -070018
19import android.app.Activity;
20import android.app.AlertDialog;
21import android.app.DownloadManager;
luxiaol62677b02013-07-22 07:54:49 +080022import android.app.DownloadManager.Request;
Michael Kolb8233fac2010-10-26 16:08:53 -070023import android.content.ActivityNotFoundException;
24import android.content.ComponentName;
Michael Kolb8233fac2010-10-26 16:08:53 -070025import android.content.Context;
qqzhoua95a2e22013-04-18 17:28:31 +080026import android.content.DialogInterface;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.Intent;
28import android.content.pm.PackageManager;
29import android.content.pm.ResolveInfo;
30import android.net.Uri;
luxiaol62677b02013-07-22 07:54:49 +080031import android.os.Bundle;
Michael Kolb8233fac2010-10-26 16:08:53 -070032import android.os.Environment;
luxiaol62677b02013-07-22 07:54:49 +080033import android.os.StatFs;
34import android.os.storage.StorageManager;
Pankaj Garg5762b362015-11-02 07:57:06 -080035import android.text.TextUtils;
Michael Kolb8233fac2010-10-26 16:08:53 -070036import android.util.Log;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080037import org.codeaurora.swe.CookieManager;
Pankaj Garg5762b362015-11-02 07:57:06 -080038import org.w3c.dom.Text;
39
Michael Kolb8233fac2010-10-26 16:08:53 -070040import android.webkit.URLUtil;
41import android.widget.Toast;
42
Bijan Amirzada41242f22014-03-21 12:12:18 -070043import com.android.browser.R;
Dave Tharp13f3f7c2015-07-16 14:58:51 -070044import com.android.browser.mdm.DownloadDirRestriction;
Bijan Amirzada41242f22014-03-21 12:12:18 -070045import com.android.browser.platformsupport.WebAddress;
46import com.android.browser.reflect.ReflectHelper;
luxiaol62677b02013-07-22 07:54:49 +080047
Axesh R. Ajmera2e241242014-05-19 15:53:38 -070048import java.util.regex.Matcher;
49import java.util.regex.Pattern;
50
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080051import java.io.File;
Michael Kolb8233fac2010-10-26 16:08:53 -070052/**
53 * Handle download requests
54 */
55public class DownloadHandler {
56
57 private static final boolean LOGD_ENABLED =
Bijan Amirzada41242f22014-03-21 12:12:18 -070058 com.android.browser.Browser.LOGD_ENABLED;
Michael Kolb8233fac2010-10-26 16:08:53 -070059
60 private static final String LOGTAG = "DLHandler";
luxiaol62677b02013-07-22 07:54:49 +080061 private static String mInternalStorage;
62 private static String mExternalStorage;
63 private final static String INVALID_PATH = "/storage";
Michael Kolb8233fac2010-10-26 16:08:53 -070064
luxiaol62677b02013-07-22 07:54:49 +080065 public static void startingDownload(Activity activity,
66 String url, String userAgent, String contentDisposition,
Pankaj Garg5762b362015-11-02 07:57:06 -080067 String mimetype, String referer, String auth,
68 boolean privateBrowsing, long contentLength,
luxiaol62677b02013-07-22 07:54:49 +080069 String filename, String downloadPath) {
70 // java.net.URI is a lot stricter than KURL so we have to encode some
71 // extra characters. Fix for b 2538060 and b 1634719
72 WebAddress webAddress;
73 try {
74 webAddress = new WebAddress(url);
75 webAddress.setPath(encodePath(webAddress.getPath()));
76 } catch (Exception e) {
77 // This only happens for very bad urls, we want to chatch the
78 // exception here
79 Log.e(LOGTAG, "Exception trying to parse url:" + url);
80 return;
81 }
82
83 String addressString = webAddress.toString();
84 Uri uri = Uri.parse(addressString);
85 final DownloadManager.Request request;
86 try {
87 request = new DownloadManager.Request(uri);
88 } catch (IllegalArgumentException e) {
89 Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
90 return;
91 }
92 request.setMimeType(mimetype);
93 // set downloaded file destination to /sdcard/Download.
94 // or, should it be set to one of several Environment.DIRECTORY* dirs
95 // depending on mimetype?
96 try {
97 setDestinationDir(downloadPath, filename, request);
98 } catch (Exception e) {
99 showNoEnoughMemoryDialog(activity);
100 return;
101 }
102 // let this downloaded file be scanned by MediaScanner - so that it can
103 // show up in Gallery app, for example.
104 request.allowScanningByMediaScanner();
105 request.setDescription(webAddress.getHost());
106 // XXX: Have to use the old url since the cookies were stored using the
107 // old percent-encoded url.
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800108
luxiaol62677b02013-07-22 07:54:49 +0800109 String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
110 request.addRequestHeader("cookie", cookies);
111 request.addRequestHeader("User-Agent", userAgent);
112 request.addRequestHeader("Referer", referer);
Panos Thomase57e3a02014-04-30 20:25:16 -0700113 request.setVisibleInDownloadsUi(!privateBrowsing);
Pankaj Garg5762b362015-11-02 07:57:06 -0800114 if (!TextUtils.isEmpty(auth)) {
115 request.addRequestHeader("Authorization", auth);
116 }
luxiaol62677b02013-07-22 07:54:49 +0800117 request.setNotificationVisibility(
118 DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
119 final DownloadManager manager = (DownloadManager) activity
120 .getSystemService(Context.DOWNLOAD_SERVICE);
121 new Thread("Browser download") {
122 public void run() {
Vivek Sekhar40713382014-06-11 14:29:32 -0700123 try {
124 manager.enqueue(request);
125 } catch (Exception e) {
126 Log.w("DLHandler", "Could not enqueue the download", e);
127 }
luxiaol62677b02013-07-22 07:54:49 +0800128 }
129 }.start();
Panos Thomase57e3a02014-04-30 20:25:16 -0700130 showStartDownloadToast(activity, privateBrowsing);
luxiaol62677b02013-07-22 07:54:49 +0800131 }
132
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800133 private static boolean isAudioFileType(int fileType){
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700134 Object[] params = {Integer.valueOf(fileType)};
135 Class[] type = new Class[] {int.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700136 Boolean result = (Boolean) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700137 "isAudioFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800138 return result;
139 }
140
141 private static boolean isVideoFileType(int fileType){
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700142 Object[] params = {Integer.valueOf(fileType)};
143 Class[] type = new Class[] {int.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700144 Boolean result = (Boolean) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700145 "isVideoFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800146 return result;
147 }
148
kaiyize6a27d02013-08-22 15:08:19 +0800149 /**
150 * Notify the host application a download should be done, or that
151 * the data should be streamed if a streaming viewer is available.
152 * @param activity Activity requesting the download.
153 * @param url The full url to the content that should be downloaded
154 * @param userAgent User agent of the downloading application.
155 * @param contentDisposition Content-disposition http header, if present.
156 * @param mimetype The mimetype of the content reported by the server
157 * @param referer The referer associated with the downloaded url
158 * @param privateBrowsing If the request is coming from a private browsing tab.
159 */
qqzhoua95a2e22013-04-18 17:28:31 +0800160 public static boolean onDownloadStart(final Activity activity, final String url,
161 final String userAgent, final String contentDisposition, final String mimetype,
Pankaj Garg5762b362015-11-02 07:57:06 -0800162 final String referer, final String auth, final boolean privateBrowsing,
163 final long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700164 // if we're dealing wih A/V content that's not explicitly marked
165 // for download, check if it's streamable.
166 if (contentDisposition == null
167 || !contentDisposition.regionMatches(
168 true, 0, "attachment", 0, 10)) {
qqzhoua95a2e22013-04-18 17:28:31 +0800169 // Add for Carrier Feature - When open an audio/video link, prompt a dialog
170 // to let the user choose play or download operation.
171 Uri uri = Uri.parse(url);
172 String scheme = uri.getScheme();
173 Log.v(LOGTAG, "scheme:" + scheme + ", mimetype:" + mimetype);
174 // Some mimetype for audio/video files is not started with "audio" or "video",
175 // such as ogg audio file with mimetype "application/ogg". So we also check
176 // file type by MediaFile.isAudioFileType() and MediaFile.isVideoFileType().
177 // For those file types other than audio or video, download it immediately.
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700178 Object[] params = {mimetype};
179 Class[] type = new Class[] {String.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700180 Integer result = (Integer) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700181 "getFileTypeForMimeType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800182 int fileType = result.intValue();
qqzhoua95a2e22013-04-18 17:28:31 +0800183 if ("http".equalsIgnoreCase(scheme) &&
184 (mimetype.startsWith("audio/") ||
185 mimetype.startsWith("video/") ||
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800186 isAudioFileType(fileType) ||
187 isVideoFileType(fileType))) {
qqzhoua95a2e22013-04-18 17:28:31 +0800188 new AlertDialog.Builder(activity)
189 .setTitle(R.string.application_name)
190 .setIcon(R.drawable.default_video_poster)
191 .setMessage(R.string.http_video_msg)
192 .setPositiveButton(R.string.video_save, new DialogInterface.OnClickListener() {
193 public void onClick(DialogInterface dialog, int which) {
194 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
Pankaj Garg5762b362015-11-02 07:57:06 -0800195 mimetype, referer, auth, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800196 }
197 })
198 .setNegativeButton(R.string.video_play, new DialogInterface.OnClickListener() {
199 public void onClick(DialogInterface dialog, int which) {
200 Intent intent = new Intent(Intent.ACTION_VIEW);
201 intent.setDataAndType(Uri.parse(url), mimetype);
202 try {
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700203 String trimmedcontentDisposition = trimContentDisposition(contentDisposition);
204 String title = URLUtil.guessFileName(url, trimmedcontentDisposition, mimetype);
qqzhoua95a2e22013-04-18 17:28:31 +0800205 intent.putExtra(Intent.EXTRA_TITLE, title);
206 activity.startActivity(intent);
207 } catch (ActivityNotFoundException ex) {
208 Log.w(LOGTAG, "When http stream play, activity not found for "
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700209 + mimetype + " over " + Uri.parse(url).getScheme(), ex);
qqzhoua95a2e22013-04-18 17:28:31 +0800210 }
211 }
212 }).show();
213
214 return true;
215 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700216 // query the package manager to see if there's a registered handler
217 // that matches.
218 Intent intent = new Intent(Intent.ACTION_VIEW);
219 intent.setDataAndType(Uri.parse(url), mimetype);
Leon Scroggins63c02662010-11-18 15:16:27 -0500220 ResolveInfo info = activity.getPackageManager().resolveActivity(intent,
Michael Kolb8233fac2010-10-26 16:08:53 -0700221 PackageManager.MATCH_DEFAULT_ONLY);
222 if (info != null) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500223 ComponentName myName = activity.getComponentName();
Michael Kolb8233fac2010-10-26 16:08:53 -0700224 // If we resolved to ourselves, we don't want to attempt to
225 // load the url only to try and download it again.
226 if (!myName.getPackageName().equals(
227 info.activityInfo.packageName)
228 || !myName.getClassName().equals(
229 info.activityInfo.name)) {
230 // someone (other than us) knows how to handle this mime
231 // type with this scheme, don't download.
232 try {
Leon Scroggins63c02662010-11-18 15:16:27 -0500233 activity.startActivity(intent);
qqzhoua95a2e22013-04-18 17:28:31 +0800234 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700235 } catch (ActivityNotFoundException ex) {
236 if (LOGD_ENABLED) {
237 Log.d(LOGTAG, "activity not found for " + mimetype
238 + " over " + Uri.parse(url).getScheme(),
239 ex);
240 }
241 // Best behavior is to fall back to a download in this
242 // case
243 }
244 }
245 }
246 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500247 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
Pankaj Garg5762b362015-11-02 07:57:06 -0800248 mimetype, referer, auth, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800249 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700250 }
251
252 // This is to work around the fact that java.net.URI throws Exceptions
253 // instead of just encoding URL's properly
254 // Helper method for onDownloadStartNoStream
255 private static String encodePath(String path) {
256 char[] chars = path.toCharArray();
257
258 boolean needed = false;
259 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700260 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700261 needed = true;
262 break;
263 }
264 }
265 if (needed == false) {
266 return path;
267 }
268
269 StringBuilder sb = new StringBuilder("");
270 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700271 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700272 sb.append('%');
273 sb.append(Integer.toHexString(c));
274 } else {
275 sb.append(c);
276 }
277 }
278
279 return sb.toString();
280 }
281
282 /**
283 * Notify the host application a download should be done, even if there
284 * is a streaming viewer available for thise type.
Leon Scroggins63c02662010-11-18 15:16:27 -0500285 * @param activity Activity requesting the download.
Michael Kolb8233fac2010-10-26 16:08:53 -0700286 * @param url The full url to the content that should be downloaded
Leon Scroggins63c02662010-11-18 15:16:27 -0500287 * @param userAgent User agent of the downloading application.
288 * @param contentDisposition Content-disposition http header, if present.
Michael Kolb8233fac2010-10-26 16:08:53 -0700289 * @param mimetype The mimetype of the content reported by the server
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700290 * @param referer The referer associated with the downloaded url
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000291 * @param privateBrowsing If the request is coming from a private browsing tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700292 */
luxiaol62677b02013-07-22 07:54:49 +0800293 /* package */static void onDownloadStartNoStream(Activity activity,
Leon Scroggins63c02662010-11-18 15:16:27 -0500294 String url, String userAgent, String contentDisposition,
Pankaj Garg5762b362015-11-02 07:57:06 -0800295 String mimetype, String referer, String auth,
296 boolean privateBrowsing, long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700297
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700298 contentDisposition = trimContentDisposition(contentDisposition);
299
Michael Kolb8233fac2010-10-26 16:08:53 -0700300 String filename = URLUtil.guessFileName(url,
301 contentDisposition, mimetype);
302
303 // Check to see if we have an SDCard
304 String status = Environment.getExternalStorageState();
305 if (!status.equals(Environment.MEDIA_MOUNTED)) {
306 int title;
307 String msg;
308
309 // Check to see if the SDCard is busy, same as the music app
310 if (status.equals(Environment.MEDIA_SHARED)) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500311 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
Michael Kolb8233fac2010-10-26 16:08:53 -0700312 title = R.string.download_sdcard_busy_dlg_title;
313 } else {
Leon Scroggins63c02662010-11-18 15:16:27 -0500314 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700315 title = R.string.download_no_sdcard_dlg_title;
316 }
317
Leon Scroggins63c02662010-11-18 15:16:27 -0500318 new AlertDialog.Builder(activity)
Michael Kolb8233fac2010-10-26 16:08:53 -0700319 .setTitle(title)
Björn Lundén2aa8ba22012-05-31 23:05:56 +0200320 .setIconAttribute(android.R.attr.alertDialogIcon)
Michael Kolb8233fac2010-10-26 16:08:53 -0700321 .setMessage(msg)
322 .setPositiveButton(R.string.ok, null)
323 .show();
324 return;
325 }
326
Michael Kolb8233fac2010-10-26 16:08:53 -0700327 if (mimetype == null) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700328 // We must have long pressed on a link or image to download it. We
329 // are not sure of the mimetype in this case, so do a head request
Pankaj Garg5762b362015-11-02 07:57:06 -0800330 new FetchUrlMimeType(activity, url, userAgent, referer, auth,
luxiaol62677b02013-07-22 07:54:49 +0800331 privateBrowsing, filename).start();
Michael Kolb8233fac2010-10-26 16:08:53 -0700332 } else {
Dave Tharp13f3f7c2015-07-16 14:58:51 -0700333 if (DownloadDirRestriction.getInstance().downloadsAllowed()) {
334 startDownloadSettings(activity, url, userAgent, contentDisposition, mimetype, referer,
Pankaj Garg5762b362015-11-02 07:57:06 -0800335 auth, privateBrowsing, contentLength, filename);
Dave Tharp13f3f7c2015-07-16 14:58:51 -0700336 }
337 else {
338 Toast.makeText(activity, R.string.managed_by_your_administrator, Toast.LENGTH_SHORT)
339 .show();
340 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700341 }
luxiaol62677b02013-07-22 07:54:49 +0800342
343 }
344
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700345 static String trimContentDisposition(String contentDisposition) {
346 final Pattern CONTENT_DISPOSITION_PATTERN =
Axesh R. Ajmera16c6bce2014-06-18 14:04:10 -0700347 Pattern.compile("filename\\s*=\\s*(\"?)([^\";]*)\\1\\s*",
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700348 Pattern.CASE_INSENSITIVE);
349
350 if (contentDisposition != null) {
351
352 try {
353 Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
354 if (m.find()) {
Axesh R. Ajmera9a293b02014-06-10 14:03:55 -0700355 contentDisposition = "attachment; filename="+m.group(2);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700356 }
Axesh R. Ajmera9a293b02014-06-10 14:03:55 -0700357
358 return contentDisposition;
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700359 } catch (IllegalStateException ex) {
360 // This function is defined as returning null when it can't parse the header
361 }
362 }
363 return null;
364 }
365
luxiaol62677b02013-07-22 07:54:49 +0800366 public static void initStorageDefaultPath(Context context) {
367 mExternalStorage = getExternalStorageDirectory(context);
368 if (isPhoneStorageSupported()) {
369 mInternalStorage = Environment.getExternalStorageDirectory().getPath();
370 } else {
371 mInternalStorage = null;
372 }
373 }
374
375 public static void startDownloadSettings(Activity activity,
376 String url, String userAgent, String contentDisposition,
Pankaj Garg5762b362015-11-02 07:57:06 -0800377 String mimetype, String referer, String auth,
378 boolean privateBrowsing, long contentLength,
luxiaol62677b02013-07-22 07:54:49 +0800379 String filename) {
380 Bundle fileInfo = new Bundle();
381 fileInfo.putString("url", url);
382 fileInfo.putString("userAgent", userAgent);
383 fileInfo.putString("contentDisposition", contentDisposition);
384 fileInfo.putString("mimetype", mimetype);
385 fileInfo.putString("referer", referer);
Pankaj Garg5762b362015-11-02 07:57:06 -0800386 fileInfo.putString("authorization", auth);
luxiaol62677b02013-07-22 07:54:49 +0800387 fileInfo.putLong("contentLength", contentLength);
388 fileInfo.putBoolean("privateBrowsing", privateBrowsing);
389 fileInfo.putString("filename", filename);
390 Intent intent = new Intent("android.intent.action.BROWSERDOWNLOAD");
Axesh R. Ajmera8a90fda2014-11-05 12:25:44 -0800391
392 // Since there could be multiple browsers capable of handling
393 // the same intent we assure that the same package handles it
394 intent.setPackage(activity.getPackageName());
395
luxiaol62677b02013-07-22 07:54:49 +0800396 intent.putExtras(fileInfo);
397 activity.startActivity(intent);
398 }
399
400 public static void setAppointedFolder(String downloadPath) {
401 File file = new File(downloadPath);
402 if (file.exists()) {
403 if (!file.isDirectory()) {
404 throw new IllegalStateException(file.getAbsolutePath() +
405 " already exists and is not a directory");
406 }
407 } else {
408 if (!file.mkdir()) {
409 throw new IllegalStateException("Unable to create directory: " +
410 file.getAbsolutePath());
411 }
412 }
413 }
414
415 private static void setDestinationDir(String downloadPath, String filename, Request request) {
416 File file = new File(downloadPath);
417 if (file.exists()) {
418 if (!file.isDirectory()) {
419 throw new IllegalStateException(file.getAbsolutePath() +
420 " already exists and is not a directory");
421 }
422 } else {
423 if (!file.mkdir()) {
424 throw new IllegalStateException("Unable to create directory: " +
425 file.getAbsolutePath());
426 }
427 }
428 setDestinationFromBase(file, filename, request);
429 }
430
431 private static void setDestinationFromBase(File file, String filename, Request request) {
432 if (filename == null) {
433 throw new NullPointerException("filename cannot be null");
434 }
435 request.setDestinationUri(Uri.withAppendedPath(Uri.fromFile(file), filename));
436 }
437
438 public static void fileExistQueryDialog(Activity activity) {
439 new AlertDialog.Builder(activity)
440 .setTitle(R.string.download_file_exist)
441 .setIcon(android.R.drawable.ic_dialog_info)
442 .setMessage(R.string.download_file_exist_msg)
443 // if yes, delete existed file and start new download thread
444 .setPositiveButton(R.string.ok, null)
445 // if no, do nothing at all
446 .show();
447 }
448
449 public static long getAvailableMemory(String root) {
450 StatFs stat = new StatFs(root);
451 final long LEFT10MByte = 2560;
452 long blockSize = stat.getBlockSize();
453 long availableBlocks = stat.getAvailableBlocks() - LEFT10MByte;
454 return availableBlocks * blockSize;
455 }
456
457 public static void showNoEnoughMemoryDialog(Activity mContext) {
458 new AlertDialog.Builder(mContext)
459 .setTitle(R.string.download_no_enough_memory)
460 .setIconAttribute(android.R.attr.alertDialogIcon)
461 .setMessage(R.string.download_no_enough_memory)
462 .setPositiveButton(R.string.ok, null)
463 .show();
464 }
465
kaiyize6a27d02013-08-22 15:08:19 +0800466 public static boolean manageNoEnoughMemory(long contentLength, String root) {
luxiaol62677b02013-07-22 07:54:49 +0800467 long mAvailableBytes = getAvailableMemory(root);
468 if (mAvailableBytes > 0) {
469 if (contentLength > mAvailableBytes) {
luxiaol62677b02013-07-22 07:54:49 +0800470 return true;
471 }
472 } else {
luxiaol62677b02013-07-22 07:54:49 +0800473 return true;
474 }
475 return false;
476 }
477
Panos Thomase57e3a02014-04-30 20:25:16 -0700478 public static void showStartDownloadToast(Activity activity,
479 boolean privateBrowsing) {
480 if (!privateBrowsing) {
481 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
Tarun Nainanif0d16702015-08-12 18:14:42 -0700482 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Panos Thomase57e3a02014-04-30 20:25:16 -0700483 activity.startActivity(intent);
484 } else {
485 activity.finish();
486 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500487 Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT)
Michael Kolb8233fac2010-10-26 16:08:53 -0700488 .show();
489 }
490
luxiaol62677b02013-07-22 07:54:49 +0800491 /**
492 * wheather the storage status OK for download file
493 *
494 * @param activity
495 * @param filename the download file's name
496 * @param downloadPath the download file's path will be in
497 * @return boolean true is ok,and false is not
498 */
499 public static boolean isStorageStatusOK(Activity activity, String filename, String downloadPath) {
500 if (downloadPath.equals(INVALID_PATH)) {
501 new AlertDialog.Builder(activity)
502 .setTitle(R.string.path_wrong)
503 .setIcon(android.R.drawable.ic_dialog_alert)
504 .setMessage(R.string.invalid_path)
505 .setPositiveButton(R.string.ok, null)
506 .show();
507 return false;
508 }
509
Axesh R. Ajmera8a90fda2014-11-05 12:25:44 -0800510 // assure that internal storage is initialized before
511 // comparing it with download path
512 if (mInternalStorage == null) {
513 initStorageDefaultPath(activity);
514 }
515
luxiaol62677b02013-07-22 07:54:49 +0800516 if (!(isPhoneStorageSupported() && downloadPath.contains(mInternalStorage))) {
517 String status = getExternalStorageState(activity);
518 if (!status.equals(Environment.MEDIA_MOUNTED)) {
519 int title;
520 String msg;
521
522 // Check to see if the SDCard is busy, same as the music app
523 if (status.equals(Environment.MEDIA_SHARED)) {
524 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
525 title = R.string.download_sdcard_busy_dlg_title;
526 } else {
527 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
528 title = R.string.download_no_sdcard_dlg_title;
529 }
530
531 new AlertDialog.Builder(activity)
532 .setTitle(title)
533 .setIcon(android.R.drawable.ic_dialog_alert)
534 .setMessage(msg)
535 .setPositiveButton(R.string.ok, null)
536 .show();
537 return false;
538 }
539 } else {
540 String status = Environment.getExternalStorageState();
541 if (!status.equals(Environment.MEDIA_MOUNTED)) {
542 int mTitle = R.string.download_path_unavailable_dlg_title;
543 String mMsg = activity.getString(R.string.download_path_unavailable_dlg_msg);
544 new AlertDialog.Builder(activity)
545 .setTitle(mTitle)
546 .setIcon(android.R.drawable.ic_dialog_alert)
547 .setMessage(mMsg)
548 .setPositiveButton(R.string.ok, null)
549 .show();
550 return false;
551 }
552 }
553 return true;
554 }
555
556 /**
557 * wheather support Phone Storage
558 *
559 * @return boolean true support Phone Storage ,false will be not
560 */
561 public static boolean isPhoneStorageSupported() {
562 return true;
563 }
564
565 /**
566 * show Dialog to warn filename is null
567 *
568 * @param activity
569 */
570 public static void showFilenameEmptyDialog(Activity activity) {
571 new AlertDialog.Builder(activity)
572 .setTitle(R.string.filename_empty_title)
573 .setIcon(android.R.drawable.ic_dialog_alert)
574 .setMessage(R.string.filename_empty_msg)
575 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
576 public void onClick(DialogInterface dialog, int which) {
577 }
578 })
579 .show();
580 }
581
582 /**
583 * get the filename except the suffix and dot
584 *
585 * @return String the filename except suffix and dot
586 */
587 public static String getFilenameBase(String filename) {
588 int dotindex = filename.lastIndexOf('.');
589 if (dotindex != -1) {
590 return filename.substring(0, dotindex);
591 } else {
592 return "";
593 }
594 }
595
596 /**
597 * get the filename's extension from filename
598 *
599 * @param filename the download filename, may be the user entered
600 * @return String the filename's extension
601 */
602 public static String getFilenameExtension(String filename) {
603 int dotindex = filename.lastIndexOf('.');
604 if (dotindex != -1) {
605 return filename.substring(dotindex + 1);
606 } else {
607 return "";
608 }
609 }
610
611 public static String getDefaultDownloadPath(Context context) {
612 String defaultDownloadPath;
613
614 String defaultStorage;
615 if (isPhoneStorageSupported()) {
616 defaultStorage = Environment.getExternalStorageDirectory().getPath();
617 } else {
618 defaultStorage = getExternalStorageDirectory(context);
619 }
620
Dave Tharp13f3f7c2015-07-16 14:58:51 -0700621 defaultDownloadPath = defaultStorage + DownloadDirRestriction.getInstance().getDownloadDirectory();
luxiaol62677b02013-07-22 07:54:49 +0800622 Log.e(LOGTAG, "defaultStorage directory is : " + defaultDownloadPath);
623 return defaultDownloadPath;
624 }
625
626 /**
627 * translate the directory name into a name which is easy to know for user
628 *
629 * @param activity
630 * @param downloadPath
631 * @return String
632 */
633 public static String getDownloadPathForUser(Activity activity, String downloadPath) {
634 if (downloadPath == null) {
635 return downloadPath;
636 }
637 final String phoneStorageDir;
638 final String sdCardDir = getExternalStorageDirectory(activity);
639 if (isPhoneStorageSupported()) {
640 phoneStorageDir = Environment.getExternalStorageDirectory().getPath();
641 } else {
642 phoneStorageDir = null;
643 }
644
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800645 if (sdCardDir != null && downloadPath.startsWith(sdCardDir)) {
luxiaol62677b02013-07-22 07:54:49 +0800646 String sdCardLabel = activity.getResources().getString(
647 R.string.download_path_sd_card_label);
648 downloadPath = downloadPath.replace(sdCardDir, sdCardLabel);
649 } else if ((phoneStorageDir != null) && downloadPath.startsWith(phoneStorageDir)) {
650 String phoneStorageLabel = activity.getResources().getString(
kaiyizf1a66762013-09-16 16:59:43 +0800651 R.string.download_path_phone_storage_label);
luxiaol62677b02013-07-22 07:54:49 +0800652 downloadPath = downloadPath.replace(phoneStorageDir, phoneStorageLabel);
653 }
654 return downloadPath;
655 }
656
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800657 private static boolean isRemovable(Object obj) {
658 return (Boolean) ReflectHelper.invokeMethod(obj,
659 "isRemovable", null, null);
660 }
661
662 private static boolean allowMassStorage(Object obj) {
663 return (Boolean) ReflectHelper.invokeMethod(obj,
664 "allowMassStorage", null, null);
665 }
666
667 private static String getPath(Object obj) {
668 return (String) ReflectHelper.invokeMethod(obj,
669 "getPath", null, null);
670 }
671
luxiaol62677b02013-07-22 07:54:49 +0800672 private static String getExternalStorageDirectory(Context context) {
673 String sd = null;
674 StorageManager mStorageManager = (StorageManager) context
675 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800676 Object[] volumes = (Object[]) ReflectHelper.invokeMethod(
677 mStorageManager, "getVolumeList", null, null);
luxiaol62677b02013-07-22 07:54:49 +0800678 for (int i = 0; i < volumes.length; i++) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800679 if (isRemovable(volumes[i]) && allowMassStorage(volumes[i])) {
680 sd = getPath(volumes[i]);
Vivek Sekhar027ecad2014-04-15 05:42:38 -0700681 break;
luxiaol62677b02013-07-22 07:54:49 +0800682 }
683 }
684 return sd;
685 }
686
687 private static String getExternalStorageState(Context context) {
688 StorageManager mStorageManager = (StorageManager) context
689 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800690 String path = getExternalStorageDirectory(context);
691 Object[] params = {path};
692 Class[] type = new Class[] {String.class};
Bijan Amirzada63a855a2014-03-26 13:57:22 -0700693 return (String) ReflectHelper.invokeMethod(mStorageManager,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800694 "getVolumeState", type, params);
luxiaol62677b02013-07-22 07:54:49 +0800695 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700696}