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