Merge branch 'master' of https://github.com/owncloud/android into develop
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileActivity.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author David A. Velasco
5 * Copyright (C) 2011 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 android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.accounts.AccountManagerCallback;
27 import android.accounts.AccountManagerFuture;
28 import android.accounts.AuthenticatorException;
29 import android.accounts.OperationCanceledException;
30 import android.content.ComponentName;
31 import android.content.Context;
32 import android.content.Intent;
33 import android.content.ServiceConnection;
34 import android.content.res.Configuration;
35 import android.os.Bundle;
36 import android.os.Handler;
37 import android.os.IBinder;
38 import android.support.v4.app.ActionBarDrawerToggle;
39 import android.support.v4.app.Fragment;
40 import android.support.v4.app.FragmentManager;
41 import android.support.v4.app.FragmentTransaction;
42 import android.support.v4.view.GravityCompat;
43 import android.support.v4.widget.DrawerLayout;
44 import android.support.v7.app.ActionBar;
45 import android.support.v7.app.ActionBarActivity;
46 import android.view.View;
47 import android.widget.AdapterView;
48 import android.widget.LinearLayout;
49 import android.widget.ListView;
50 import android.widget.Toast;
51
52 import com.owncloud.android.BuildConfig;
53 import com.owncloud.android.MainApp;
54 import com.owncloud.android.R;
55 import com.owncloud.android.authentication.AccountUtils;
56 import com.owncloud.android.authentication.AuthenticatorActivity;
57 import com.owncloud.android.datamodel.FileDataStorageManager;
58 import com.owncloud.android.datamodel.OCFile;
59 import com.owncloud.android.files.FileOperationsHelper;
60 import com.owncloud.android.files.services.FileDownloader;
61 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
62 import com.owncloud.android.files.services.FileUploader;
63 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
64 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
65 import com.owncloud.android.lib.common.operations.RemoteOperation;
66 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
67 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
68 import com.owncloud.android.lib.common.utils.Log_OC;
69 import com.owncloud.android.operations.CreateShareOperation;
70 import com.owncloud.android.operations.SynchronizeFileOperation;
71 import com.owncloud.android.operations.SynchronizeFolderOperation;
72 import com.owncloud.android.operations.UnshareLinkOperation;
73 import com.owncloud.android.services.OperationsService;
74 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
75 import com.owncloud.android.ui.NavigationDrawerItem;
76 import com.owncloud.android.ui.adapter.NavigationDrawerListAdapter;
77 import com.owncloud.android.ui.dialog.LoadingDialog;
78 import com.owncloud.android.ui.dialog.SharePasswordDialogFragment;
79 import com.owncloud.android.ui.fragment.FileDetailFragment;
80 import com.owncloud.android.ui.fragment.FileFragment;
81 import com.owncloud.android.utils.ErrorMessageAdapter;
82
83 import java.util.ArrayList;
84
85
86 /**
87 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud
88 * {@link Account}s .
89 */
90 public class FileActivity extends ActionBarActivity
91 implements OnRemoteOperationListener, ComponentsGetter {
92
93 public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
94 public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
95 public static final String EXTRA_WAITING_TO_PREVIEW =
96 "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
97 public static final String EXTRA_FROM_NOTIFICATION =
98 "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
99
100 public static final String TAG = FileActivity.class.getSimpleName();
101
102 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
103 private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
104 private static final String DIALOG_SHARE_PASSWORD = "DIALOG_SHARE_PASSWORD";
105 private static final String KEY_TRY_SHARE_AGAIN = "TRY_SHARE_AGAIN";
106 private static final String KEY_ACTION_BAR_TITLE = "ACTION_BAR_TITLE";
107
108 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS = 200;
109
110
111 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.*/
112 private Account mAccount;
113
114 /** Main {@link OCFile} handled by the activity.*/
115 private OCFile mFile;
116
117 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud
118 * {@link Account} */
119 private boolean mRedirectingToSetupAccount = false;
120
121 /** Flag to signal when the value of mAccount was set */
122 protected boolean mAccountWasSet;
123
124 /** Flag to signal when the value of mAccount was restored from a saved state */
125 protected boolean mAccountWasRestored;
126
127 /** Flag to signal if the activity is launched by a notification */
128 private boolean mFromNotification;
129
130 /** Messages handler associated to the main thread and the life cycle of the activity */
131 private Handler mHandler;
132
133 /** Access point to the cached database for the current ownCloud {@link Account} */
134 private FileDataStorageManager mStorageManager = null;
135
136 private FileOperationsHelper mFileOperationsHelper;
137
138 private ServiceConnection mOperationsServiceConnection = null;
139
140 private OperationsServiceBinder mOperationsServiceBinder = null;
141
142 protected FileDownloaderBinder mDownloaderBinder = null;
143 protected FileUploaderBinder mUploaderBinder = null;
144 private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
145
146 private boolean mTryShareAgain = false;
147
148 // Navigation Drawer
149 protected DrawerLayout mDrawerLayout;
150 protected ActionBarDrawerToggle mDrawerToggle;
151 protected ListView mDrawerList;
152
153 // Slide menu items
154 protected String[] mDrawerTitles;
155 protected String[] mDrawerContentDescriptions;
156
157 protected ArrayList<NavigationDrawerItem> mDrawerItems;
158
159 protected NavigationDrawerListAdapter mNavigationDrawerAdapter = null;
160
161
162 // TODO re-enable when "Accounts" is available in Navigation Drawer
163 // protected boolean mShowAccounts = false;
164
165 /**
166 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
167 * the {@link FileActivity}.
168 *
169 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
170 * is requested to create a new one.
171 */
172 @Override
173 protected void onCreate(Bundle savedInstanceState) {
174 super.onCreate(savedInstanceState);
175 mHandler = new Handler();
176 mFileOperationsHelper = new FileOperationsHelper(this);
177 Account account = null;
178 if(savedInstanceState != null) {
179 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
180 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
181 mFileOperationsHelper.setOpIdWaitingFor(
182 savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
183 );
184 mTryShareAgain = savedInstanceState.getBoolean(KEY_TRY_SHARE_AGAIN);
185 getSupportActionBar().setTitle(savedInstanceState.getString(KEY_ACTION_BAR_TITLE));
186 } else {
187 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
188 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
189 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION,
190 false);
191 }
192
193 AccountUtils.updateAccountVersion(this); // best place, before any access to AccountManager
194 // or database
195
196 setAccount(account, savedInstanceState != null);
197
198 mOperationsServiceConnection = new OperationsServiceConnection();
199 bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection,
200 Context.BIND_AUTO_CREATE);
201
202 mDownloadServiceConnection = newTransferenceServiceConnection();
203 if (mDownloadServiceConnection != null) {
204 bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection,
205 Context.BIND_AUTO_CREATE);
206 }
207 mUploadServiceConnection = newTransferenceServiceConnection();
208 if (mUploadServiceConnection != null) {
209 bindService(new Intent(this, FileUploader.class), mUploadServiceConnection,
210 Context.BIND_AUTO_CREATE);
211 }
212
213 }
214
215 @Override
216 protected void onNewIntent (Intent intent) {
217 Log_OC.v(TAG, "onNewIntent() start");
218 Account current = AccountUtils.getCurrentOwnCloudAccount(this);
219 if (current != null && mAccount != null && !mAccount.name.equals(current.name)) {
220 mAccount = current;
221 }
222 Log_OC.v(TAG, "onNewIntent() stop");
223 }
224
225 /**
226 * Since ownCloud {@link Account}s can be managed from the system setting menu,
227 * the existence of the {@link Account} associated to the instance must be checked
228 * every time it is restarted.
229 */
230 @Override
231 protected void onRestart() {
232 Log_OC.v(TAG, "onRestart() start");
233 super.onRestart();
234 boolean validAccount = (mAccount != null && AccountUtils.exists(mAccount, this));
235 if (!validAccount) {
236 swapToDefaultAccount();
237 }
238 Log_OC.v(TAG, "onRestart() end");
239 }
240
241
242 @Override
243 protected void onStart() {
244 super.onStart();
245
246 if (mAccountWasSet) {
247 onAccountSet(mAccountWasRestored);
248 }
249 }
250
251 @Override
252 protected void onResume() {
253 super.onResume();
254
255 if (mOperationsServiceBinder != null) {
256 doOnResumeAndBound();
257 }
258 }
259
260 @Override
261 protected void onPause() {
262 if (mOperationsServiceBinder != null) {
263 mOperationsServiceBinder.removeOperationListener(this);
264 }
265
266 super.onPause();
267 }
268
269
270 @Override
271 protected void onDestroy() {
272 if (mOperationsServiceConnection != null) {
273 unbindService(mOperationsServiceConnection);
274 mOperationsServiceBinder = null;
275 }
276 if (mDownloadServiceConnection != null) {
277 unbindService(mDownloadServiceConnection);
278 mDownloadServiceConnection = null;
279 }
280 if (mUploadServiceConnection != null) {
281 unbindService(mUploadServiceConnection);
282 mUploadServiceConnection = null;
283 }
284
285 super.onDestroy();
286 }
287
288 @Override
289 protected void onPostCreate(Bundle savedInstanceState) {
290 super.onPostCreate(savedInstanceState);
291 // Sync the toggle state after onRestoreInstanceState has occurred.
292 if (mDrawerToggle != null) {
293 mDrawerToggle.syncState();
294 if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
295 getSupportActionBar().setTitle(R.string.app_name);
296 mDrawerToggle.setDrawerIndicatorEnabled(true);
297 }
298 }
299 }
300
301 @Override
302 public void onConfigurationChanged(Configuration newConfig) {
303 super.onConfigurationChanged(newConfig);
304 if (mDrawerToggle != null) {
305 mDrawerToggle.onConfigurationChanged(newConfig);
306 }
307 }
308
309 protected void initDrawer(){
310 // constant settings for action bar when navigation drawer is inited
311 getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
312
313
314 mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
315 // Notification Drawer
316 LinearLayout navigationDrawerLayout = (LinearLayout) findViewById(R.id.left_drawer);
317 mDrawerList = (ListView) navigationDrawerLayout.findViewById(R.id.drawer_list);
318
319 // TODO re-enable when "Accounts" is available in Navigation Drawer
320 // // load Account in the Drawer Title
321 // // User-Icon
322 // ImageView userIcon = (ImageView) navigationDrawerLayout.findViewById(R.id.drawer_userIcon);
323 // userIcon.setImageResource(DisplayUtils.getSeasonalIconId());
324 //
325 // // Username
326 // TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username);
327 // Account account = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
328 //
329 // if (account != null) {
330 // int lastAtPos = account.name.lastIndexOf("@");
331 // username.setText(account.name.substring(0, lastAtPos));
332 // }
333
334 // load slide menu items
335 mDrawerTitles = getResources().getStringArray(R.array.drawer_items);
336
337 // nav drawer content description from resources
338 mDrawerContentDescriptions = getResources().
339 getStringArray(R.array.drawer_content_descriptions);
340
341 // nav drawer items
342 mDrawerItems = new ArrayList<NavigationDrawerItem>();
343 // adding nav drawer items to array
344 // TODO re-enable when "Accounts" is available in Navigation Drawer
345 // Accounts
346 // mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[0],
347 // mDrawerContentDescriptions[0]));
348 // All Files
349 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[0], mDrawerContentDescriptions[0]));
350
351 // TODO Enable when "On Device" is recovered
352 // On Device
353 //mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[2],
354 // mDrawerContentDescriptions[2]));
355
356 // Settings
357 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[1], mDrawerContentDescriptions[1]));
358 // Logs
359 if (BuildConfig.DEBUG) {
360 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[2],
361 mDrawerContentDescriptions[2]));
362 }
363
364 // setting the nav drawer list adapter
365 mNavigationDrawerAdapter = new NavigationDrawerListAdapter(getApplicationContext(), this,
366 mDrawerItems);
367 mDrawerList.setAdapter(mNavigationDrawerAdapter);
368
369 mDrawerToggle = new ActionBarDrawerToggle(
370 this,
371 mDrawerLayout,
372 R.drawable.ic_drawer,
373 R.string.app_name,
374 R.string.drawer_close) {
375
376 /** Called when a drawer has settled in a completely closed state. */
377 public void onDrawerClosed(View view) {
378 super.onDrawerClosed(view);
379 updateActionBarTitleAndHomeButton(null);
380 invalidateOptionsMenu();
381 }
382
383 /** Called when a drawer has settled in a completely open state. */
384 public void onDrawerOpened(View drawerView) {
385 super.onDrawerOpened(drawerView);
386 getSupportActionBar().setTitle(R.string.app_name);
387 mDrawerToggle.setDrawerIndicatorEnabled(true);
388 invalidateOptionsMenu();
389 }
390 };
391
392 //mDrawerToggle.setDrawerIndicatorEnabled(true);
393 // Set the list's click listener
394 mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
395
396 // Set the drawer toggle as the DrawerListener
397 mDrawerLayout.setDrawerListener(mDrawerToggle);
398 }
399
400 /**
401 * Updates title bar and home buttons (state and icon).
402 *
403 * Assumes that navigation drawer is NOT visible.
404 */
405 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
406 String title = getString(R.string.default_display_name_for_root_folder); // default
407 boolean inRoot;
408
409 /// choose the appropiate title
410 if (chosenFile == null) {
411 chosenFile = mFile; // if no file is passed, current file decides
412 }
413 inRoot = (
414 chosenFile == null ||
415 (chosenFile.isFolder() && chosenFile.getParentId() == FileDataStorageManager.ROOT_PARENT_ID)
416 );
417 if (!inRoot) {
418 title = chosenFile.getFileName();
419 }
420
421 /// set the chosen title
422 ActionBar actionBar = getSupportActionBar();
423 actionBar.setTitle(title);
424 /// also as content description
425 View actionBarTitleView = getWindow().getDecorView().findViewById(
426 getResources().getIdentifier("action_bar_title", "id", "android")
427 );
428 if (actionBarTitleView != null) { // it's null in Android 2.x
429 actionBarTitleView.setContentDescription(title);
430 }
431
432 /// set home button properties
433 mDrawerToggle.setDrawerIndicatorEnabled(inRoot);
434 actionBar.setDisplayHomeAsUpEnabled(true);
435 actionBar.setDisplayShowTitleEnabled(true);
436
437 }
438
439
440 /**
441 * Sets and validates the ownCloud {@link Account} associated to the Activity.
442 *
443 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
444 *
445 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
446 *
447 * @param account New {@link Account} to set.
448 * @param savedAccount When 'true', account was retrieved from a saved instance state.
449 */
450 protected void setAccount(Account account, boolean savedAccount) {
451 Account oldAccount = mAccount;
452 boolean validAccount =
453 (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(),
454 account.name));
455 if (validAccount) {
456 mAccount = account;
457 mAccountWasSet = true;
458 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
459
460 } else {
461 swapToDefaultAccount();
462 }
463 }
464
465
466 /**
467 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
468 *
469 * If no valid ownCloud {@link Account} exists, the the user is requested
470 * to create a new ownCloud {@link Account}.
471 *
472 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
473 */
474 private void swapToDefaultAccount() {
475 // default to the most recently used account
476 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
477 if (newAccount == null) {
478 /// no account available: force account creation
479 createFirstAccount();
480 mRedirectingToSetupAccount = true;
481 mAccountWasSet = false;
482 mAccountWasRestored = false;
483
484 } else {
485 mAccountWasSet = true;
486 mAccountWasRestored = (newAccount.equals(mAccount));
487 mAccount = newAccount;
488 }
489 }
490
491
492 /**
493 * Launches the account creation activity. To use when no ownCloud account is available
494 */
495 private void createFirstAccount() {
496 AccountManager am = AccountManager.get(getApplicationContext());
497 am.addAccount(MainApp.getAccountType(),
498 null,
499 null,
500 null,
501 this,
502 new AccountCreationCallback(),
503 null);
504 }
505
506
507 /**
508 * {@inheritDoc}
509 */
510 @Override
511 protected void onSaveInstanceState(Bundle outState) {
512 super.onSaveInstanceState(outState);
513 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
514 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
515 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
516 outState.putBoolean(KEY_TRY_SHARE_AGAIN, mTryShareAgain);
517 outState.putString(KEY_ACTION_BAR_TITLE, getSupportActionBar().getTitle().toString());
518 }
519
520
521 /**
522 * Getter for the main {@link OCFile} handled by the activity.
523 *
524 * @return Main {@link OCFile} handled by the activity.
525 */
526 public OCFile getFile() {
527 return mFile;
528 }
529
530
531 /**
532 * Setter for the main {@link OCFile} handled by the activity.
533 *
534 * @param file Main {@link OCFile} to be handled by the activity.
535 */
536 public void setFile(OCFile file) {
537 mFile = file;
538 }
539
540
541 /**
542 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity
543 * is located.
544 *
545 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity
546 * is located.
547 */
548 public Account getAccount() {
549 return mAccount;
550 }
551
552 protected void setAccount(Account account) {
553 mAccount = account;
554 }
555
556 /**
557 * @return Value of mFromNotification: True if the Activity is launched by a notification
558 */
559 public boolean fromNotification() {
560 return mFromNotification;
561 }
562
563 /**
564 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
565 */
566 protected boolean isRedirectingToSetupAccount() {
567 return mRedirectingToSetupAccount;
568 }
569
570 public boolean isTryShareAgain(){
571 return mTryShareAgain;
572 }
573
574 public void setTryShareAgain(boolean tryShareAgain) {
575 mTryShareAgain = tryShareAgain;
576 }
577
578 public OperationsServiceBinder getOperationsServiceBinder() {
579 return mOperationsServiceBinder;
580 }
581
582 protected ServiceConnection newTransferenceServiceConnection() {
583 return null;
584 }
585
586 /**
587 * Helper class handling a callback from the {@link AccountManager} after the creation of
588 * a new ownCloud {@link Account} finished, successfully or not.
589 *
590 * At this moment, only called after the creation of the first account.
591 */
592 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
593
594 @Override
595 public void run(AccountManagerFuture<Bundle> future) {
596 FileActivity.this.mRedirectingToSetupAccount = false;
597 boolean accountWasSet = false;
598 if (future != null) {
599 try {
600 Bundle result;
601 result = future.getResult();
602 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
603 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
604 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
605 setAccount(new Account(name, type), false);
606 accountWasSet = true;
607 }
608 } catch (OperationCanceledException e) {
609 Log_OC.d(TAG, "Account creation canceled");
610
611 } catch (Exception e) {
612 Log_OC.e(TAG, "Account creation finished in exception: ", e);
613 }
614
615 } else {
616 Log_OC.e(TAG, "Account creation callback with null bundle");
617 }
618 if (!accountWasSet) {
619 moveTaskToBack(true);
620 }
621 }
622
623 }
624
625
626 /**
627 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
628 *
629 * Child classes must grant that state depending on the {@link Account} is updated.
630 */
631 protected void onAccountSet(boolean stateWasRecovered) {
632 if (getAccount() != null) {
633 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
634
635 } else {
636 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
637 }
638 }
639
640
641 public FileDataStorageManager getStorageManager() {
642 return mStorageManager;
643 }
644
645
646 public OnRemoteOperationListener getRemoteOperationListener() {
647 return this;
648 }
649
650
651 public Handler getHandler() {
652 return mHandler;
653 }
654
655 public FileOperationsHelper getFileOperationsHelper() {
656 return mFileOperationsHelper;
657 }
658
659 /**
660 *
661 * @param operation Removal operation performed.
662 * @param result Result of the removal.
663 */
664 @Override
665 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
666 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the "
667 + "FileActivities ");
668
669 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
670
671 if (!result.isSuccess() && (
672 result.getCode() == ResultCode.UNAUTHORIZED ||
673 result.isIdPRedirection() ||
674 (result.isException() && result.getException() instanceof AuthenticatorException)
675 )) {
676
677 requestCredentialsUpdate();
678
679 if (result.getCode() == ResultCode.UNAUTHORIZED) {
680 dismissLoadingDialog();
681 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
682 operation, getResources()),
683 Toast.LENGTH_LONG);
684 t.show();
685 }
686 mTryShareAgain = false;
687
688 } else if (operation instanceof CreateShareOperation) {
689 onCreateShareOperationFinish((CreateShareOperation) operation, result);
690
691 } else if (operation instanceof UnshareLinkOperation) {
692 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
693
694 } else if (operation instanceof SynchronizeFolderOperation) {
695 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
696
697 }else if (operation instanceof SynchronizeFileOperation) {
698 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
699
700 }
701 }
702
703 protected void requestCredentialsUpdate() {
704 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
705 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
706 updateAccountCredentials.putExtra(
707 AuthenticatorActivity.EXTRA_ACTION,
708 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
709 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
710 startActivity(updateAccountCredentials);
711 }
712
713
714 private void onCreateShareOperationFinish(CreateShareOperation operation,
715 RemoteOperationResult result) {
716 dismissLoadingDialog();
717 if (result.isSuccess()) {
718 mTryShareAgain = false;
719 updateFileFromDB();
720
721 Intent sendIntent = operation.getSendIntent();
722 startActivity(sendIntent);
723 } else {
724 // Detect Failure (403) --> needs Password
725 if (result.getCode() == ResultCode.SHARE_FORBIDDEN) {
726 if (!isTryShareAgain()) {
727 SharePasswordDialogFragment dialog =
728 SharePasswordDialogFragment.newInstance(new OCFile(operation.getPath()),
729 operation.getSendIntent());
730 dialog.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD);
731 } else {
732 Toast t = Toast.makeText(this,
733 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
734 Toast.LENGTH_LONG);
735 t.show();
736 mTryShareAgain = false;
737 }
738 } else {
739 Toast t = Toast.makeText(this,
740 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
741 Toast.LENGTH_LONG);
742 t.show();
743 }
744 }
745 }
746
747
748 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation,
749 RemoteOperationResult result) {
750 dismissLoadingDialog();
751
752 if (result.isSuccess()){
753 updateFileFromDB();
754
755 } else {
756 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
757 operation, getResources()), Toast.LENGTH_LONG);
758 t.show();
759 }
760 }
761
762 private void onSynchronizeFolderOperationFinish(
763 SynchronizeFolderOperation operation, RemoteOperationResult result
764 ) {
765 if (!result.isSuccess() && result.getCode() != ResultCode.CANCELLED){
766 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
767 operation, getResources()), Toast.LENGTH_LONG);
768 t.show();
769 }
770 }
771
772 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
773 RemoteOperationResult result) {
774 dismissLoadingDialog();
775 OCFile syncedFile = operation.getLocalFile();
776 if (!result.isSuccess()) {
777 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
778 Intent i = new Intent(this, ConflictsResolveActivity.class);
779 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
780 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
781 startActivity(i);
782
783 }
784 } else {
785 if (!operation.transferWasRequested()) {
786 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
787 operation, getResources()), Toast.LENGTH_LONG);
788 msg.show();
789 }
790 }
791 }
792
793 protected void updateFileFromDB(){
794 OCFile file = getFile();
795 if (file != null) {
796 file = getStorageManager().getFileByPath(file.getRemotePath());
797 setFile(file);
798 }
799 }
800
801
802 /**
803 * Show loading dialog
804 */
805 public void showLoadingDialog() {
806 // Construct dialog
807 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
808 FragmentManager fm = getSupportFragmentManager();
809 FragmentTransaction ft = fm.beginTransaction();
810 loading.show(ft, DIALOG_WAIT_TAG);
811
812 }
813
814
815 /**
816 * Dismiss loading dialog
817 */
818 public void dismissLoadingDialog(){
819 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
820 if (frag != null) {
821 LoadingDialog loading = (LoadingDialog) frag;
822 loading.dismiss();
823 }
824 }
825
826
827 private void doOnResumeAndBound() {
828 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
829 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
830 if (waitingForOpId <= Integer.MAX_VALUE) {
831 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId,
832 this);
833 if (!wait ) {
834 dismissLoadingDialog();
835 }
836 }
837 }
838
839
840 /**
841 * Implements callback methods for service binding. Passed as a parameter to {
842 */
843 private class OperationsServiceConnection implements ServiceConnection {
844
845 @Override
846 public void onServiceConnected(ComponentName component, IBinder service) {
847 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
848 Log_OC.d(TAG, "Operations service connected");
849 mOperationsServiceBinder = (OperationsServiceBinder) service;
850 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
851 dismissLoadingDialog();
852 }*/
853 doOnResumeAndBound();
854
855 } else {
856 return;
857 }
858 }
859
860
861 @Override
862 public void onServiceDisconnected(ComponentName component) {
863 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
864 Log_OC.d(TAG, "Operations service disconnected");
865 mOperationsServiceBinder = null;
866 // TODO whatever could be waiting for the service is unbound
867 }
868 }
869 }
870
871
872 @Override
873 public FileDownloaderBinder getFileDownloaderBinder() {
874 return mDownloaderBinder;
875 }
876
877
878 @Override
879 public FileUploaderBinder getFileUploaderBinder() {
880 return mUploaderBinder;
881 }
882
883
884 public void restart(){
885 Intent i = new Intent(this, FileDisplayActivity.class);
886 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
887 startActivity(i);
888 }
889
890 // TODO re-enable when "Accounts" is available in Navigation Drawer
891 // public void closeDrawer() {
892 // mDrawerLayout.closeDrawers();
893 // }
894
895 public void allFilesOption(){
896 restart();
897 }
898
899 private class DrawerItemClickListener implements ListView.OnItemClickListener {
900 @Override
901 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
902 // TODO re-enable when "Accounts" is available in Navigation Drawer
903 // if (mShowAccounts && position > 0){
904 // position = position - 1;
905 // }
906 switch (position){
907 // TODO re-enable when "Accounts" is available in Navigation Drawer
908 // case 0: // Accounts
909 // mShowAccounts = !mShowAccounts;
910 // mNavigationDrawerAdapter.setShowAccounts(mShowAccounts);
911 // mNavigationDrawerAdapter.notifyDataSetChanged();
912 // break;
913
914 case 0: // All Files
915 allFilesOption();
916 mDrawerLayout.closeDrawers();
917 break;
918
919 // TODO Enable when "On Device" is recovered ?
920 // case 2:
921 // MainApp.showOnlyFilesOnDevice(true);
922 // mDrawerLayout.closeDrawers();
923 // break;
924
925 case 1: // Settings
926 Intent settingsIntent = new Intent(getApplicationContext(),
927 Preferences.class);
928 startActivity(settingsIntent);
929 mDrawerLayout.closeDrawers();
930 break;
931
932 case 2: // Logs
933 Intent loggerIntent = new Intent(getApplicationContext(),
934 LogHistoryActivity.class);
935 startActivity(loggerIntent);
936 mDrawerLayout.closeDrawers();
937 break;
938 }
939 }
940 }
941 }