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