d36e1cb1c83f0910a6aa0c48ffc86487fd9672fc
[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.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Stack;
30 import java.util.Vector;
31
32 import android.accounts.Account;
33 import android.accounts.AccountManager;
34 import android.app.AlertDialog;
35 import android.app.AlertDialog.Builder;
36 import android.app.Dialog;
37 import android.app.ProgressDialog;
38 import android.content.Context;
39 import android.content.DialogInterface;
40 import android.content.DialogInterface.OnCancelListener;
41 import android.content.DialogInterface.OnClickListener;
42 import android.content.Intent;
43 import android.content.SharedPreferences;
44 import android.content.res.Resources.NotFoundException;
45 import android.database.Cursor;
46 import android.net.Uri;
47 import android.os.Bundle;
48 import android.os.Parcelable;
49 import android.preference.PreferenceManager;
50 import android.provider.MediaStore.Audio;
51 import android.provider.MediaStore.Images;
52 import android.provider.MediaStore.Video;
53 import android.view.View;
54 import android.widget.AdapterView;
55 import android.widget.AdapterView.OnItemClickListener;
56 import android.widget.Button;
57 import android.widget.EditText;
58 import android.widget.ListView;
59 import android.widget.SimpleAdapter;
60 import android.widget.Toast;
61
62 import com.actionbarsherlock.app.ActionBar;
63 import com.actionbarsherlock.view.MenuItem;
64 import com.owncloud.android.MainApp;
65 import com.owncloud.android.R;
66 import com.owncloud.android.authentication.AccountAuthenticator;
67 import com.owncloud.android.authentication.PinCheck;
68 import com.owncloud.android.datamodel.FileDataStorageManager;
69 import com.owncloud.android.datamodel.OCFile;
70 import com.owncloud.android.files.services.FileUploader;
71 import com.owncloud.android.lib.common.operations.RemoteOperation;
72 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
73 import com.owncloud.android.lib.common.utils.Log_OC;
74 import com.owncloud.android.operations.CreateFolderOperation;
75 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
76 import com.owncloud.android.utils.DisplayUtils;
77 import com.owncloud.android.utils.ErrorMessageAdapter;
78
79
80 /**
81 * This can be used to upload things to an ownCloud instance.
82 */
83 public class Uploader extends FileActivity
84 implements OnItemClickListener, android.view.View.OnClickListener {
85
86 private static final String TAG = Uploader.class.getSimpleName();
87
88 private AccountManager mAccountManager;
89 private Stack<String> mParents;
90 private ArrayList<Parcelable> mStreamsToUpload;
91 private boolean mCreateDir;
92 private String mUploadPath;
93 private OCFile mFile;
94 private boolean mAccountSelected;
95
96 private final static int DIALOG_NO_ACCOUNT = 0;
97 private final static int DIALOG_WAITING = 1;
98 private final static int DIALOG_NO_STREAM = 2;
99 private final static int DIALOG_MULTIPLE_ACCOUNT = 3;
100
101 private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;
102
103 private final static String KEY_PARENTS = "PARENTS";
104 private final static String KEY_FILE = "FILE";
105 private final static String KEY_ACCOUNT_SELECTED = "ACCOUNT_SELECTED";
106
107 @Override
108 protected void onCreate(Bundle savedInstanceState) {
109 prepareStreamsToUpload();
110
111 if (savedInstanceState == null) {
112 mParents = new Stack<String>();
113 mAccountSelected = false;
114 } else {
115 mParents = (Stack<String>) savedInstanceState.getSerializable(KEY_PARENTS);
116 mFile = savedInstanceState.getParcelable(KEY_FILE);
117 mAccountSelected = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTED);
118 }
119 super.onCreate(savedInstanceState);
120
121 // Check Pin entry
122 if (PinCheck.checkIfPinEntry()){
123 Intent i = new Intent(MainApp.getAppContext(), PinCodeActivity.class);
124 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "ownCloudUploader");
125 startActivity(i);
126 }
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 local.add(data);
455 remote.add(mUploadPath +
456 c.getString(c.getColumnIndex(Images.Media.DISPLAY_NAME)));
457
458 }
459 else if (mimeType.contains("video")) {
460 String[] CONTENT_PROJECTION = { Video.Media.DATA,
461 Video.Media.DISPLAY_NAME, Video.Media.MIME_TYPE,
462 Video.Media.SIZE, Video.Media.DATE_MODIFIED };
463 Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null,
464 null, null);
465 c.moveToFirst();
466 int index = c.getColumnIndex(Video.Media.DATA);
467 String data = c.getString(index);
468 local.add(data);
469 remote.add(mUploadPath +
470 c.getString(c.getColumnIndex(Video.Media.DISPLAY_NAME)));
471
472 }
473 else if (mimeType.contains("audio")) {
474 String[] CONTENT_PROJECTION = { Audio.Media.DATA,
475 Audio.Media.DISPLAY_NAME, Audio.Media.MIME_TYPE,
476 Audio.Media.SIZE };
477 Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null,
478 null, null);
479 c.moveToFirst();
480 int index = c.getColumnIndex(Audio.Media.DATA);
481 String data = c.getString(index);
482 local.add(data);
483 remote.add(mUploadPath +
484 c.getString(c.getColumnIndex(Audio.Media.DISPLAY_NAME)));
485
486 }
487 else {
488 String filePath = Uri.decode(uri.toString()).replace(uri.getScheme() +
489 "://", "");
490 // cut everything whats before mnt. It occurred to me that sometimes
491 // apps send their name into the URI
492 if (filePath.contains("mnt")) {
493 String splitedFilePath[] = filePath.split("/mnt");
494 filePath = splitedFilePath[1];
495 }
496 final File file = new File(filePath);
497 local.add(file.getAbsolutePath());
498 remote.add(mUploadPath + file.getName());
499 }
500
501 } else if (uri.getScheme().equals("file")) {
502 String filePath = Uri.decode(uri.toString()).replace(uri.getScheme() +
503 "://", "");
504 if (filePath.contains("mnt")) {
505 String splitedFilePath[] = filePath.split("/mnt");
506 filePath = splitedFilePath[1];
507 }
508 final File file = new File(filePath);
509 local.add(file.getAbsolutePath());
510 remote.add(mUploadPath + file.getName());
511 }
512 else {
513 throw new SecurityException();
514 }
515 }
516 else {
517 throw new SecurityException();
518 }
519
520 Intent intent = new Intent(getApplicationContext(), FileUploader.class);
521 intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
522 intent.putExtra(FileUploader.KEY_LOCAL_FILE, local.toArray(new String[local.size()]));
523 intent.putExtra(FileUploader.KEY_REMOTE_FILE,
524 remote.toArray(new String[remote.size()]));
525 intent.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
526 startService(intent);
527
528 //Save the path to shared preferences
529 SharedPreferences.Editor appPrefs = PreferenceManager
530 .getDefaultSharedPreferences(getApplicationContext()).edit();
531 appPrefs.putString("last_upload_path", mUploadPath);
532 appPrefs.apply();
533
534 finish();
535 }
536
537 } catch (SecurityException e) {
538 String message = String.format(getString(R.string.uploader_error_forbidden_content),
539 getString(R.string.app_name));
540 Toast.makeText(this, message, Toast.LENGTH_LONG).show();
541 }
542 }
543
544 @Override
545 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
546 super.onRemoteOperationFinish(operation, result);
547
548
549 if (operation instanceof CreateFolderOperation) {
550 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
551 }
552
553 }
554
555 /**
556 * Updates the view associated to the activity after the finish of an operation
557 * trying create a new folder
558 *
559 * @param operation Creation operation performed.
560 * @param result Result of the creation.
561 */
562 private void onCreateFolderOperationFinish(CreateFolderOperation operation,
563 RemoteOperationResult result) {
564 if (result.isSuccess()) {
565 dismissLoadingDialog();
566 populateDirectoryList();
567 } else {
568 dismissLoadingDialog();
569 try {
570 Toast msg = Toast.makeText(this,
571 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
572 Toast.LENGTH_LONG);
573 msg.show();
574
575 } catch (NotFoundException e) {
576 Log_OC.e(TAG, "Error while trying to show fail message " , e);
577 }
578 }
579 }
580
581
582 /**
583 * Loads the target folder initialize shown to the user.
584 *
585 * The target account has to be chosen before this method is called.
586 */
587 private void initTargetFolder() {
588 if (getStorageManager() == null) {
589 throw new IllegalStateException("Do not call this method before " +
590 "initializing mStorageManager");
591 }
592
593 SharedPreferences appPreferences = PreferenceManager
594 .getDefaultSharedPreferences(getApplicationContext());
595
596 String last_path = appPreferences.getString("last_upload_path", "");
597 // "/" equals root-directory
598 if(last_path.equals("/")) {
599 mParents.add("");
600 }
601 else{
602 String[] dir_names = last_path.split("/");
603 for (String dir : dir_names)
604 mParents.add(dir);
605 }
606 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
607 while(!getStorageManager().fileExists(generatePath(mParents)) && mParents.size() > 1){
608 mParents.pop();
609 }
610 }
611
612
613 @Override
614 public boolean onOptionsItemSelected(MenuItem item) {
615 boolean retval = true;
616 switch (item.getItemId()) {
617 case android.R.id.home: {
618 if((mParents.size() > 1)) {
619 onBackPressed();
620 }
621 break;
622 }
623 default:
624 retval = super.onOptionsItemSelected(item);
625 }
626 return retval;
627 }
628
629
630 }