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