blob: 0e417015029e04176748832c2406bf3ad2d07e5d [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
luxiaol62677b02013-07-22 07:54:49 +0800288 initStorageDefaultPath(activity);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700289
290 contentDisposition = trimContentDisposition(contentDisposition);
291
Michael Kolb8233fac2010-10-26 16:08:53 -0700292 String filename = URLUtil.guessFileName(url,
293 contentDisposition, mimetype);
294
295 // Check to see if we have an SDCard
296 String status = Environment.getExternalStorageState();
297 if (!status.equals(Environment.MEDIA_MOUNTED)) {
298 int title;
299 String msg;
300
301 // Check to see if the SDCard is busy, same as the music app
302 if (status.equals(Environment.MEDIA_SHARED)) {
Leon Scroggins63c02662010-11-18 15:16:27 -0500303 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
Michael Kolb8233fac2010-10-26 16:08:53 -0700304 title = R.string.download_sdcard_busy_dlg_title;
305 } else {
Leon Scroggins63c02662010-11-18 15:16:27 -0500306 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700307 title = R.string.download_no_sdcard_dlg_title;
308 }
309
Leon Scroggins63c02662010-11-18 15:16:27 -0500310 new AlertDialog.Builder(activity)
Michael Kolb8233fac2010-10-26 16:08:53 -0700311 .setTitle(title)
Björn Lundén2aa8ba22012-05-31 23:05:56 +0200312 .setIconAttribute(android.R.attr.alertDialogIcon)
Michael Kolb8233fac2010-10-26 16:08:53 -0700313 .setMessage(msg)
314 .setPositiveButton(R.string.ok, null)
315 .show();
316 return;
317 }
318
Michael Kolb8233fac2010-10-26 16:08:53 -0700319 if (mimetype == null) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700320 // We must have long pressed on a link or image to download it. We
321 // are not sure of the mimetype in this case, so do a head request
luxiaol62677b02013-07-22 07:54:49 +0800322 new FetchUrlMimeType(activity, url, userAgent, referer,
323 privateBrowsing, filename).start();
Michael Kolb8233fac2010-10-26 16:08:53 -0700324 } else {
luxiaol62677b02013-07-22 07:54:49 +0800325 startDownloadSettings(activity, url, userAgent, contentDisposition, mimetype, referer,
326 privateBrowsing, contentLength, filename);
Michael Kolb8233fac2010-10-26 16:08:53 -0700327 }
luxiaol62677b02013-07-22 07:54:49 +0800328
329 }
330
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700331 static String trimContentDisposition(String contentDisposition) {
332 final Pattern CONTENT_DISPOSITION_PATTERN =
Axesh R. Ajmera9a293b02014-06-10 14:03:55 -0700333 Pattern.compile("filename\\s*=\\s*(\"?)([^\"]*)\\1\\s*;?",
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700334 Pattern.CASE_INSENSITIVE);
335
336 if (contentDisposition != null) {
337
338 try {
339 Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
340 if (m.find()) {
Axesh R. Ajmera9a293b02014-06-10 14:03:55 -0700341 contentDisposition = "attachment; filename="+m.group(2);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700342 }
Axesh R. Ajmera9a293b02014-06-10 14:03:55 -0700343
344 return contentDisposition;
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700345 } catch (IllegalStateException ex) {
346 // This function is defined as returning null when it can't parse the header
347 }
348 }
349 return null;
350 }
351
luxiaol62677b02013-07-22 07:54:49 +0800352 public static void initStorageDefaultPath(Context context) {
353 mExternalStorage = getExternalStorageDirectory(context);
354 if (isPhoneStorageSupported()) {
355 mInternalStorage = Environment.getExternalStorageDirectory().getPath();
356 } else {
357 mInternalStorage = null;
358 }
359 }
360
361 public static void startDownloadSettings(Activity activity,
362 String url, String userAgent, String contentDisposition,
363 String mimetype, String referer, boolean privateBrowsing, long contentLength,
364 String filename) {
365 Bundle fileInfo = new Bundle();
366 fileInfo.putString("url", url);
367 fileInfo.putString("userAgent", userAgent);
368 fileInfo.putString("contentDisposition", contentDisposition);
369 fileInfo.putString("mimetype", mimetype);
370 fileInfo.putString("referer", referer);
371 fileInfo.putLong("contentLength", contentLength);
372 fileInfo.putBoolean("privateBrowsing", privateBrowsing);
373 fileInfo.putString("filename", filename);
374 Intent intent = new Intent("android.intent.action.BROWSERDOWNLOAD");
375 intent.putExtras(fileInfo);
376 activity.startActivity(intent);
377 }
378
379 public static void setAppointedFolder(String downloadPath) {
380 File file = new File(downloadPath);
381 if (file.exists()) {
382 if (!file.isDirectory()) {
383 throw new IllegalStateException(file.getAbsolutePath() +
384 " already exists and is not a directory");
385 }
386 } else {
387 if (!file.mkdir()) {
388 throw new IllegalStateException("Unable to create directory: " +
389 file.getAbsolutePath());
390 }
391 }
392 }
393
394 private static void setDestinationDir(String downloadPath, String filename, Request request) {
395 File file = new File(downloadPath);
396 if (file.exists()) {
397 if (!file.isDirectory()) {
398 throw new IllegalStateException(file.getAbsolutePath() +
399 " already exists and is not a directory");
400 }
401 } else {
402 if (!file.mkdir()) {
403 throw new IllegalStateException("Unable to create directory: " +
404 file.getAbsolutePath());
405 }
406 }
407 setDestinationFromBase(file, filename, request);
408 }
409
410 private static void setDestinationFromBase(File file, String filename, Request request) {
411 if (filename == null) {
412 throw new NullPointerException("filename cannot be null");
413 }
414 request.setDestinationUri(Uri.withAppendedPath(Uri.fromFile(file), filename));
415 }
416
417 public static void fileExistQueryDialog(Activity activity) {
418 new AlertDialog.Builder(activity)
419 .setTitle(R.string.download_file_exist)
420 .setIcon(android.R.drawable.ic_dialog_info)
421 .setMessage(R.string.download_file_exist_msg)
422 // if yes, delete existed file and start new download thread
423 .setPositiveButton(R.string.ok, null)
424 // if no, do nothing at all
425 .show();
426 }
427
428 public static long getAvailableMemory(String root) {
429 StatFs stat = new StatFs(root);
430 final long LEFT10MByte = 2560;
431 long blockSize = stat.getBlockSize();
432 long availableBlocks = stat.getAvailableBlocks() - LEFT10MByte;
433 return availableBlocks * blockSize;
434 }
435
436 public static void showNoEnoughMemoryDialog(Activity mContext) {
437 new AlertDialog.Builder(mContext)
438 .setTitle(R.string.download_no_enough_memory)
439 .setIconAttribute(android.R.attr.alertDialogIcon)
440 .setMessage(R.string.download_no_enough_memory)
441 .setPositiveButton(R.string.ok, null)
442 .show();
443 }
444
kaiyize6a27d02013-08-22 15:08:19 +0800445 public static boolean manageNoEnoughMemory(long contentLength, String root) {
luxiaol62677b02013-07-22 07:54:49 +0800446 long mAvailableBytes = getAvailableMemory(root);
447 if (mAvailableBytes > 0) {
448 if (contentLength > mAvailableBytes) {
luxiaol62677b02013-07-22 07:54:49 +0800449 return true;
450 }
451 } else {
luxiaol62677b02013-07-22 07:54:49 +0800452 return true;
453 }
454 return false;
455 }
456
Panos Thomase57e3a02014-04-30 20:25:16 -0700457 public static void showStartDownloadToast(Activity activity,
458 boolean privateBrowsing) {
459 if (!privateBrowsing) {
460 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
461 activity.startActivity(intent);
462 } else {
463 activity.finish();
464 }
Leon Scroggins63c02662010-11-18 15:16:27 -0500465 Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT)
Michael Kolb8233fac2010-10-26 16:08:53 -0700466 .show();
467 }
468
luxiaol62677b02013-07-22 07:54:49 +0800469 /**
470 * wheather the storage status OK for download file
471 *
472 * @param activity
473 * @param filename the download file's name
474 * @param downloadPath the download file's path will be in
475 * @return boolean true is ok,and false is not
476 */
477 public static boolean isStorageStatusOK(Activity activity, String filename, String downloadPath) {
478 if (downloadPath.equals(INVALID_PATH)) {
479 new AlertDialog.Builder(activity)
480 .setTitle(R.string.path_wrong)
481 .setIcon(android.R.drawable.ic_dialog_alert)
482 .setMessage(R.string.invalid_path)
483 .setPositiveButton(R.string.ok, null)
484 .show();
485 return false;
486 }
487
488 if (!(isPhoneStorageSupported() && downloadPath.contains(mInternalStorage))) {
489 String status = getExternalStorageState(activity);
490 if (!status.equals(Environment.MEDIA_MOUNTED)) {
491 int title;
492 String msg;
493
494 // Check to see if the SDCard is busy, same as the music app
495 if (status.equals(Environment.MEDIA_SHARED)) {
496 msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
497 title = R.string.download_sdcard_busy_dlg_title;
498 } else {
499 msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
500 title = R.string.download_no_sdcard_dlg_title;
501 }
502
503 new AlertDialog.Builder(activity)
504 .setTitle(title)
505 .setIcon(android.R.drawable.ic_dialog_alert)
506 .setMessage(msg)
507 .setPositiveButton(R.string.ok, null)
508 .show();
509 return false;
510 }
511 } else {
512 String status = Environment.getExternalStorageState();
513 if (!status.equals(Environment.MEDIA_MOUNTED)) {
514 int mTitle = R.string.download_path_unavailable_dlg_title;
515 String mMsg = activity.getString(R.string.download_path_unavailable_dlg_msg);
516 new AlertDialog.Builder(activity)
517 .setTitle(mTitle)
518 .setIcon(android.R.drawable.ic_dialog_alert)
519 .setMessage(mMsg)
520 .setPositiveButton(R.string.ok, null)
521 .show();
522 return false;
523 }
524 }
525 return true;
526 }
527
528 /**
529 * wheather support Phone Storage
530 *
531 * @return boolean true support Phone Storage ,false will be not
532 */
533 public static boolean isPhoneStorageSupported() {
534 return true;
535 }
536
537 /**
538 * show Dialog to warn filename is null
539 *
540 * @param activity
541 */
542 public static void showFilenameEmptyDialog(Activity activity) {
543 new AlertDialog.Builder(activity)
544 .setTitle(R.string.filename_empty_title)
545 .setIcon(android.R.drawable.ic_dialog_alert)
546 .setMessage(R.string.filename_empty_msg)
547 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
548 public void onClick(DialogInterface dialog, int which) {
549 }
550 })
551 .show();
552 }
553
554 /**
555 * get the filename except the suffix and dot
556 *
557 * @return String the filename except suffix and dot
558 */
559 public static String getFilenameBase(String filename) {
560 int dotindex = filename.lastIndexOf('.');
561 if (dotindex != -1) {
562 return filename.substring(0, dotindex);
563 } else {
564 return "";
565 }
566 }
567
568 /**
569 * get the filename's extension from filename
570 *
571 * @param filename the download filename, may be the user entered
572 * @return String the filename's extension
573 */
574 public static String getFilenameExtension(String filename) {
575 int dotindex = filename.lastIndexOf('.');
576 if (dotindex != -1) {
577 return filename.substring(dotindex + 1);
578 } else {
579 return "";
580 }
581 }
582
583 public static String getDefaultDownloadPath(Context context) {
584 String defaultDownloadPath;
585
586 String defaultStorage;
587 if (isPhoneStorageSupported()) {
588 defaultStorage = Environment.getExternalStorageDirectory().getPath();
589 } else {
590 defaultStorage = getExternalStorageDirectory(context);
591 }
592
kaiyize6a27d02013-08-22 15:08:19 +0800593 defaultDownloadPath = defaultStorage + context.getString(R.string.download_default_path);
luxiaol62677b02013-07-22 07:54:49 +0800594 Log.e(LOGTAG, "defaultStorage directory is : " + defaultDownloadPath);
595 return defaultDownloadPath;
596 }
597
598 /**
599 * translate the directory name into a name which is easy to know for user
600 *
601 * @param activity
602 * @param downloadPath
603 * @return String
604 */
605 public static String getDownloadPathForUser(Activity activity, String downloadPath) {
606 if (downloadPath == null) {
607 return downloadPath;
608 }
609 final String phoneStorageDir;
610 final String sdCardDir = getExternalStorageDirectory(activity);
611 if (isPhoneStorageSupported()) {
612 phoneStorageDir = Environment.getExternalStorageDirectory().getPath();
613 } else {
614 phoneStorageDir = null;
615 }
616
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800617 if (sdCardDir != null && downloadPath.startsWith(sdCardDir)) {
luxiaol62677b02013-07-22 07:54:49 +0800618 String sdCardLabel = activity.getResources().getString(
619 R.string.download_path_sd_card_label);
620 downloadPath = downloadPath.replace(sdCardDir, sdCardLabel);
621 } else if ((phoneStorageDir != null) && downloadPath.startsWith(phoneStorageDir)) {
622 String phoneStorageLabel = activity.getResources().getString(
kaiyizf1a66762013-09-16 16:59:43 +0800623 R.string.download_path_phone_storage_label);
luxiaol62677b02013-07-22 07:54:49 +0800624 downloadPath = downloadPath.replace(phoneStorageDir, phoneStorageLabel);
625 }
626 return downloadPath;
627 }
628
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800629 private static boolean isRemovable(Object obj) {
630 return (Boolean) ReflectHelper.invokeMethod(obj,
631 "isRemovable", null, null);
632 }
633
634 private static boolean allowMassStorage(Object obj) {
635 return (Boolean) ReflectHelper.invokeMethod(obj,
636 "allowMassStorage", null, null);
637 }
638
639 private static String getPath(Object obj) {
640 return (String) ReflectHelper.invokeMethod(obj,
641 "getPath", null, null);
642 }
643
luxiaol62677b02013-07-22 07:54:49 +0800644 private static String getExternalStorageDirectory(Context context) {
645 String sd = null;
646 StorageManager mStorageManager = (StorageManager) context
647 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800648 Object[] volumes = (Object[]) ReflectHelper.invokeMethod(
649 mStorageManager, "getVolumeList", null, null);
luxiaol62677b02013-07-22 07:54:49 +0800650 for (int i = 0; i < volumes.length; i++) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800651 if (isRemovable(volumes[i]) && allowMassStorage(volumes[i])) {
652 sd = getPath(volumes[i]);
Vivek Sekhar027ecad2014-04-15 05:42:38 -0700653 break;
luxiaol62677b02013-07-22 07:54:49 +0800654 }
655 }
656 return sd;
657 }
658
659 private static String getExternalStorageState(Context context) {
660 StorageManager mStorageManager = (StorageManager) context
661 .getSystemService(Context.STORAGE_SERVICE);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800662 String path = getExternalStorageDirectory(context);
663 Object[] params = {path};
664 Class[] type = new Class[] {String.class};
Bijan Amirzada63a855a2014-03-26 13:57:22 -0700665 return (String) ReflectHelper.invokeMethod(mStorageManager,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800666 "getVolumeState", type, params);
luxiaol62677b02013-07-22 07:54:49 +0800667 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700668}