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