blob: 05e7fe6205832b9b8ce49b8143b60b7934115e0a [file] [log] [blame]
luxiaol62677b02013-07-22 07:54:49 +08001/*
Axesh R. Ajmera7cfd7a72014-04-01 16:03:42 -07002 * Copyright (c) 2013,2014, The Linux Foundation. All rights reserved.
luxiaol62677b02013-07-22 07:54:49 +08003 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above
10 * copyright notice, this list of conditions and the following
11 * disclaimer in the documentation and/or other materials provided
12 * with the distribution.
13 * * Neither the name of The Linux Foundation nor the names of its
14 * contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
Bijan Amirzada41242f22014-03-21 12:12:18 -070030package com.android.browser;
luxiaol62677b02013-07-22 07:54:49 +080031
32import java.io.File;
33
34import android.app.Activity;
35import android.content.Intent;
36import java.lang.Thread;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080037
Bijan Amirzada41242f22014-03-21 12:12:18 -070038import com.android.browser.R;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080039
luxiaol62677b02013-07-22 07:54:49 +080040import android.net.Uri;
41import android.os.Bundle;
kaiyizf1a66762013-09-16 16:59:43 +080042import android.os.Environment;
luxiaol62677b02013-07-22 07:54:49 +080043import android.text.format.*;
44import android.util.Log;
45import android.view.View;
46import android.view.View.OnClickListener;
47import android.widget.Button;
48import android.widget.EditText;
jrizzoli700a8672015-10-18 00:15:07 +020049import android.widget.ImageButton;
luxiaol62677b02013-07-22 07:54:49 +080050import android.widget.TextView;
51import android.view.Window;
52import android.widget.Toast;
Axesh R. Ajmeraf9cb0cb2015-04-09 17:23:31 -070053import android.webkit.MimeTypeMap;
luxiaol62677b02013-07-22 07:54:49 +080054import android.text.TextUtils;
Vivek Sekhara3d93b12015-11-21 21:26:33 -080055import android.content.pm.PackageManager;
56import android.Manifest.permission;
luxiaol62677b02013-07-22 07:54:49 +080057
Axesh R. Ajmera7cfd7a72014-04-01 16:03:42 -070058import com.android.browser.reflect.ReflectHelper;
59
luxiaol62677b02013-07-22 07:54:49 +080060public class DownloadSettings extends Activity {
61
62 private EditText downloadFilenameET;
63 private EditText downloadPathET;
64 private TextView downloadEstimateSize;
65 private TextView downloadEstimateTime;
jrizzoli700a8672015-10-18 00:15:07 +020066 private ImageButton downloadStart;
67 private ImageButton downloadCancel;
luxiaol62677b02013-07-22 07:54:49 +080068 private String url;
69 private String userAgent;
70 private String contentDisposition;
71 private String mimetype;
72 private String referer;
Pankaj Garg5762b362015-11-02 07:57:06 -080073 private String authorization;
luxiaol62677b02013-07-22 07:54:49 +080074 private String filenameBase;
75 private String filename;
76 private String filenameExtension;
77 private boolean privateBrowsing;
78 private long contentLength;
79 private String downloadPath;
80 private String downloadPathForUser;
81 private static final int downloadRate = (1024 * 100 * 60);// Download Rate
82 // 100KB/s
83 private final static String LOGTAG = "DownloadSettings";
84 private final static int DOWNLOAD_PATH = 0;
85 private boolean isDownloadStarted = false;
86
87 private static final String ENV_EMULATED_STORAGE_TARGET = "EMULATED_STORAGE_TARGET";
Axesh R. Ajmera7cfd7a72014-04-01 16:03:42 -070088 private static final String APK_TYPE="apk";
89 private static final String OCTET_STREAM = "application/octet-stream";
luxiaol62677b02013-07-22 07:54:49 +080090
Vivek Sekhara3d93b12015-11-21 21:26:33 -080091 private int nextRequestCode = 2000;
92
luxiaol62677b02013-07-22 07:54:49 +080093 protected void onCreate(Bundle savedInstanceState) {
94 super.onCreate(savedInstanceState);
95 // initial the DownloadSettings view
96 requestWindowFeature(Window.FEATURE_NO_TITLE);
97 setContentView(R.layout.download_settings);
98 downloadFilenameET = (EditText) findViewById(R.id.download_filename_edit);
99 downloadPathET = (EditText) findViewById(R.id.download_filepath_selected);
100 downloadEstimateSize = (TextView) findViewById(R.id.download_estimate_size_content);
101 downloadEstimateTime = (TextView) findViewById(R.id.download_estimate_time_content);
jrizzoli700a8672015-10-18 00:15:07 +0200102 downloadStart = (ImageButton) findViewById(R.id.download_start);
103 downloadCancel = (ImageButton) findViewById(R.id.download_cancel);
luxiaol62677b02013-07-22 07:54:49 +0800104 downloadPathET.setOnClickListener(downloadPathListener);
105 downloadStart.setOnClickListener(downloadStartListener);
106 downloadCancel.setOnClickListener(downloadCancelListener);
107
108 // get the bundle from Intent
109 Intent intent = getIntent();
110 Bundle fileInfo = intent.getExtras();
111 url = fileInfo.getString("url");
112 userAgent = fileInfo.getString("userAgent");
113 contentDisposition = fileInfo.getString("contentDisposition");
114 mimetype = fileInfo.getString("mimetype");
115 referer = fileInfo.getString("referer");
Pankaj Garg5762b362015-11-02 07:57:06 -0800116 authorization = fileInfo.getString("authorization");
luxiaol62677b02013-07-22 07:54:49 +0800117 contentLength = fileInfo.getLong("contentLength");
118 privateBrowsing = fileInfo.getBoolean("privateBrowsing");
119 filename = fileInfo.getString("filename");
120
121 // download filenamebase's length is depended on filenameLength's values
122 // if filenamebase.length >= flienameLength, destroy the last string!
123
124 filenameBase = DownloadHandler.getFilenameBase(filename);
125 if (filenameBase.length() >= (BrowserUtils.FILENAME_MAX_LENGTH)) {
126 filenameBase = filenameBase.substring(0, BrowserUtils.FILENAME_MAX_LENGTH);
127 }
128
129 // warring when user enter more over letters into the EditText
130 BrowserUtils.maxLengthFilter(DownloadSettings.this, downloadFilenameET,
131 BrowserUtils.FILENAME_MAX_LENGTH);
132
133 downloadFilenameET.setText(filenameBase);
Axesh R. Ajmera7cfd7a72014-04-01 16:03:42 -0700134
135 String filenameExtension = DownloadHandler.getFilenameExtension(filename);
136
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700137 // introspect for octet stream mimetype what type of file extension it has
138 // and reassign mimetype
139 if (mimetype == null || mimetype.isEmpty() || mimetype.equals(OCTET_STREAM)) {
Axesh R. Ajmera7cfd7a72014-04-01 16:03:42 -0700140
141 String updatedFileName = filenameBase + "." + filenameExtension;
142 Object[] params = {updatedFileName};
143 Class[] type = new Class[] {String.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -0700144 mimetype = (String) ReflectHelper.invokeMethod("android.media.MediaFile",
Axesh R. Ajmeraf9cb0cb2015-04-09 17:23:31 -0700145 "getMimeTypeForFile", type, params);
Axesh R. Ajmera7cfd7a72014-04-01 16:03:42 -0700146 }
147
148 //Add special check for .apk files with octet-stream mimetype
Axesh R. Ajmera77258982014-04-02 14:39:09 -0700149 if (filenameExtension.equals(APK_TYPE) && mimetype != null && mimetype.equals(OCTET_STREAM)) {
Axesh R. Ajmera7cfd7a72014-04-01 16:03:42 -0700150 mimetype = "application/vnd.android.package-archive";
151 }
152
Axesh R. Ajmeraf9cb0cb2015-04-09 17:23:31 -0700153 // last way to fetch for mimetype if its still null
154 if (mimetype == null || mimetype.isEmpty())
155 mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(filenameExtension);
156
kaiyizf1a66762013-09-16 16:59:43 +0800157 downloadPath = chooseFolderFromMimeType(BrowserSettings.getInstance().getDownloadPath(),
158 mimetype);
luxiaol62677b02013-07-22 07:54:49 +0800159 downloadPathForUser = DownloadHandler.getDownloadPathForUser(DownloadSettings.this,
160 downloadPath);
Axesh R. Ajmeraf9cb0cb2015-04-09 17:23:31 -0700161
162 autoupdateFileName(filenameBase, DownloadHandler.getFilenameExtension(filename), downloadPath);
luxiaol62677b02013-07-22 07:54:49 +0800163 setDownloadPathForUserText(downloadPathForUser);
164 setDownloadFileSizeText();
165 setDownloadFileTimeText();
luxiaol62677b02013-07-22 07:54:49 +0800166 }
167
Axesh R. Ajmeraf9cb0cb2015-04-09 17:23:31 -0700168 private void autoupdateFileName(String filenameBase, String extension, String downloadPath) {
169 String fullPath = downloadPath + "/" + filenameBase + "." + extension;
170 int count = 1;
171 String newFilenameBase = "";
172
173 while(new File(fullPath).exists()) {
174 newFilenameBase = filenameBase+"-"+count++;
175 fullPath = downloadPath + "/" + newFilenameBase + "." + extension;
176 }
177
178 if(!TextUtils.isEmpty(newFilenameBase)) {
179 filenameBase = newFilenameBase;
180 }
181
182 downloadFilenameET.setText(filenameBase);
183 }
184
luxiaol62677b02013-07-22 07:54:49 +0800185 private OnClickListener downloadPathListener = new OnClickListener() {
186
187 @Override
188 public void onClick(View v) {
189
Vivek Sekharefefe6b2015-01-05 16:01:07 -0800190 final String filemanagerIntent =
191 getResources().getString(R.string.def_intent_file_manager);
192 if (!TextUtils.isEmpty(filemanagerIntent)) {
193 // start filemanager for getting download path
194 try {
195 Intent downloadPathIntent = new Intent(filemanagerIntent);
196 DownloadSettings.this.startActivityForResult(downloadPathIntent, DOWNLOAD_PATH);
197 } catch (Exception e) {
198 String err_msg = getString(R.string.activity_not_found,
199 filemanagerIntent);
200 Toast.makeText(DownloadSettings.this, err_msg, Toast.LENGTH_LONG).show();
201 }
202 } else {
203 Log.e(LOGTAG, "File Manager intent not defined !!");
luxiaol62677b02013-07-22 07:54:49 +0800204 }
205
206 }
207 };
208
209 private OnClickListener downloadStartListener = new OnClickListener() {
210
211 @Override
212 public void onClick(View v) {
213 filenameBase = getFilenameBaseFromUserEnter();
214 // check the filename user enter is null or not
Sagar Dhawan97ed6c92015-07-31 15:36:07 -0700215 if (TextUtils.isEmpty(filenameBase) || TextUtils.isEmpty(downloadPath)) {
luxiaol62677b02013-07-22 07:54:49 +0800216 DownloadHandler.showFilenameEmptyDialog(DownloadSettings.this);
217 return;
218 }
219
220 filenameExtension = DownloadHandler.getFilenameExtension(filename);
221 filename = filenameBase + "." + filenameExtension;
222
223 // check the storage status
224 if (!DownloadHandler.isStorageStatusOK(DownloadSettings.this, filename, downloadPath)) {
225 return;
226 }
227
228 // check the storage memory enough or not
229 try {
230 DownloadHandler.setAppointedFolder(downloadPath);
231 } catch (Exception e) {
232 DownloadHandler.showNoEnoughMemoryDialog(DownloadSettings.this);
233 return;
234 }
kaiyize6a27d02013-08-22 15:08:19 +0800235 boolean isNoEnoughMemory = DownloadHandler.manageNoEnoughMemory(contentLength,
236 downloadPath);
luxiaol62677b02013-07-22 07:54:49 +0800237 if (isNoEnoughMemory) {
kaiyize6a27d02013-08-22 15:08:19 +0800238 DownloadHandler.showNoEnoughMemoryDialog(DownloadSettings.this);
luxiaol62677b02013-07-22 07:54:49 +0800239 return;
240 }
241
242 // check the download file is exist or not
243 String fullFilename = downloadPath + "/" + filename;
244 if (mimetype != null && new File(fullFilename).exists()) {
245 DownloadHandler.fileExistQueryDialog(DownloadSettings.this);
246 return;
247 }
248
Vivek Sekhara3d93b12015-11-21 21:26:33 -0800249 // check for permission
250 if (!hasPermission(permission.WRITE_EXTERNAL_STORAGE)) {
251 requestPermissions(new String[] {permission.WRITE_EXTERNAL_STORAGE},
252 ++nextRequestCode);
253 } else {
254 download();
255 }
luxiaol62677b02013-07-22 07:54:49 +0800256 }
257 };
258
Vivek Sekhara3d93b12015-11-21 21:26:33 -0800259 @Override
260 public void onRequestPermissionsResult(int requestCode,
261 String[] permissions, int[] grantResults) {
262 if (nextRequestCode == requestCode) {
263 if (grantResults.length > 0
264 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
265 download();
266 } else {
267 finish();
268 }
269 }
270 }
271
272 private void download() {
273 // staring downloading
274 DownloadHandler.startingDownload(DownloadSettings.this,
275 url, userAgent, contentDisposition,
276 mimetype, referer, authorization,
277 privateBrowsing, contentLength,
278 Uri.encode(filename), downloadPath);
279 isDownloadStarted = true;
280 }
281
282 private boolean hasPermission(String permission) {
283 return (checkCallingOrSelfPermission(permission)
284 == PackageManager.PERMISSION_GRANTED);
285 }
286
luxiaol62677b02013-07-22 07:54:49 +0800287 private OnClickListener downloadCancelListener = new OnClickListener() {
luxiaol62677b02013-07-22 07:54:49 +0800288 @Override
289 public void onClick(View v) {
290 finish();
291 }
292 };
293
294 protected void onDestroy() {
295 super.onDestroy();
296 }
297
298 protected void onPause() {
299 super.onPause();
300 if (isDownloadStarted) {
301 finish();
302 }
303 }
304
305 protected void onResume() {
306 super.onResume();
Vivek Sekhara3d93b12015-11-21 21:26:33 -0800307 if (isDownloadStarted) {
308 finish();
309 }
luxiaol62677b02013-07-22 07:54:49 +0800310 }
311
312 @Override
313 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
Vivek Sekharefefe6b2015-01-05 16:01:07 -0800314
luxiaol62677b02013-07-22 07:54:49 +0800315 if (DOWNLOAD_PATH == requestCode) {
Vivek Sekharefefe6b2015-01-05 16:01:07 -0800316 if (resultCode == Activity.RESULT_OK && intent != null) {
317 final String result_dir_sel =
318 getResources().getString(R.string.def_file_manager_result_dir);
319 downloadPath = intent.getStringExtra(result_dir_sel);
Vivek Sekhar76074ac2014-06-27 16:33:13 -0700320 // Fallback logic to stock browser
321 if (downloadPath == null) {
322 Uri uri = intent.getData();
323 if(uri != null)
324 downloadPath = uri.getPath();
325 }
luxiaol62677b02013-07-22 07:54:49 +0800326 if (downloadPath != null) {
327 String rawEmulatedStorageTarget = System.getenv(ENV_EMULATED_STORAGE_TARGET);
328 if (!TextUtils.isEmpty(rawEmulatedStorageTarget)) {
329 if (downloadPath.startsWith("/storage/sdcard0"))
330 downloadPath = downloadPath.replace("/storage/sdcard0",
331 "/storage/emulated/0");
332 if (downloadPath.startsWith("/storage/emulated/legacy"))
333 downloadPath = downloadPath.replace("/storage/emulated/legacy",
334 "/storage/emulated/0");
335 }
336 downloadPathForUser = DownloadHandler.getDownloadPathForUser(
337 DownloadSettings.this, downloadPath);
338 setDownloadPathForUserText(downloadPathForUser);
339 }
340 }
341 }
342 }
343
kaiyizf1a66762013-09-16 16:59:43 +0800344 // Add for carrier feature - download to related folders by mimetype.
345 private static String chooseFolderFromMimeType(String path, String mimeType) {
346 String destinationFolder = null;
347 if (!path.contains(Environment.DIRECTORY_DOWNLOADS) || null == mimeType)
348 return path;
349 if (mimeType.startsWith("audio"))
350 destinationFolder = Environment.DIRECTORY_MUSIC;
351 else if (mimeType.startsWith("video"))
352 destinationFolder = Environment.DIRECTORY_MOVIES;
353 else if (mimeType.startsWith("image"))
354 destinationFolder = Environment.DIRECTORY_PICTURES;
355 if (null != destinationFolder)
356 path = path.replace(Environment.DIRECTORY_DOWNLOADS, destinationFolder);
357 return path;
358 }
359
luxiaol62677b02013-07-22 07:54:49 +0800360 /**
361 * show download path for user
362 *
363 * @param downloadPath the download path user can see
364 */
365 private void setDownloadPathForUserText(String downloadPathForUser) {
366 downloadPathET.setText(downloadPathForUser);
367 }
368
369 /**
370 * get the filename from user select the download path
371 *
372 * @return String the filename from user selected
373 */
374 private String getFilenameBaseFromUserEnter() {
375 return downloadFilenameET.getText().toString();
376 }
377
378 /**
379 * set the download file size for user to be known
380 */
381 private void setDownloadFileSizeText() {
382 String sizeText;
383 if (contentLength <= 0) {
384 sizeText = getString(R.string.unknow_length);
385 } else {
386 sizeText = getDownloadFileSize();
387 }
388 downloadEstimateSize.setText(sizeText);
389
390 }
391
392 /**
393 * set the time which downloaded this file will be estimately use;
394 */
395 private void setDownloadFileTimeText() {
396 String neededTimeText;
397 if (contentLength <= 0) {
398 neededTimeText = getString(R.string.unknow_length);
399 } else {
400 neededTimeText = getNeededTime() + getString(R.string.time_min);
401 }
402 downloadEstimateTime.setText(neededTimeText);
403 }
404
405 /**
406 * count the download file's size and format the values
407 *
408 * @return String the format values
409 */
410 private String getDownloadFileSize() {
411 String currentSizeText = "";
412 if (contentLength > 0) {
413 currentSizeText = Formatter.formatFileSize(DownloadSettings.this, contentLength);
414 }
415 return currentSizeText;
416 }
417
418 /**
419 * get the time download this file will be use,and format this time values
420 *
421 * @return long the valses of time which download this file will be use
422 */
423 private long getNeededTime() {
424 long timeNeeded = contentLength / downloadRate;
425 if (timeNeeded < 1) {
426 timeNeeded = 1;
427 }
428 Log.e(LOGTAG, "TimeNeeded:" + timeNeeded + "min");
429 // return the time like 5 min, not 5 s;
430 return timeNeeded;
431 }
432}