blob: 419e4b46d5ef630b47f4e8a8656eebec7920de2c [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;
41import com.android.browser.platformsupport.WebAddress;
42import com.android.browser.reflect.ReflectHelper;
luxiaol62677b02013-07-22 07:54:49 +080043
Axesh R. Ajmera2e241242014-05-19 15:53:38 -070044import java.util.regex.Matcher;
45import java.util.regex.Pattern;
46
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080047import java.io.File;
Michael Kolb8233fac2010-10-26 16:08:53 -070048/**
49 * Handle download requests
50 */
51public class DownloadHandler {
52
53 private static final boolean LOGD_ENABLED =
Bijan Amirzada41242f22014-03-21 12:12:18 -070054 com.android.browser.Browser.LOGD_ENABLED;
Michael Kolb8233fac2010-10-26 16:08:53 -070055
56 private static final String LOGTAG = "DLHandler";
luxiaol62677b02013-07-22 07:54:49 +080057 private static String mInternalStorage;
58 private static String mExternalStorage;
59 private final static String INVALID_PATH = "/storage";
Michael Kolb8233fac2010-10-26 16:08:53 -070060
luxiaol62677b02013-07-22 07:54:49 +080061 public static void startingDownload(Activity activity,
62 String url, String userAgent, String contentDisposition,
63 String mimetype, String referer, boolean privateBrowsing, long contentLength,
64 String filename, String downloadPath) {
65 // java.net.URI is a lot stricter than KURL so we have to encode some
66 // extra characters. Fix for b 2538060 and b 1634719
67 WebAddress webAddress;
68 try {
69 webAddress = new WebAddress(url);
70 webAddress.setPath(encodePath(webAddress.getPath()));
71 } catch (Exception e) {
72 // This only happens for very bad urls, we want to chatch the
73 // exception here
74 Log.e(LOGTAG, "Exception trying to parse url:" + url);
75 return;
76 }
77
78 String addressString = webAddress.toString();
79 Uri uri = Uri.parse(addressString);
80 final DownloadManager.Request request;
81 try {
82 request = new DownloadManager.Request(uri);
83 } catch (IllegalArgumentException e) {
84 Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
85 return;
86 }
87 request.setMimeType(mimetype);
88 // set downloaded file destination to /sdcard/Download.
89 // or, should it be set to one of several Environment.DIRECTORY* dirs
90 // depending on mimetype?
91 try {
92 setDestinationDir(downloadPath, filename, request);
93 } catch (Exception e) {
94 showNoEnoughMemoryDialog(activity);
95 return;
96 }
97 // let this downloaded file be scanned by MediaScanner - so that it can
98 // show up in Gallery app, for example.
99 request.allowScanningByMediaScanner();
100 request.setDescription(webAddress.getHost());
101 // XXX: Have to use the old url since the cookies were stored using the
102 // old percent-encoded url.
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800103
luxiaol62677b02013-07-22 07:54:49 +0800104 String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
105 request.addRequestHeader("cookie", cookies);
106 request.addRequestHeader("User-Agent", userAgent);
107 request.addRequestHeader("Referer", referer);
Panos Thomase57e3a02014-04-30 20:25:16 -0700108 request.setVisibleInDownloadsUi(!privateBrowsing);
luxiaol62677b02013-07-22 07:54:49 +0800109 request.setNotificationVisibility(
110 DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
111 final DownloadManager manager = (DownloadManager) activity
112 .getSystemService(Context.DOWNLOAD_SERVICE);
113 new Thread("Browser download") {
114 public void run() {
Vivek Sekhar40713382014-06-11 14:29:32 -0700115 try {
116 manager.enqueue(request);
117 } catch (Exception e) {
118 Log.w("DLHandler", "Could not enqueue the download", e);
119 }
luxiaol62677b02013-07-22 07:54:49 +0800120 }
121 }.start();
Panos Thomase57e3a02014-04-30 20:25:16 -0700122 showStartDownloadToast(activity, privateBrowsing);
luxiaol62677b02013-07-22 07:54:49 +0800123 }
124
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800125 private static boolean isAudioFileType(int fileType){
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700126 Object[] params = {Integer.valueOf(fileType)};
127 Class[] type = new Class[] {int.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700128 Boolean result = (Boolean) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700129 "isAudioFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800130 return result;
131 }
132
133 private static boolean isVideoFileType(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 "isVideoFileType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800138 return result;
139 }
140
kaiyize6a27d02013-08-22 15:08:19 +0800141 /**
142 * Notify the host application a download should be done, or that
143 * the data should be streamed if a streaming viewer is available.
144 * @param activity Activity requesting the download.
145 * @param url The full url to the content that should be downloaded
146 * @param userAgent User agent of the downloading application.
147 * @param contentDisposition Content-disposition http header, if present.
148 * @param mimetype The mimetype of the content reported by the server
149 * @param referer The referer associated with the downloaded url
150 * @param privateBrowsing If the request is coming from a private browsing tab.
151 */
qqzhoua95a2e22013-04-18 17:28:31 +0800152 public static boolean onDownloadStart(final Activity activity, final String url,
153 final String userAgent, final String contentDisposition, final String mimetype,
luxiaol62677b02013-07-22 07:54:49 +0800154 final String referer, final boolean privateBrowsing, final long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700155 // if we're dealing wih A/V content that's not explicitly marked
156 // for download, check if it's streamable.
157 if (contentDisposition == null
158 || !contentDisposition.regionMatches(
159 true, 0, "attachment", 0, 10)) {
qqzhoua95a2e22013-04-18 17:28:31 +0800160 // Add for Carrier Feature - When open an audio/video link, prompt a dialog
161 // to let the user choose play or download operation.
162 Uri uri = Uri.parse(url);
163 String scheme = uri.getScheme();
164 Log.v(LOGTAG, "scheme:" + scheme + ", mimetype:" + mimetype);
165 // Some mimetype for audio/video files is not started with "audio" or "video",
166 // such as ogg audio file with mimetype "application/ogg". So we also check
167 // file type by MediaFile.isAudioFileType() and MediaFile.isVideoFileType().
168 // For those file types other than audio or video, download it immediately.
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700169 Object[] params = {mimetype};
170 Class[] type = new Class[] {String.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700171 Integer result = (Integer) ReflectHelper.invokeMethod("android.media.MediaFile",
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700172 "getFileTypeForMimeType", type, params);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800173 int fileType = result.intValue();
qqzhoua95a2e22013-04-18 17:28:31 +0800174 if ("http".equalsIgnoreCase(scheme) &&
175 (mimetype.startsWith("audio/") ||
176 mimetype.startsWith("video/") ||
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800177 isAudioFileType(fileType) ||
178 isVideoFileType(fileType))) {
qqzhoua95a2e22013-04-18 17:28:31 +0800179 new AlertDialog.Builder(activity)
180 .setTitle(R.string.application_name)
181 .setIcon(R.drawable.default_video_poster)
182 .setMessage(R.string.http_video_msg)
183 .setPositiveButton(R.string.video_save, new DialogInterface.OnClickListener() {
184 public void onClick(DialogInterface dialog, int which) {
185 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800186 mimetype, referer, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800187 }
188 })
189 .setNegativeButton(R.string.video_play, new DialogInterface.OnClickListener() {
190 public void onClick(DialogInterface dialog, int which) {
191 Intent intent = new Intent(Intent.ACTION_VIEW);
192 intent.setDataAndType(Uri.parse(url), mimetype);
193 try {
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700194 String trimmedcontentDisposition = trimContentDisposition(contentDisposition);
195 String title = URLUtil.guessFileName(url, trimmedcontentDisposition, mimetype);
qqzhoua95a2e22013-04-18 17:28:31 +0800196 intent.putExtra(Intent.EXTRA_TITLE, title);
197 activity.startActivity(intent);
198 } catch (ActivityNotFoundException ex) {
199 Log.w(LOGTAG, "When http stream play, activity not found for "
Bijan Amirzadaac832f72014-03-17 15:29:16 -0700200 + mimetype + " over " + Uri.parse(url).getScheme(), ex);
qqzhoua95a2e22013-04-18 17:28:31 +0800201 }
202 }
203 }).show();
204
205 return true;
206 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700207 // query the package manager to see if there's a registered handler
208 // that matches.
209 Intent intent = new Intent(Intent.ACTION_VIEW);
210 intent.setDataAndType(Uri.parse(url), mimetype);
Leon Scroggins63c02662010-11-18 15:16:27 -0500211 ResolveInfo info = activity.getPackageManager().resolveActivity(intent,
Michael Kolb8233fac2010-10-26 16:08:53 -0700212 PackageManager.MATCH_DEFAULT_ONLY);
213 if (info != null) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500214 ComponentName myName = activity.getComponentName();
Michael Kolb8233fac2010-10-26 16:08:53 -0700215 // If we resolved to ourselves, we don't want to attempt to
216 // load the url only to try and download it again.
217 if (!myName.getPackageName().equals(
218 info.activityInfo.packageName)
219 || !myName.getClassName().equals(
220 info.activityInfo.name)) {
221 // someone (other than us) knows how to handle this mime
222 // type with this scheme, don't download.
223 try {
Leon Scroggins63c02662010-11-18 15:16:27 -0500224 activity.startActivity(intent);
qqzhoua95a2e22013-04-18 17:28:31 +0800225 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700226 } catch (ActivityNotFoundException ex) {
227 if (LOGD_ENABLED) {
228 Log.d(LOGTAG, "activity not found for " + mimetype
229 + " over " + Uri.parse(url).getScheme(),
230 ex);
231 }
232 // Best behavior is to fall back to a download in this
233 // case
234 }
235 }
236 }
237 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500238 onDownloadStartNoStream(activity, url, userAgent, contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800239 mimetype, referer, privateBrowsing, contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +0800240 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700241 }
242
243 // This is to work around the fact that java.net.URI throws Exceptions
244 // instead of just encoding URL's properly
245 // Helper method for onDownloadStartNoStream
246 private static String encodePath(String path) {
247 char[] chars = path.toCharArray();
248
249 boolean needed = false;
250 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700251 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700252 needed = true;
253 break;
254 }
255 }
256 if (needed == false) {
257 return path;
258 }
259
260 StringBuilder sb = new StringBuilder("");
261 for (char c : chars) {
Selim Guruna770f8d2012-06-13 14:51:23 -0700262 if (c == '[' || c == ']' || c == '|') {
Michael Kolb8233fac2010-10-26 16:08:53 -0700263 sb.append('%');
264 sb.append(Integer.toHexString(c));
265 } else {
266 sb.append(c);
267 }
268 }
269
270 return sb.toString();
271 }
272
273 /**
274 * Notify the host application a download should be done, even if there
275 * is a streaming viewer available for thise type.
Leon Scroggins63c02662010-11-18 15:16:27 -0500276 * @param activity Activity requesting the download.
Michael Kolb8233fac2010-10-26 16:08:53 -0700277 * @param url The full url to the content that should be downloaded
Leon Scroggins63c02662010-11-18 15:16:27 -0500278 * @param userAgent User agent of the downloading application.
279 * @param contentDisposition Content-disposition http header, if present.
Michael Kolb8233fac2010-10-26 16:08:53 -0700280 * @param mimetype The mimetype of the content reported by the server
Selim Gurun0b3d66f2012-08-29 13:08:13 -0700281 * @param referer The referer associated with the downloaded url
Kristian Monsenbc5cc752011-03-02 13:14:03 +0000282 * @param privateBrowsing If the request is coming from a private browsing tab.
Michael Kolb8233fac2010-10-26 16:08:53 -0700283 */
luxiaol62677b02013-07-22 07:54:49 +0800284 /* package */static void onDownloadStartNoStream(Activity activity,
Leon Scroggins63c02662010-11-18 15:16:27 -0500285 String url, String userAgent, String contentDisposition,
luxiaol62677b02013-07-22 07:54:49 +0800286 String mimetype, String referer, boolean privateBrowsing, long contentLength) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700287
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700288 contentDisposition = trimContentDisposition(contentDisposition);
289
Michael Kolb8233fac2010-10-26 16:08:53 -0700290 String filename = URLUtil.guessFileName(url,
291 contentDisposition, mimetype);
292
293 // Check to see if we have an SDCard
294 String status = Environment.getExternalStorageState();
295 if (!status.equals(Environment.MEDIA_MOUNTED)) {
296 int title;
297 String msg;
298
299 // Check to see if the SDCard is busy, same as the music app
300 if (status.equals(Environment.MEDIA_SHARED)) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500301 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
Michael Kolb8233fac2010-10-26 16:08:53 -0700302 title = R.string.download_sdcard_busy_dlg_title;
303 } else {
Leon Scroggins63c02662010-11-18 15:16:27 -0500304 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700305 title = R.string.download_no_sdcard_dlg_title;
306 }
307
Leon Scroggins63c02662010-11-18 15:16:27 -0500308 new AlertDialog.Builder(activity)
Michael Kolb8233fac2010-10-26 16:08:53 -0700309 .setTitle(title)
Björn Lundén2aa8ba22012-05-31 23:05:56 +0200310 .setIconAttribute(android.R.attr.alertDialogIcon)
Michael Kolb8233fac2010-10-26 16:08:53 -0700311 .setMessage(msg)
312 .setPositiveButton(R.string.ok, null)
313 .show();
314 return;
315 }
316
Michael Kolb8233fac2010-10-26 16:08:53 -0700317 if (mimetype == null) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700318 // We must have long pressed on a link or image to download it. We
319 // are not sure of the mimetype in this case, so do a head request
luxiaol62677b02013-07-22 07:54:49 +0800320 new FetchUrlMimeType(activity, url, userAgent, referer,
321 privateBrowsing, filename).start();
Michael Kolb8233fac2010-10-26 16:08:53 -0700322 } else {
luxiaol62677b02013-07-22 07:54:49 +0800323 startDownloadSettings(activity, url, userAgent, contentDisposition, mimetype, referer,
324 privateBrowsing, contentLength, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700325 }
luxiaol62677b02013-07-22 07:54:49 +0800326
327 }
328
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700329 static String trimContentDisposition(String contentDisposition) {
330 final Pattern CONTENT_DISPOSITION_PATTERN =
Axesh R. Ajmera16c6bce2014-06-18 14:04:10 -0700331 Pattern.compile("filename\\s*=\\s*(\"?)([^\";]*)\\1\\s*",
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700332 Pattern.CASE_INSENSITIVE);
333
334 if (contentDisposition != null) {
335
336 try {
337 Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
338 if (m.find()) {
Axesh R. Ajmera9a293b02014-06-10 14:03:55 -0700339 contentDisposition = "attachment; filename="+m.group(2);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700340 }
Axesh R. Ajmera9a293b02014-06-10 14:03:55 -0700341
342 return contentDisposition;
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700343 } catch (IllegalStateException ex) {
344 // This function is defined as returning null when it can't parse the header
345 }
346 }
347 return null;
348 }
349
luxiaol62677b02013-07-22 07:54:49 +0800350 public static void initStorageDefaultPath(Context context) {
351 mExternalStorage = getExternalStorageDirectory(context);
352 if (isPhoneStorageSupported()) {
353 mInternalStorage = Environment.getExternalStorageDirectory().getPath();
354 } else {
355 mInternalStorage = null;
356 }
357 }
358
359 public static void startDownloadSettings(Activity activity,
360 String url, String userAgent, String contentDisposition,
361 String mimetype, String referer, boolean privateBrowsing, long contentLength,
362 String filename) {
363 Bundle fileInfo = new Bundle();
364 fileInfo.putString("url", url);
365 fileInfo.putString("userAgent", userAgent);
366 fileInfo.putString("contentDisposition", contentDisposition);
367 fileInfo.putString("mimetype", mimetype);
368 fileInfo.putString("referer", referer);
369 fileInfo.putLong("contentLength", contentLength);
370 fileInfo.putBoolean("privateBrowsing", privateBrowsing);
371 fileInfo.putString("filename", filename);
372 Intent intent = new Intent("android.intent.action.BROWSERDOWNLOAD");
Axesh R. Ajmera8a90fda2014-11-05 12:25:44 -0800373
374 // Since there could be multiple browsers capable of handling
375 // the same intent we assure that the same package handles it
376 intent.setPackage(activity.getPackageName());
377
luxiaol62677b02013-07-22 07:54:49 +0800378 intent.putExtras(fileInfo);
379 activity.startActivity(intent);
380 }
381
382 public static void setAppointedFolder(String downloadPath) {
383 File file = new File(downloadPath);
384 if (file.exists()) {
385 if (!file.isDirectory()) {
386 throw new IllegalStateException(file.getAbsolutePath() +
387 " already exists and is not a directory");
388 }
389 } else {
390 if (!file.mkdir()) {
391 throw new IllegalStateException("Unable to create directory: " +
392 file.getAbsolutePath());
393 }
394 }
395 }
396
397 private static void setDestinationDir(String downloadPath, String filename, Request request) {
398 File file = new File(downloadPath);
399 if (file.exists()) {
400 if (!file.isDirectory()) {
401 throw new IllegalStateException(file.getAbsolutePath() +
402 " already exists and is not a directory");
403 }
404 } else {
405 if (!file.mkdir()) {
406 throw new IllegalStateException("Unable to create directory: " +
407 file.getAbsolutePath());
408 }
409 }
410 setDestinationFromBase(file, filename, request);
411 }
412
413 private static void setDestinationFromBase(File file, String filename, Request request) {
414 if (filename == null) {
415 throw new NullPointerException("filename cannot be null");
416 }
417 request.setDestinationUri(Uri.withAppendedPath(Uri.fromFile(file), filename));
418 }
419
420 public static void fileExistQueryDialog(Activity activity) {
421 new AlertDialog.Builder(activity)
422 .setTitle(R.string.download_file_exist)
423 .setIcon(android.R.drawable.ic_dialog_info)
424 .setMessage(R.string.download_file_exist_msg)
425 // if yes, delete existed file and start new download thread
426 .setPositiveButton(R.string.ok, null)
427 // if no, do nothing at all
428 .show();
429 }
430
431 public static long getAvailableMemory(String root) {
432 StatFs stat = new StatFs(root);
433 final long LEFT10MByte = 2560;
434 long blockSize = stat.getBlockSize();
435 long availableBlocks = stat.getAvailableBlocks() - LEFT10MByte;
436 return availableBlocks * blockSize;
437 }
438
439 public static void showNoEnoughMemoryDialog(Activity mContext) {
440 new AlertDialog.Builder(mContext)
441 .setTitle(R.string.download_no_enough_memory)
442 .setIconAttribute(android.R.attr.alertDialogIcon)
443 .setMessage(R.string.download_no_enough_memory)
444 .setPositiveButton(R.string.ok, null)
445 .show();
446 }
447
kaiyize6a27d02013-08-22 15:08:19 +0800448 public static boolean manageNoEnoughMemory(long contentLength, String root) {
luxiaol62677b02013-07-22 07:54:49 +0800449 long mAvailableBytes = getAvailableMemory(root);
450 if (mAvailableBytes > 0) {
451 if (contentLength > mAvailableBytes) {
luxiaol62677b02013-07-22 07:54:49 +0800452 return true;
453 }
454 } else {
luxiaol62677b02013-07-22 07:54:49 +0800455 return true;
456 }
457 return false;
458 }
459
Panos Thomase57e3a02014-04-30 20:25:16 -0700460 public static void showStartDownloadToast(Activity activity,
461 boolean privateBrowsing) {
462 if (!privateBrowsing) {
463 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
464 activity.startActivity(intent);
465 } else {
466 activity.finish();
467 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500468 Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT)
Michael Kolb8233fac2010-10-26 16:08:53 -0700469 .show();
470 }
471
luxiaol62677b02013-07-22 07:54:49 +0800472 /**
473 * wheather the storage status OK for download file
474 *
475 * @param activity
476 * @param filename the download file's name
477 * @param downloadPath the download file's path will be in
478 * @return boolean true is ok,and false is not
479 */
480 public static boolean isStorageStatusOK(Activity activity, String filename, String downloadPath) {
481 if (downloadPath.equals(INVALID_PATH)) {
482 new AlertDialog.Builder(activity)
483 .setTitle(R.string.path_wrong)
484 .setIcon(android.R.drawable.ic_dialog_alert)
485 .setMessage(R.string.invalid_path)
486 .setPositiveButton(R.string.ok, null)
487 .show();
488 return false;
489 }
490
Axesh R. Ajmera8a90fda2014-11-05 12:25:44 -0800491 // assure that internal storage is initialized before
492 // comparing it with download path
493 if (mInternalStorage == null) {
494 initStorageDefaultPath(activity);
495 }
496
luxiaol62677b02013-07-22 07:54:49 +0800497 if (!(isPhoneStorageSupported() && downloadPath.contains(mInternalStorage))) {
498 String status = getExternalStorageState(activity);
499 if (!status.equals(Environment.MEDIA_MOUNTED)) {
500 int title;
501 String msg;
502
503 // Check to see if the SDCard is busy, same as the music app
504 if (status.equals(Environment.MEDIA_SHARED)) {
505 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
506 title = R.string.download_sdcard_busy_dlg_title;
507 } else {
508 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
509 title = R.string.download_no_sdcard_dlg_title;
510 }
511
512 new AlertDialog.Builder(activity)
513 .setTitle(title)
514 .setIcon(android.R.drawable.ic_dialog_alert)
515 .setMessage(msg)
516 .setPositiveButton(R.string.ok, null)
517 .show();
518 return false;
519 }
520 } else {
521 String status = Environment.getExternalStorageState();
522 if (!status.equals(Environment.MEDIA_MOUNTED)) {
523 int mTitle = R.string.download_path_unavailable_dlg_title;
524 String mMsg = activity.getString(R.string.download_path_unavailable_dlg_msg);
525 new AlertDialog.Builder(activity)
526 .setTitle(mTitle)
527 .setIcon(android.R.drawable.ic_dialog_alert)
528 .setMessage(mMsg)
529 .setPositiveButton(R.string.ok, null)
530 .show();
531 return false;
532 }
533 }
534 return true;
535 }
536
537 /**
538 * wheather support Phone Storage
539 *
540 * @return boolean true support Phone Storage ,false will be not
541 */
542 public static boolean isPhoneStorageSupported() {
543 return true;
544 }
545
546 /**
547 * show Dialog to warn filename is null
548 *
549 * @param activity
550 */
551 public static void showFilenameEmptyDialog(Activity activity) {
552 new AlertDialog.Builder(activity)
553 .setTitle(R.string.filename_empty_title)
554 .setIcon(android.R.drawable.ic_dialog_alert)
555 .setMessage(R.string.filename_empty_msg)
556 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
557 public void onClick(DialogInterface dialog, int which) {
558 }
559 })
560 .show();
561 }
562
563 /**
564 * get the filename except the suffix and dot
565 *
566 * @return String the filename except suffix and dot
567 */
568 public static String getFilenameBase(String filename) {
569 int dotindex = filename.lastIndexOf('.');
570 if (dotindex != -1) {
571 return filename.substring(0, dotindex);
572 } else {
573 return "";
574 }
575 }
576
577 /**
578 * get the filename's extension from filename
579 *
580 * @param filename the download filename, may be the user entered
581 * @return String the filename's extension
582 */
583 public static String getFilenameExtension(String filename) {
584 int dotindex = filename.lastIndexOf('.');
585 if (dotindex != -1) {
586 return filename.substring(dotindex + 1);
587 } else {
588 return "";
589 }
590 }
591
592 public static String getDefaultDownloadPath(Context context) {
593 String defaultDownloadPath;
594
595 String defaultStorage;
596 if (isPhoneStorageSupported()) {
597 defaultStorage = Environment.getExternalStorageDirectory().getPath();
598 } else {
599 defaultStorage = getExternalStorageDirectory(context);
600 }
601
kaiyize6a27d02013-08-22 15:08:19 +0800602 defaultDownloadPath = defaultStorage + context.getString(R.string.download_default_path);
luxiaol62677b02013-07-22 07:54:49 +0800603 Log.e(LOGTAG, "defaultStorage directory is : " + defaultDownloadPath);
604 return defaultDownloadPath;
605 }
606
607 /**
608 * translate the directory name into a name which is easy to know for user
609 *
610 * @param activity
611 * @param downloadPath
612 * @return String
613 */
614 public static String getDownloadPathForUser(Activity activity, String downloadPath) {
615 if (downloadPath == null) {
616 return downloadPath;
617 }
618 final String phoneStorageDir;
619 final String sdCardDir = getExternalStorageDirectory(activity);
620 if (isPhoneStorageSupported()) {
621 phoneStorageDir = Environment.getExternalStorageDirectory().getPath();
622 } else {
623 phoneStorageDir = null;
624 }
625
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800626 if (sdCardDir != null && downloadPath.startsWith(sdCardDir)) {
luxiaol62677b02013-07-22 07:54:49 +0800627 String sdCardLabel = activity.getResources().getString(
628 R.string.download_path_sd_card_label);
629 downloadPath = downloadPath.replace(sdCardDir, sdCardLabel);
630 } else if ((phoneStorageDir != null) && downloadPath.startsWith(phoneStorageDir)) {
631 String phoneStorageLabel = activity.getResources().getString(
kaiyizf1a66762013-09-16 16:59:43 +0800632 R.string.download_path_phone_storage_label);
luxiaol62677b02013-07-22 07:54:49 +0800633 downloadPath = downloadPath.replace(phoneStorageDir, phoneStorageLabel);
634 }
635 return downloadPath;
636 }
637
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800638 private static boolean isRemovable(Object obj) {
639 return (Boolean) ReflectHelper.invokeMethod(obj,
640 "isRemovable", null, null);
641 }
642
643 private static boolean allowMassStorage(Object obj) {
644 return (Boolean) ReflectHelper.invokeMethod(obj,
645 "allowMassStorage", null, null);
646 }
647
648 private static String getPath(Object obj) {
649 return (String) ReflectHelper.invokeMethod(obj,
650 "getPath", null, null);
651 }
652
luxiaol62677b02013-07-22 07:54:49 +0800653 private static String getExternalStorageDirectory(Context context) {
654 String sd = null;
655 StorageManager mStorageManager = (StorageManager) context
656 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800657 Object[] volumes = (Object[]) ReflectHelper.invokeMethod(
658 mStorageManager, "getVolumeList", null, null);
luxiaol62677b02013-07-22 07:54:49 +0800659 for (int i = 0; i < volumes.length; i++) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800660 if (isRemovable(volumes[i]) && allowMassStorage(volumes[i])) {
661 sd = getPath(volumes[i]);
Vivek Sekhar027ecad2014-04-15 05:42:38 -0700662 break;
luxiaol62677b02013-07-22 07:54:49 +0800663 }
664 }
665 return sd;
666 }
667
668 private static String getExternalStorageState(Context context) {
669 StorageManager mStorageManager = (StorageManager) context
670 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800671 String path = getExternalStorageDirectory(context);
672 Object[] params = {path};
673 Class[] type = new Class[] {String.class};
Bijan Amirzada63a855a2014-03-26 13:57:22 -0700674 return (String) ReflectHelper.invokeMethod(mStorageManager,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800675 "getVolumeState", type, params);
luxiaol62677b02013-07-22 07:54:49 +0800676 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700677}