Execute the file to upload copy in an AsyncTask
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / Uploader.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Bartek Przybylski
5 * Copyright (C) 2012 Bartek Przybylski
6 * Copyright (C) 2015 ownCloud Inc.
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 package com.owncloud.android.ui.activity;
23
24 import java.io.File;
25 import java.io.FileDescriptor;
26 import java.io.FileInputStream;
27 import java.io.FileNotFoundException;
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.LinkedList;
34 import java.util.List;
35 import java.util.Stack;
36 import java.util.Vector;
37 import java.util.concurrent.ExecutionException;
38
39 import android.accounts.Account;
40 import android.accounts.AccountManager;
41 import android.app.AlertDialog;
42 import android.app.AlertDialog.Builder;
43 import android.app.Dialog;
44 import android.app.ProgressDialog;
45 import android.content.Context;
46 import android.content.DialogInterface;
47 import android.content.DialogInterface.OnCancelListener;
48 import android.content.DialogInterface.OnClickListener;
49 import android.content.Intent;
50 import android.content.SharedPreferences;
51 import android.content.res.Resources.NotFoundException;
52 import android.database.Cursor;
53 import android.net.Uri;
54 import android.os.Bundle;
55 import android.os.ParcelFileDescriptor;
56 import android.os.Parcelable;
57 import android.preference.PreferenceManager;
58 import android.provider.MediaStore.Audio;
59 import android.provider.MediaStore.Images;
60 import android.provider.MediaStore.Video;
61 import android.view.View;
62 import android.widget.AdapterView;
63 import android.widget.AdapterView.OnItemClickListener;
64 import android.widget.Button;
65 import android.widget.EditText;
66 import android.widget.ListView;
67 import android.widget.SimpleAdapter;
68 import android.widget.Toast;
69
70 import com.actionbarsherlock.app.ActionBar;
71 import com.actionbarsherlock.view.MenuItem;
72 import com.owncloud.android.MainApp;
73 import com.owncloud.android.R;
74 import com.owncloud.android.authentication.AccountAuthenticator;
75 import com.owncloud.android.datamodel.OCFile;
76 import com.owncloud.android.files.services.FileUploader;
77 import com.owncloud.android.lib.common.operations.RemoteOperation;
78 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
79 import com.owncloud.android.lib.common.utils.Log_OC;
80 import com.owncloud.android.operations.CreateFolderOperation;
81 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
82 import com.owncloud.android.utils.CopyTmpFileAsyncTask;
83 import com.owncloud.android.utils.DisplayUtils;
84 import com.owncloud.android.utils.ErrorMessageAdapter;
85 import com.owncloud.android.utils.FileStorageUtils;
86 import com.owncloud.android.utils.UriUtils;
87
88
89 /**
90 * This can be used to upload things to an ownCloud instance.
91 */
92 public class Uploader extends FileActivity
93 implements OnItemClickListener, android.view.View.OnClickListener,
94 CopyTmpFileAsyncTask.OnCopyTmpFileTaskListener {
95
96 private static final String TAG = Uploader.class.getSimpleName();
97
98 private AccountManager mAccountManager;
99 private Stack<String> mParents;
100 private ArrayList<Parcelable> mStreamsToUpload;
101 private boolean mCreateDir;
102 private String mUploadPath;
103 private OCFile mFile;
104 private boolean mAccountSelected;
105
106 private final static int DIALOG_NO_ACCOUNT = 0;
107 private final static int DIALOG_WAITING = 1;
108 private final static int DIALOG_NO_STREAM = 2;
109 private final static int DIALOG_MULTIPLE_ACCOUNT = 3;
110
111 private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;
112
113 private final static String KEY_PARENTS = "PARENTS";
114 private final static String KEY_FILE = "FILE";
115 private final static String KEY_ACCOUNT_SELECTED = "ACCOUNT_SELECTED";
116
117 @Override
118 protected void onCreate(Bundle savedInstanceState) {
119 prepareStreamsToUpload();
120
121 if (savedInstanceState == null) {
122 mParents = new Stack<String>();
123 mAccountSelected = false;
124 } else {
125 mParents = (Stack<String>) savedInstanceState.getSerializable(KEY_PARENTS);
126 mFile = savedInstanceState.getParcelable(KEY_FILE);
127 mAccountSelected = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTED);
128 }
129 super.onCreate(savedInstanceState);
130
131 ActionBar actionBar = getSupportActionBar();
132 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
133
134 }
135
136 @Override
137 protected void setAccount(Account account, boolean savedAccount) {
138 if (somethingToUpload()) {
139 mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
140 Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAccountType());
141 if (accounts.length == 0) {
142 Log_OC.i(TAG, "No ownCloud account is available");
143 showDialog(DIALOG_NO_ACCOUNT);
144 } else if (accounts.length > 1 && !mAccountSelected) {
145 Log_OC.i(TAG, "More than one ownCloud is available");
146 showDialog(DIALOG_MULTIPLE_ACCOUNT);
147 } else {
148 if (!savedAccount) {
149 setAccount(accounts[0]);
150 }
151 }
152
153 } else {
154 showDialog(DIALOG_NO_STREAM);
155 }
156
157 super.setAccount(account, savedAccount);
158 }
159
160 @Override
161 protected void onAccountSet(boolean stateWasRecovered) {
162 super.onAccountSet(mAccountWasRestored);
163 initTargetFolder();
164 populateDirectoryList();
165 }
166
167 @Override
168 protected void onSaveInstanceState(Bundle outState) {
169 Log_OC.d(TAG, "onSaveInstanceState() start");
170 super.onSaveInstanceState(outState);
171 outState.putSerializable(KEY_PARENTS, mParents);
172 //outState.putParcelable(KEY_ACCOUNT, mAccount);
173 outState.putParcelable(KEY_FILE, mFile);
174 outState.putBoolean(KEY_ACCOUNT_SELECTED, mAccountSelected);
175
176 Log_OC.d(TAG, "onSaveInstanceState() end");
177 }
178
179 @Override
180 protected Dialog onCreateDialog(final int id) {
181 final AlertDialog.Builder builder = new Builder(this);
182 switch (id) {
183 case DIALOG_WAITING:
184 ProgressDialog pDialog = new ProgressDialog(this);
185 pDialog.setIndeterminate(false);
186 pDialog.setCancelable(false);
187 pDialog.setMessage(getResources().getString(R.string.uploader_info_uploading));
188 return pDialog;
189 case DIALOG_NO_ACCOUNT:
190 builder.setIcon(android.R.drawable.ic_dialog_alert);
191 builder.setTitle(R.string.uploader_wrn_no_account_title);
192 builder.setMessage(String.format(
193 getString(R.string.uploader_wrn_no_account_text), getString(R.string.app_name)));
194 builder.setCancelable(false);
195 builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
196 @Override
197 public void onClick(DialogInterface dialog, int which) {
198 if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
199 // using string value since in API7 this
200 // constatn is not defined
201 // in API7 < this constatant is defined in
202 // Settings.ADD_ACCOUNT_SETTINGS
203 // and Settings.EXTRA_AUTHORITIES
204 Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
205 intent.putExtra("authorities", new String[] { MainApp.getAuthTokenType() });
206 startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
207 } else {
208 // since in API7 there is no direct call for
209 // account setup, so we need to
210 // show our own AccountSetupAcricity, get
211 // desired results and setup
212 // everything for ourself
213 Intent intent = new Intent(getBaseContext(), AccountAuthenticator.class);
214 startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
215 }
216 }
217 });
218 builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {
219 @Override
220 public void onClick(DialogInterface dialog, int which) {
221 finish();
222 }
223 });
224 return builder.create();
225 case DIALOG_MULTIPLE_ACCOUNT:
226 CharSequence ac[] = new CharSequence[
227 mAccountManager.getAccountsByType(MainApp.getAccountType()).length];
228 for (int i = 0; i < ac.length; ++i) {
229 ac[i] = DisplayUtils.convertIdn(
230 mAccountManager.getAccountsByType(MainApp.getAccountType())[i].name, false);
231 }
232 builder.setTitle(R.string.common_choose_account);
233 builder.setItems(ac, new OnClickListener() {
234 @Override
235 public void onClick(DialogInterface dialog, int which) {
236 setAccount(mAccountManager.getAccountsByType(MainApp.getAccountType())[which]);
237 onAccountSet(mAccountWasRestored);
238 dialog.dismiss();
239 mAccountSelected = true;
240 }
241 });
242 builder.setCancelable(true);
243 builder.setOnCancelListener(new OnCancelListener() {
244 @Override
245 public void onCancel(DialogInterface dialog) {
246 dialog.cancel();
247 finish();
248 }
249 });
250 return builder.create();
251 case DIALOG_NO_STREAM:
252 builder.setIcon(android.R.drawable.ic_dialog_alert);
253 builder.setTitle(R.string.uploader_wrn_no_content_title);
254 builder.setMessage(R.string.uploader_wrn_no_content_text);
255 builder.setCancelable(false);
256 builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
257 @Override
258 public void onClick(DialogInterface dialog, int which) {
259 finish();
260 }
261 });
262 return builder.create();
263 default:
264 throw new IllegalArgumentException("Unknown dialog id: " + id);
265 }
266 }
267
268 class a implements OnClickListener {
269 String mPath;
270 EditText mDirname;
271
272 public a(String path, EditText dirname) {
273 mPath = path;
274 mDirname = dirname;
275 }
276
277 @Override
278 public void onClick(DialogInterface dialog, int which) {
279 Uploader.this.mUploadPath = mPath + mDirname.getText().toString();
280 Uploader.this.mCreateDir = true;
281 uploadFiles();
282 }
283 }
284
285 @Override
286 public void onBackPressed() {
287
288 if (mParents.size() <= 1) {
289 super.onBackPressed();
290 return;
291 } else {
292 mParents.pop();
293 populateDirectoryList();
294 }
295 }
296
297 @Override
298 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
299 // click on folder in the list
300 Log_OC.d(TAG, "on item click");
301 Vector<OCFile> tmpfiles = getStorageManager().getFolderContent(mFile);
302 if (tmpfiles.size() <= 0) return;
303 // filter on dirtype
304 Vector<OCFile> files = new Vector<OCFile>();
305 for (OCFile f : tmpfiles)
306 if (f.isFolder())
307 files.add(f);
308 if (files.size() < position) {
309 throw new IndexOutOfBoundsException("Incorrect item selected");
310 }
311 mParents.push(files.get(position).getFileName());
312 populateDirectoryList();
313 }
314
315 @Override
316 public void onClick(View v) {
317 // click on button
318 switch (v.getId()) {
319 case R.id.uploader_choose_folder:
320 mUploadPath = ""; // first element in mParents is root dir, represented by "";
321 // init mUploadPath with "/" results in a "//" prefix
322 for (String p : mParents)
323 mUploadPath += p + OCFile.PATH_SEPARATOR;
324 Log_OC.d(TAG, "Uploading file to dir " + mUploadPath);
325
326 uploadFiles();
327
328 break;
329
330 case R.id.uploader_new_folder:
331 CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(mFile);
332 dialog.show(getSupportFragmentManager(), "createdirdialog");
333 break;
334
335
336 default:
337 throw new IllegalArgumentException("Wrong element clicked");
338 }
339 }
340
341 @Override
342 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
343 super.onActivityResult(requestCode, resultCode, data);
344 Log_OC.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
345 if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {
346 dismissDialog(DIALOG_NO_ACCOUNT);
347 if (resultCode == RESULT_CANCELED) {
348 finish();
349 }
350 Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAuthTokenType());
351 if (accounts.length == 0) {
352 showDialog(DIALOG_NO_ACCOUNT);
353 } else {
354 // there is no need for checking for is there more then one
355 // account at this point
356 // since account setup can set only one account at time
357 setAccount(accounts[0]);
358 populateDirectoryList();
359 }
360 }
361 }
362
363 private void populateDirectoryList() {
364 setContentView(R.layout.uploader_layout);
365
366 ListView mListView = (ListView) findViewById(android.R.id.list);
367
368 String current_dir = mParents.peek();
369 if(current_dir.equals("")){
370 getSupportActionBar().setTitle(getString(R.string.default_display_name_for_root_folder));
371 }
372 else{
373 getSupportActionBar().setTitle(current_dir);
374 }
375 boolean notRoot = (mParents.size() > 1);
376 ActionBar actionBar = getSupportActionBar();
377 actionBar.setDisplayHomeAsUpEnabled(notRoot);
378 actionBar.setHomeButtonEnabled(notRoot);
379
380 String full_path = generatePath(mParents);
381
382 Log_OC.d(TAG, "Populating view with content of : " + full_path);
383
384 mFile = getStorageManager().getFileByPath(full_path);
385 if (mFile != null) {
386 Vector<OCFile> files = getStorageManager().getFolderContent(mFile);
387 List<HashMap<String, Object>> data = new LinkedList<HashMap<String,Object>>();
388 for (OCFile f : files) {
389 HashMap<String, Object> h = new HashMap<String, Object>();
390 if (f.isFolder()) {
391 h.put("dirname", f.getFileName());
392 data.add(h);
393 }
394 }
395 SimpleAdapter sa = new SimpleAdapter(this,
396 data,
397 R.layout.uploader_list_item_layout,
398 new String[] {"dirname"},
399 new int[] {R.id.textView1});
400
401 mListView.setAdapter(sa);
402 Button btnChooseFolder = (Button) findViewById(R.id.uploader_choose_folder);
403 btnChooseFolder.setOnClickListener(this);
404
405 Button btnNewFolder = (Button) findViewById(R.id.uploader_new_folder);
406 btnNewFolder.setOnClickListener(this);
407
408 mListView.setOnItemClickListener(this);
409 }
410 }
411
412 private String generatePath(Stack<String> dirs) {
413 String full_path = "";
414
415 for (String a : dirs)
416 full_path += a + "/";
417 return full_path;
418 }
419
420 private void prepareStreamsToUpload() {
421 if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
422 mStreamsToUpload = new ArrayList<Parcelable>();
423 mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
424 } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
425 mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
426 }
427 }
428
429 private boolean somethingToUpload() {
430 return (mStreamsToUpload != null && mStreamsToUpload.get(0) != null);
431 }
432
433 public void uploadFiles() {
434 try {
435
436 ArrayList<String> local = new ArrayList<String>();
437 ArrayList<String> remote = new ArrayList<String>();
438
439 // this checks the mimeType
440 for (Parcelable mStream : mStreamsToUpload) {
441
442 Uri uri = (Uri) mStream;
443 if (uri != null) {
444 if (uri.getScheme().equals("content")) {
445
446 String mimeType = getContentResolver().getType(uri);
447
448 if (mimeType.contains("image")) {
449 String[] CONTENT_PROJECTION = { Images.Media.DATA,
450 Images.Media.DISPLAY_NAME, Images.Media.MIME_TYPE,
451 Images.Media.SIZE };
452 Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null,
453 null, null);
454 c.moveToFirst();
455 int index = c.getColumnIndex(Images.Media.DATA);
456 String data = c.getString(index);
457 String filePath = mUploadPath +
458 c.getString(c.getColumnIndex(Images.Media.DISPLAY_NAME));
459
460 if (data == null) {
461 CopyTmpFileAsyncTask copyTask = new CopyTmpFileAsyncTask(this);
462 Object[] params = { uri, filePath };
463 try {
464 data = copyTask.execute(params).get();
465 } catch (ExecutionException e) {
466 Log_OC.e(TAG, "ExecutionException " + e);
467 } catch (InterruptedException e) {
468 Log_OC.e(TAG, "InterruptedException " + e);
469 }
470 }
471
472 local.add(data);
473 remote.add(mUploadPath +
474 c.getString(c.getColumnIndex(Images.Media.DISPLAY_NAME)));
475
476 }
477 else if (mimeType.contains("video")) {
478 String[] CONTENT_PROJECTION = { Video.Media.DATA,
479 Video.Media.DISPLAY_NAME, Video.Media.MIME_TYPE,
480 Video.Media.SIZE, Video.Media.DATE_MODIFIED };
481 Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null,
482 null, null);
483 c.moveToFirst();
484 int index = c.getColumnIndex(Video.Media.DATA);
485 String data = c.getString(index);
486 local.add(data);
487 remote.add(mUploadPath +
488 c.getString(c.getColumnIndex(Video.Media.DISPLAY_NAME)));
489
490 }
491 else if (mimeType.contains("audio")) {
492 String[] CONTENT_PROJECTION = { Audio.Media.DATA,
493 Audio.Media.DISPLAY_NAME, Audio.Media.MIME_TYPE,
494 Audio.Media.SIZE };
495 Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null,
496 null, null);
497 c.moveToFirst();
498 int index = c.getColumnIndex(Audio.Media.DATA);
499 String data = c.getString(index);
500 local.add(data);
501 remote.add(mUploadPath +
502 c.getString(c.getColumnIndex(Audio.Media.DISPLAY_NAME)));
503
504 }
505 else {
506 String filePath = Uri.decode(uri.toString()).replace(uri.getScheme() +
507 "://", "");
508 // cut everything whats before mnt. It occurred to me that sometimes
509 // apps send their name into the URI
510 if (filePath.contains("mnt")) {
511 String splitedFilePath[] = filePath.split("/mnt");
512 filePath = splitedFilePath[1];
513 }
514 final File file = new File(filePath);
515 local.add(file.getAbsolutePath());
516 remote.add(mUploadPath + file.getName());
517 }
518
519 } else if (uri.getScheme().equals("file")) {
520 String filePath = Uri.decode(uri.toString()).replace(uri.getScheme() +
521 "://", "");
522 if (filePath.contains("mnt")) {
523 String splitedFilePath[] = filePath.split("/mnt");
524 filePath = splitedFilePath[1];
525 }
526 final File file = new File(filePath);
527 local.add(file.getAbsolutePath());
528 remote.add(mUploadPath + file.getName());
529 }
530 else {
531 throw new SecurityException();
532 }
533 }
534 else {
535 throw new SecurityException();
536 }
537
538 Intent intent = new Intent(getApplicationContext(), FileUploader.class);
539 intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
540 intent.putExtra(FileUploader.KEY_LOCAL_FILE, local.toArray(new String[local.size()]));
541 intent.putExtra(FileUploader.KEY_REMOTE_FILE,
542 remote.toArray(new String[remote.size()]));
543 intent.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
544 startService(intent);
545
546 //Save the path to shared preferences
547 SharedPreferences.Editor appPrefs = PreferenceManager
548 .getDefaultSharedPreferences(getApplicationContext()).edit();
549 appPrefs.putString("last_upload_path", mUploadPath);
550 appPrefs.apply();
551
552 finish();
553 }
554
555 } catch (SecurityException e) {
556 String message = String.format(getString(R.string.uploader_error_forbidden_content),
557 getString(R.string.app_name));
558 Toast.makeText(this, message, Toast.LENGTH_LONG).show();
559 }
560 }
561
562 @Override
563 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
564 super.onRemoteOperationFinish(operation, result);
565
566
567 if (operation instanceof CreateFolderOperation) {
568 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
569 }
570
571 }
572
573 /**
574 * Updates the view associated to the activity after the finish of an operation
575 * trying create a new folder
576 *
577 * @param operation Creation operation performed.
578 * @param result Result of the creation.
579 */
580 private void onCreateFolderOperationFinish(CreateFolderOperation operation,
581 RemoteOperationResult result) {
582 if (result.isSuccess()) {
583 dismissLoadingDialog();
584 populateDirectoryList();
585 } else {
586 dismissLoadingDialog();
587 try {
588 Toast msg = Toast.makeText(this,
589 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
590 Toast.LENGTH_LONG);
591 msg.show();
592
593 } catch (NotFoundException e) {
594 Log_OC.e(TAG, "Error while trying to show fail message " , e);
595 }
596 }
597 }
598
599
600 /**
601 * Loads the target folder initialize shown to the user.
602 *
603 * The target account has to be chosen before this method is called.
604 */
605 private void initTargetFolder() {
606 if (getStorageManager() == null) {
607 throw new IllegalStateException("Do not call this method before " +
608 "initializing mStorageManager");
609 }
610
611 SharedPreferences appPreferences = PreferenceManager
612 .getDefaultSharedPreferences(getApplicationContext());
613
614 String last_path = appPreferences.getString("last_upload_path", "");
615 // "/" equals root-directory
616 if(last_path.equals("/")) {
617 mParents.add("");
618 } else{
619 String[] dir_names = last_path.split("/");
620 for (String dir : dir_names)
621 mParents.add(dir);
622 }
623 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
624 while(!getStorageManager().fileExists(generatePath(mParents)) && mParents.size() > 1){
625 mParents.pop();
626 }
627 }
628
629
630 @Override
631 public boolean onOptionsItemSelected(MenuItem item) {
632 boolean retval = true;
633 switch (item.getItemId()) {
634 case android.R.id.home:
635 if((mParents.size() > 1)) {
636 onBackPressed();
637 }
638 break;
639
640 default:
641 retval = super.onOptionsItemSelected(item);
642 }
643 return retval;
644 }
645
646
647 /**
648 * Process the result of CopyTmpFileAsyncTask
649 * @param result
650 */
651 @Override
652 public void OnCopyTmpFileTaskListener(String result) {
653
654 }
655
656 }