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