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