blob: 0148fda430a0908a2a345cc8db721572520b01ac [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;
Michael Kolb8233fac2010-10-26 16:08:53 -070035import android.util.Log;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080036import org.codeaurora.swe.CookieManager;
Michael Kolb8233fac2010-10-26 16:08:53 -070037import android.webkit.URLUtil;
38import android.widget.Toast;
39
Bijan Amirzada41242f22014-03-21 12:12:18 -070040import com.android.browser.R;
Dave Tharp13f3f7c2015-07-16 14:58:51 -070041import com.android.browser.mdm.DownloadDirRestriction;
Bijan Amirzada41242f22014-03-21 12:12:18 -070042import com.android.browser.platformsupport.WebAddress;
43import com.android.browser.reflect.ReflectHelper;
luxiaol62677b02013-07-22 07:54:49 +080044
Axesh R. Ajmera2e241242014-05-19 15:53:38 -070045import java.util.regex.Matcher;
46import java.util.regex.Pattern;
47
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080048import java.io.File;
Michael Kolb8233fac2010-10-26 16:08:53 -070049/**
50 * Handle download requests
51 */
52public class DownloadHandler {
53
54 private static final boolean LOGD_ENABLED =
Bijan Amirzada41242f22014-03-21 12:12:18 -070055 com.android.browser.Browser.LOGD_ENABLED;
Michael Kolb8233fac2010-10-26 16:08:53 -070056
57 private static final String LOGTAG = "DLHandler";
luxiaol62677b02013-07-22 07:54:49 +080058 private static String mInternalStorage;
59 private static String mExternalStorage;
60 private final static String INVALID_PATH = "/storage";
Michael Kolb8233fac2010-10-26 16:08:53 -070061
luxiaol62677b02013-07-22 07:54:49 +080062 public static void startingDownload(Activity activity,
63 String url, String userAgent, String contentDisposition,
64 String mimetype, String referer, boolean privateBrowsing, long contentLength,
65 String filename, String downloadPath) {
66 // java.net.URI is a lot stricter than KURL so we have to encode some
67 // extra characters. Fix for b 2538060 and b 1634719
68 WebAddress webAddress;
69 try {
70 webAddress = new WebAddress(url);
71 webAddress.setPath(encodePath(webAddress.getPath()));
72 } catch (Exception e) {
73 // This only happens for very bad urls, we want to chatch the
74 // exception here
75 Log.e(LOGTAG, "Exception trying to parse url:" + url);
76 return;
77 }
78
79 String addressString = webAddress.toString();
80 Uri uri = Uri.parse(addressString);
81 final DownloadManager.Request request;
82 try {
83 request = new DownloadManager.Request(uri);
84 } catch (IllegalArgumentException e) {
85 Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
86 return;
87 }
88 request.setMimeType(mimetype);
89 // set downloaded file destination to /sdcard/Download.
90 // or, should it be set to one of several Environment.DIRECTORY* dirs
91 // depending on mimetype?
92 try {
93 setDestinationDir(downloadPath, filename, request);
94 } catch (Exception e) {
95 showNoEnoughMemoryDialog(activity);
96 return;
97 }
98 // let this downloaded file be scanned by MediaScanner - so that it can
99 // show up in Gallery app, for example.
100 request.allowScanningByMediaScanner();
101 request.setDescription(webAddress.getHost());
102 // XXX: Have to use the old url since the cookies were stored using the
103 // old percent-encoded url.
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800104
luxiaol62677b02013-07-22 07:54:49 +0800105 String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
106 request.addRequestHeader("cookie", cookies);
107 request.addRequestHeader("User-Agent", userAgent);
108 request.addRequestHeader("Referer", referer);
Panos Thomase57e3a02014-04-30 20:25:16 -0700109 request.setVisibleInDownloadsUi(!privateBrowsing);
luxiaol62677b02013-07-22 07:54:49 +0800110 request.setNotificationVisibility(
111 DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
112 final DownloadManager manager = (DownloadManager) activity
113 .getSystemService(Context.DOWNLOAD_SERVICE);
114 new Thread("Browser download") {
115 public void run() {
Vivek Sekhar40713382014-06-11 14:29:32 -0700116 try {
117 manager.enqueue(request);
118 } catch (Exception e) {
119 Log.w("DLHandler", "Could not enqueue the download", e);
120 }
luxiaol62677b02013-07-22 07:54:49 +0800121 }
122 }.start();
Panos Thomase57e3a02014-04-30 20:25:16 -0700123 showStartDownloadToast(activity, privateBrowsing);
luxiaol62677b02013-07-22 07:54:49 +0800124 }
125
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800126 private static boolean isAudioFileType(int fileType){
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700127 Object[] params = {Integer.valueOf(fileType)};
128 Class[] type = new Class[] {int.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700129 Boolean result = (Boolean) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700130 "isAudioFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800131 return result;
132 }
133
134 private static boolean isVideoFileType(int fileType){
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700135 Object[] params = {Integer.valueOf(fileType)};
136 Class[] type = new Class[] {int.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700137 Boolean result = (Boolean) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700138 "isVideoFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800139 return result;
140 }
141
kaiyize6a27d02013-08-22 15:08:19 +0800142 /**
143 * Notify the host application a download should be done, or that
144 * the data should be streamed if a streaming viewer is available.
145 * @param activity Activity requesting the download.
146 * @param url The full url to the content that should be downloaded
147 * @param userAgent User agent of the downloading application.
148 * @param contentDisposition Content-disposition http header, if present.
149 * @param mimetype The mimetype of the content reported by the server
150 * @param referer The referer associated with the downloaded url
151 * @param privateBrowsing If the request is coming from a private browsing tab.
152 */
qqzhoua95a2e22013-04-18 17:28:31 +0800153 public static boolean onDownloadStart(final Activity activity, final String url,
154 final String userAgent, final String contentDisposition, final String mimetype,
luxiaol62677b02013-07-22 07:54:49 +0800155 final String referer, final boolean privateBrowsing, final long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 // if we're dealing wih A/V content that's not explicitly marked
157 // for download, check if it's streamable.
158 if (contentDisposition == null
159 || !contentDisposition.regionMatches(
160 true, 0, "attachment", 0, 10)) {
qqzhoua95a2e22013-04-18 17:28:31 +0800161 // Add for Carrier Feature - When open an audio/video link, prompt a dialog
162 // to let the user choose play or download operation.
163 Uri uri = Uri.parse(url);
164 String scheme = uri.getScheme();
165 Log.v(LOGTAG, "scheme:" + scheme + ", mimetype:" + mimetype);
166 // Some mimetype for audio/video files is not started with "audio" or "video",
167 // such as ogg audio file with mimetype "application/ogg". So we also check
168 // file type by MediaFile.isAudioFileType() and MediaFile.isVideoFileType().
169 // For those file types other than audio or video, download it immediately.
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700170 Object[] params = {mimetype};
171 Class[] type = new Class[] {String.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700172 Integer result = (Integer) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700173 "getFileTypeForMimeType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800174 int fileType = result.intValue();
qqzhoua95a2e22013-04-18 17:28:31 +0800175 if ("http".equalsIgnoreCase(scheme) &&
176 (mimetype.startsWith("audio/") ||
177 mimetype.startsWith("video/") ||
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800178 isAudioFileType(fileType) ||
179 isVideoFileType(fileType))) {
qqzhoua95a2e22013-04-18 17:28:31 +0800180 new AlertDialog.Builder(activity)
181 .setTitle(R.string.application_name)
182 .setIcon(R.drawable.default_video_poster)
183 .setMessage(R.string.http_video_msg)
184 .setPositiveButton(R.string.video_save, new DialogInterface.OnClickListener() {
185 public void onClick(DialogInterface dialog, int which) {
186 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800187 mimetype, referer, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800188 }
189 })
190 .setNegativeButton(R.string.video_play, new DialogInterface.OnClickListener() {
191 public void onClick(DialogInterface dialog, int which) {
192 Intent intent = new Intent(Intent.ACTION_VIEW);
193 intent.setDataAndType(Uri.parse(url), mimetype);
194 try {
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700195 String trimmedcontentDisposition = trimContentDisposition(contentDisposition);
196 String title = URLUtil.guessFileName(url, trimmedcontentDisposition, mimetype);
qqzhoua95a2e22013-04-18 17:28:31 +0800197 intent.putExtra(Intent.EXTRA_TITLE, title);
198 activity.startActivity(intent);
199 } catch (ActivityNotFoundException ex) {
200 Log.w(LOGTAG, "When http stream play, activity not found for "
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700201 + mimetype + " over " + Uri.parse(url).getScheme(), ex);
qqzhoua95a2e22013-04-18 17:28:31 +0800202 }
203 }
204 }).show();
205
206 return true;
207 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700208 // query the package manager to see if there's a registered handler
209 // that matches.
210 Intent intent = new Intent(Intent.ACTION_VIEW);
211 intent.setDataAndType(Uri.parse(url), mimetype);
Leon Scroggins63c02662010-11-18 15:16:27 -0500212 ResolveInfo info = activity.getPackageManager().resolveActivity(intent,
Michael Kolb8233fac2010-10-26 16:08:53 -0700213 PackageManager.MATCH_DEFAULT_ONLY);
214 if (info != null) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500215 ComponentName myName = activity.getComponentName();
Michael Kolb8233fac2010-10-26 16:08:53 -0700216 // If we resolved to ourselves, we don't want to attempt to
217 // load the url only to try and download it again.
218 if (!myName.getPackageName().equals(
219 info.activityInfo.packageName)
220 || !myName.getClassName().equals(
221 info.activityInfo.name)) {
222 // someone (other than us) knows how to handle this mime
223 // type with this scheme, don't download.
224 try {
Leon Scroggins63c02662010-11-18 15:16:27 -0500225 activity.startActivity(intent);
qqzhoua95a2e22013-04-18 17:28:31 +0800226 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700227 } catch (ActivityNotFoundException ex) {
228 if (LOGD_ENABLED) {
229 Log.d(LOGTAG, "activity not found for " + mimetype
230 + " over " + Uri.parse(url).getScheme(),
231 ex);
232 }
233 // Best behavior is to fall back to a download in this
234 // case
235 }
236 }
237 }
238 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500239 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800240 mimetype, referer, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800241 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700242 }
243
244 // This is to work around the fact that java.net.URI throws Exceptions
245 // instead of just encoding URL's properly
246 // Helper method for onDownloadStartNoStream
247 private static String encodePath(String path) {
248 char[] chars = path.toCharArray();
249
250 boolean needed = false;
251 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700252 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700253 needed = true;
254 break;
255 }
256 }
257 if (needed == false) {
258 return path;
259 }
260
261 StringBuilder sb = new StringBuilder("");
262 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700263 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700264 sb.append('%');
265 sb.append(Integer.toHexString(c));
266 } else {
267 sb.append(c);
268 }
269 }
270
271 return sb.toString();
272 }
273
274 /**
275 * Notify the host application a download should be done, even if there
276 * is a streaming viewer available for thise type.
Leon Scroggins63c02662010-11-18 15:16:27 -0500277 * @param activity Activity requesting the download.
Michael Kolb8233fac2010-10-26 16:08:53 -0700278 * @param url The full url to the content that should be downloaded
Leon Scroggins63c02662010-11-18 15:16:27 -0500279 * @param userAgent User agent of the downloading application.
280 * @param contentDisposition Content-disposition http header, if present.
Michael Kolb8233fac2010-10-26 16:08:53 -0700281 * @param mimetype The mimetype of the content reported by the server
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700282 * @param referer The referer associated with the downloaded url
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000283 * @param privateBrowsing If the request is coming from a private browsing tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700284 */
luxiaol62677b02013-07-22 07:54:49 +0800285 /* package */static void onDownloadStartNoStream(Activity activity,
Leon Scroggins63c02662010-11-18 15:16:27 -0500286 String url, String userAgent, String contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800287 String mimetype, String referer, boolean privateBrowsing, long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700288
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700289 contentDisposition = trimContentDisposition(contentDisposition);
290
Michael Kolb8233fac2010-10-26 16:08:53 -0700291 String filename = URLUtil.guessFileName(url,
292 contentDisposition, mimetype);
293
294 // Check to see if we have an SDCard
295 String status = Environment.getExternalStorageState();
296 if (!status.equals(Environment.MEDIA_MOUNTED)) {
297 int title;
298 String msg;
299
300 // Check to see if the SDCard is busy, same as the music app
301 if (status.equals(Environment.MEDIA_SHARED)) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500302 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
Michael Kolb8233fac2010-10-26 16:08:53 -0700303 title = R.string.download_sdcard_busy_dlg_title;
304 } else {
Leon Scroggins63c02662010-11-18 15:16:27 -0500305 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700306 title = R.string.download_no_sdcard_dlg_title;
307 }
308
Leon Scroggins63c02662010-11-18 15:16:27 -0500309 new AlertDialog.Builder(activity)
Michael Kolb8233fac2010-10-26 16:08:53 -0700310 .setTitle(title)
Björn Lundén2aa8ba22012-05-31 23:05:56 +0200311 .setIconAttribute(android.R.attr.alertDialogIcon)
Michael Kolb8233fac2010-10-26 16:08:53 -0700312 .setMessage(msg)
313 .setPositiveButton(R.string.ok, null)
314 .show();
315 return;
316 }
317
Michael Kolb8233fac2010-10-26 16:08:53 -0700318 if (mimetype == null) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700319 // We must have long pressed on a link or image to download it. We
320 // are not sure of the mimetype in this case, so do a head request
luxiaol62677b02013-07-22 07:54:49 +0800321 new FetchUrlMimeType(activity, url, userAgent, referer,
322 privateBrowsing, filename).start();
Michael Kolb8233fac2010-10-26 16:08:53 -0700323 } else {
Dave Tharp13f3f7c2015-07-16 14:58:51 -0700324 if (DownloadDirRestriction.getInstance().downloadsAllowed()) {
325 startDownloadSettings(activity, url, userAgent, contentDisposition, mimetype, referer,
326 privateBrowsing, contentLength, filename);
327 }
328 else {
329 Toast.makeText(activity, R.string.managed_by_your_administrator, Toast.LENGTH_SHORT)
330 .show();
331 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700332 }
luxiaol62677b02013-07-22 07:54:49 +0800333
334 }
335
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700336 static String trimContentDisposition(String contentDisposition) {
337 final Pattern CONTENT_DISPOSITION_PATTERN =
Axesh R. Ajmera16c6bce2014-06-18 14:04:10 -0700338 Pattern.compile("filename\\s*=\\s*(\"?)([^\";]*)\\1\\s*",
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700339 Pattern.CASE_INSENSITIVE);
340
341 if (contentDisposition != null) {
342
343 try {
344 Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
345 if (m.find()) {
Axesh R. Ajmera9a293b02014-06-10 14:03:55 -0700346 contentDisposition = "attachment; filename="+m.group(2);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700347 }
Axesh R. Ajmera9a293b02014-06-10 14:03:55 -0700348
349 return contentDisposition;
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700350 } catch (IllegalStateException ex) {
351 // This function is defined as returning null when it can't parse the header
352 }
353 }
354 return null;
355 }
356
luxiaol62677b02013-07-22 07:54:49 +0800357 public static void initStorageDefaultPath(Context context) {
358 mExternalStorage = getExternalStorageDirectory(context);
359 if (isPhoneStorageSupported()) {
360 mInternalStorage = Environment.getExternalStorageDirectory().getPath();
361 } else {
362 mInternalStorage = null;
363 }
364 }
365
366 public static void startDownloadSettings(Activity activity,
367 String url, String userAgent, String contentDisposition,
368 String mimetype, String referer, boolean privateBrowsing, long contentLength,
369 String filename) {
370 Bundle fileInfo = new Bundle();
371 fileInfo.putString("url", url);
372 fileInfo.putString("userAgent", userAgent);
373 fileInfo.putString("contentDisposition", contentDisposition);
374 fileInfo.putString("mimetype", mimetype);
375 fileInfo.putString("referer", referer);
376 fileInfo.putLong("contentLength", contentLength);
377 fileInfo.putBoolean("privateBrowsing", privateBrowsing);
378 fileInfo.putString("filename", filename);
379 Intent intent = new Intent("android.intent.action.BROWSERDOWNLOAD");
Axesh R. Ajmera8a90fda2014-11-05 12:25:44 -0800380
381 // Since there could be multiple browsers capable of handling
382 // the same intent we assure that the same package handles it
383 intent.setPackage(activity.getPackageName());
384
luxiaol62677b02013-07-22 07:54:49 +0800385 intent.putExtras(fileInfo);
386 activity.startActivity(intent);
387 }
388
389 public static void setAppointedFolder(String downloadPath) {
390 File file = new File(downloadPath);
391 if (file.exists()) {
392 if (!file.isDirectory()) {
393 throw new IllegalStateException(file.getAbsolutePath() +
394 " already exists and is not a directory");
395 }
396 } else {
397 if (!file.mkdir()) {
398 throw new IllegalStateException("Unable to create directory: " +
399 file.getAbsolutePath());
400 }
401 }
402 }
403
404 private static void setDestinationDir(String downloadPath, String filename, Request request) {
405 File file = new File(downloadPath);
406 if (file.exists()) {
407 if (!file.isDirectory()) {
408 throw new IllegalStateException(file.getAbsolutePath() +
409 " already exists and is not a directory");
410 }
411 } else {
412 if (!file.mkdir()) {
413 throw new IllegalStateException("Unable to create directory: " +
414 file.getAbsolutePath());
415 }
416 }
417 setDestinationFromBase(file, filename, request);
418 }
419
420 private static void setDestinationFromBase(File file, String filename, Request request) {
421 if (filename == null) {
422 throw new NullPointerException("filename cannot be null");
423 }
424 request.setDestinationUri(Uri.withAppendedPath(Uri.fromFile(file), filename));
425 }
426
427 public static void fileExistQueryDialog(Activity activity) {
428 new AlertDialog.Builder(activity)
429 .setTitle(R.string.download_file_exist)
430 .setIcon(android.R.drawable.ic_dialog_info)
431 .setMessage(R.string.download_file_exist_msg)
432 // if yes, delete existed file and start new download thread
433 .setPositiveButton(R.string.ok, null)
434 // if no, do nothing at all
435 .show();
436 }
437
438 public static long getAvailableMemory(String root) {
439 StatFs stat = new StatFs(root);
440 final long LEFT10MByte = 2560;
441 long blockSize = stat.getBlockSize();
442 long availableBlocks = stat.getAvailableBlocks() - LEFT10MByte;
443 return availableBlocks * blockSize;
444 }
445
446 public static void showNoEnoughMemoryDialog(Activity mContext) {
447 new AlertDialog.Builder(mContext)
448 .setTitle(R.string.download_no_enough_memory)
449 .setIconAttribute(android.R.attr.alertDialogIcon)
450 .setMessage(R.string.download_no_enough_memory)
451 .setPositiveButton(R.string.ok, null)
452 .show();
453 }
454
kaiyize6a27d02013-08-22 15:08:19 +0800455 public static boolean manageNoEnoughMemory(long contentLength, String root) {
luxiaol62677b02013-07-22 07:54:49 +0800456 long mAvailableBytes = getAvailableMemory(root);
457 if (mAvailableBytes > 0) {
458 if (contentLength > mAvailableBytes) {
luxiaol62677b02013-07-22 07:54:49 +0800459 return true;
460 }
461 } else {
luxiaol62677b02013-07-22 07:54:49 +0800462 return true;
463 }
464 return false;
465 }
466
Panos Thomase57e3a02014-04-30 20:25:16 -0700467 public static void showStartDownloadToast(Activity activity,
468 boolean privateBrowsing) {
469 if (!privateBrowsing) {
470 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
Tarun Nainanif0d16702015-08-12 18:14:42 -0700471 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Panos Thomase57e3a02014-04-30 20:25:16 -0700472 activity.startActivity(intent);
473 } else {
474 activity.finish();
475 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500476 Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT)
Michael Kolb8233fac2010-10-26 16:08:53 -0700477 .show();
478 }
479
luxiaol62677b02013-07-22 07:54:49 +0800480 /**
481 * wheather the storage status OK for download file
482 *
483 * @param activity
484 * @param filename the download file's name
485 * @param downloadPath the download file's path will be in
486 * @return boolean true is ok,and false is not
487 */
488 public static boolean isStorageStatusOK(Activity activity, String filename, String downloadPath) {
489 if (downloadPath.equals(INVALID_PATH)) {
490 new AlertDialog.Builder(activity)
491 .setTitle(R.string.path_wrong)
492 .setIcon(android.R.drawable.ic_dialog_alert)
493 .setMessage(R.string.invalid_path)
494 .setPositiveButton(R.string.ok, null)
495 .show();
496 return false;
497 }
498
Axesh R. Ajmera8a90fda2014-11-05 12:25:44 -0800499 // assure that internal storage is initialized before
500 // comparing it with download path
501 if (mInternalStorage == null) {
502 initStorageDefaultPath(activity);
503 }
504
luxiaol62677b02013-07-22 07:54:49 +0800505 if (!(isPhoneStorageSupported() && downloadPath.contains(mInternalStorage))) {
506 String status = getExternalStorageState(activity);
507 if (!status.equals(Environment.MEDIA_MOUNTED)) {
508 int title;
509 String msg;
510
511 // Check to see if the SDCard is busy, same as the music app
512 if (status.equals(Environment.MEDIA_SHARED)) {
513 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
514 title = R.string.download_sdcard_busy_dlg_title;
515 } else {
516 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
517 title = R.string.download_no_sdcard_dlg_title;
518 }
519
520 new AlertDialog.Builder(activity)
521 .setTitle(title)
522 .setIcon(android.R.drawable.ic_dialog_alert)
523 .setMessage(msg)
524 .setPositiveButton(R.string.ok, null)
525 .show();
526 return false;
527 }
528 } else {
529 String status = Environment.getExternalStorageState();
530 if (!status.equals(Environment.MEDIA_MOUNTED)) {
531 int mTitle = R.string.download_path_unavailable_dlg_title;
532 String mMsg = activity.getString(R.string.download_path_unavailable_dlg_msg);
533 new AlertDialog.Builder(activity)
534 .setTitle(mTitle)
535 .setIcon(android.R.drawable.ic_dialog_alert)
536 .setMessage(mMsg)
537 .setPositiveButton(R.string.ok, null)
538 .show();
539 return false;
540 }
541 }
542 return true;
543 }
544
545 /**
546 * wheather support Phone Storage
547 *
548 * @return boolean true support Phone Storage ,false will be not
549 */
550 public static boolean isPhoneStorageSupported() {
551 return true;
552 }
553
554 /**
555 * show Dialog to warn filename is null
556 *
557 * @param activity
558 */
559 public static void showFilenameEmptyDialog(Activity activity) {
560 new AlertDialog.Builder(activity)
561 .setTitle(R.string.filename_empty_title)
562 .setIcon(android.R.drawable.ic_dialog_alert)
563 .setMessage(R.string.filename_empty_msg)
564 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
565 public void onClick(DialogInterface dialog, int which) {
566 }
567 })
568 .show();
569 }
570
571 /**
572 * get the filename except the suffix and dot
573 *
574 * @return String the filename except suffix and dot
575 */
576 public static String getFilenameBase(String filename) {
577 int dotindex = filename.lastIndexOf('.');
578 if (dotindex != -1) {
579 return filename.substring(0, dotindex);
580 } else {
581 return "";
582 }
583 }
584
585 /**
586 * get the filename's extension from filename
587 *
588 * @param filename the download filename, may be the user entered
589 * @return String the filename's extension
590 */
591 public static String getFilenameExtension(String filename) {
592 int dotindex = filename.lastIndexOf('.');
593 if (dotindex != -1) {
594 return filename.substring(dotindex + 1);
595 } else {
596 return "";
597 }
598 }
599
600 public static String getDefaultDownloadPath(Context context) {
601 String defaultDownloadPath;
602
603 String defaultStorage;
604 if (isPhoneStorageSupported()) {
605 defaultStorage = Environment.getExternalStorageDirectory().getPath();
606 } else {
607 defaultStorage = getExternalStorageDirectory(context);
608 }
609
Dave Tharp13f3f7c2015-07-16 14:58:51 -0700610 defaultDownloadPath = defaultStorage + DownloadDirRestriction.getInstance().getDownloadDirectory();
luxiaol62677b02013-07-22 07:54:49 +0800611 Log.e(LOGTAG, "defaultStorage directory is : " + defaultDownloadPath);
612 return defaultDownloadPath;
613 }
614
615 /**
616 * translate the directory name into a name which is easy to know for user
617 *
618 * @param activity
619 * @param downloadPath
620 * @return String
621 */
622 public static String getDownloadPathForUser(Activity activity, String downloadPath) {
623 if (downloadPath == null) {
624 return downloadPath;
625 }
626 final String phoneStorageDir;
627 final String sdCardDir = getExternalStorageDirectory(activity);
628 if (isPhoneStorageSupported()) {
629 phoneStorageDir = Environment.getExternalStorageDirectory().getPath();
630 } else {
631 phoneStorageDir = null;
632 }
633
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800634 if (sdCardDir != null && downloadPath.startsWith(sdCardDir)) {
luxiaol62677b02013-07-22 07:54:49 +0800635 String sdCardLabel = activity.getResources().getString(
636 R.string.download_path_sd_card_label);
637 downloadPath = downloadPath.replace(sdCardDir, sdCardLabel);
638 } else if ((phoneStorageDir != null) && downloadPath.startsWith(phoneStorageDir)) {
639 String phoneStorageLabel = activity.getResources().getString(
kaiyizf1a66762013-09-16 16:59:43 +0800640 R.string.download_path_phone_storage_label);
luxiaol62677b02013-07-22 07:54:49 +0800641 downloadPath = downloadPath.replace(phoneStorageDir, phoneStorageLabel);
642 }
643 return downloadPath;
644 }
645
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800646 private static boolean isRemovable(Object obj) {
647 return (Boolean) ReflectHelper.invokeMethod(obj,
648 "isRemovable", null, null);
649 }
650
651 private static boolean allowMassStorage(Object obj) {
652 return (Boolean) ReflectHelper.invokeMethod(obj,
653 "allowMassStorage", null, null);
654 }
655
656 private static String getPath(Object obj) {
657 return (String) ReflectHelper.invokeMethod(obj,
658 "getPath", null, null);
659 }
660
luxiaol62677b02013-07-22 07:54:49 +0800661 private static String getExternalStorageDirectory(Context context) {
662 String sd = null;
663 StorageManager mStorageManager = (StorageManager) context
664 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800665 Object[] volumes = (Object[]) ReflectHelper.invokeMethod(
666 mStorageManager, "getVolumeList", null, null);
luxiaol62677b02013-07-22 07:54:49 +0800667 for (int i = 0; i < volumes.length; i++) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800668 if (isRemovable(volumes[i]) && allowMassStorage(volumes[i])) {
669 sd = getPath(volumes[i]);
Vivek Sekhar027ecad2014-04-15 05:42:38 -0700670 break;
luxiaol62677b02013-07-22 07:54:49 +0800671 }
672 }
673 return sd;
674 }
675
676 private static String getExternalStorageState(Context context) {
677 StorageManager mStorageManager = (StorageManager) context
678 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800679 String path = getExternalStorageDirectory(context);
680 Object[] params = {path};
681 Class[] type = new Class[] {String.class};
Bijan Amirzada63a855a2014-03-26 13:57:22 -0700682 return (String) ReflectHelper.invokeMethod(mStorageManager,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800683 "getVolumeState", type, params);
luxiaol62677b02013-07-22 07:54:49 +0800684 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700685}