marshmallow changes redone
[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 // TODO Enable when "On Device" is recovered
395 // On Device
396 //mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[2],
397 // mDrawerContentDescriptions[2]));
398
399 // Settings
400 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[1], mDrawerContentDescriptions[1],
401 R.drawable.ic_settings));
402 // Logs
403 if (BuildConfig.DEBUG) {
404 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[2],
405 mDrawerContentDescriptions[2],R.drawable.ic_log));
406 }
407
408 // setting the nav drawer list adapter
409 mNavigationDrawerAdapter = new NavigationDrawerListAdapter(getApplicationContext(), this,
410 mDrawerItems);
411 mDrawerList.setAdapter(mNavigationDrawerAdapter);
412
413
414 mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.drawer_open,R.string.drawer_close) {
415
416 /** Called when a drawer has settled in a completely closed state. */
417 public void onDrawerClosed(View view) {
418 super.onDrawerClosed(view);
419 updateActionBarTitleAndHomeButton(null);
420 invalidateOptionsMenu();
421 }
422
423 /** Called when a drawer has settled in a completely open state. */
424 public void onDrawerOpened(View drawerView) {
425 super.onDrawerOpened(drawerView);
426 getSupportActionBar().setTitle(R.string.app_name);
427 mDrawerToggle.setDrawerIndicatorEnabled(true);
428 invalidateOptionsMenu();
429 }
430 };
431
432 // Set the list's click listener
433 mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
434
435 // Set the drawer toggle as the DrawerListener
436 mDrawerLayout.setDrawerListener(mDrawerToggle);
437 mDrawerToggle.setDrawerIndicatorEnabled(false);
438 }
439
440 /**
441 * sets the given account name in the drawer in case the drawer is available. The account name
442 * is shortened beginning from the @-sign in the username.
443 *
444 * @param navigationDrawerLayout the drawer layout to be used
445 * @param account the account to be set in the drawer
446 */
447 protected void setUsernameInDrawer(RelativeLayout navigationDrawerLayout, Account account) {
448 if (navigationDrawerLayout != null && getAccount() != null) {
449 TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username);
450 int lastAtPos = account.name.lastIndexOf("@");
451 username.setText(account.name.substring(0, lastAtPos));
452 }
453 }
454
455 /**
456 * Updates title bar and home buttons (state and icon).
457 *
458 * Assumes that navigation drawer is NOT visible.
459 */
460 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
461 String title = getString(R.string.default_display_name_for_root_folder); // default
462 boolean inRoot;
463
464 /// choose the appropiate title
465 if (chosenFile == null) {
466 chosenFile = mFile; // if no file is passed, current file decides
467 }
468 inRoot = (
469 chosenFile == null ||
470 (chosenFile.isFolder() && chosenFile.getParentId() == FileDataStorageManager.ROOT_PARENT_ID)
471 );
472 if (!inRoot) {
473 title = chosenFile.getFileName();
474 }
475
476 /// set the chosen title
477 ActionBar actionBar = getSupportActionBar();
478 actionBar.setTitle(title);
479 /// also as content description
480 View actionBarTitleView = getWindow().getDecorView().findViewById(
481 getResources().getIdentifier("action_bar_title", "id", "android")
482 );
483 if (actionBarTitleView != null) { // it's null in Android 2.x
484 actionBarTitleView.setContentDescription(title);
485 }
486
487 /// set home button properties
488 mDrawerToggle.setDrawerIndicatorEnabled(inRoot);
489 actionBar.setDisplayHomeAsUpEnabled(true);
490 actionBar.setDisplayShowTitleEnabled(true);
491
492 }
493
494
495 /**
496 * Sets and validates the ownCloud {@link Account} associated to the Activity.
497 *
498 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
499 *
500 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
501 *
502 * @param account New {@link Account} to set.
503 * @param savedAccount When 'true', account was retrieved from a saved instance state.
504 */
505 protected void setAccount(Account account, boolean savedAccount) {
506 Account oldAccount = mAccount;
507 boolean validAccount =
508 (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(),
509 account.name));
510 if (validAccount) {
511 mAccount = account;
512 mAccountWasSet = true;
513 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
514
515 } else {
516 swapToDefaultAccount();
517 }
518 }
519
520
521 /**
522 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
523 *
524 * If no valid ownCloud {@link Account} exists, the the user is requested
525 * to create a new ownCloud {@link Account}.
526 *
527 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
528 */
529 private void swapToDefaultAccount() {
530 // default to the most recently used account
531 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
532 if (newAccount == null) {
533 /// no account available: force account creation
534 createFirstAccount();
535 mRedirectingToSetupAccount = true;
536 mAccountWasSet = false;
537 mAccountWasRestored = false;
538
539 } else {
540 mAccountWasSet = true;
541 mAccountWasRestored = (newAccount.equals(mAccount));
542 mAccount = newAccount;
543 }
544 }
545
546
547 /**
548 * Launches the account creation activity. To use when no ownCloud account is available
549 */
550 private void createFirstAccount() {
551 AccountManager am = AccountManager.get(getApplicationContext());
552 am.addAccount(MainApp.getAccountType(),
553 null,
554 null,
555 null,
556 this,
557 new AccountCreationCallback(),
558 null);
559 }
560
561
562 /**
563 * {@inheritDoc}
564 */
565 @Override
566 protected void onSaveInstanceState(Bundle outState) {
567 super.onSaveInstanceState(outState);
568 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
569 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
570 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
571 if(getSupportActionBar() != null && getSupportActionBar().getTitle() != null) {
572 // Null check in case the actionbar is used in ActionBar.NAVIGATION_MODE_LIST
573 // since it doesn't have a title then
574 outState.putString(KEY_ACTION_BAR_TITLE, getSupportActionBar().getTitle().toString());
575 }
576 }
577
578
579 /**
580 * Getter for the main {@link OCFile} handled by the activity.
581 *
582 * @return Main {@link OCFile} handled by the activity.
583 */
584 public OCFile getFile() {
585 return mFile;
586 }
587
588
589 /**
590 * Setter for the main {@link OCFile} handled by the activity.
591 *
592 * @param file Main {@link OCFile} to be handled by the activity.
593 */
594 public void setFile(OCFile file) {
595 mFile = file;
596 }
597
598
599 /**
600 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity
601 * is located.
602 *
603 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity
604 * is located.
605 */
606 public Account getAccount() {
607 return mAccount;
608 }
609
610 protected void setAccount(Account account) {
611 mAccount = account;
612 }
613
614
615 /**
616 * Getter for the capabilities of the server where the current OC account lives.
617 *
618 * @return Capabilities of the server where the current OC account lives. Null if the account is not
619 * set yet.
620 */
621 public OCCapability getCapabilities() {
622 return mCapabilities;
623 }
624
625
626 /**
627 * @return Value of mFromNotification: True if the Activity is launched by a notification
628 */
629 public boolean fromNotification() {
630 return mFromNotification;
631 }
632
633 /**
634 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
635 */
636 protected boolean isRedirectingToSetupAccount() {
637 return mRedirectingToSetupAccount;
638 }
639
640 public OperationsServiceBinder getOperationsServiceBinder() {
641 return mOperationsServiceBinder;
642 }
643
644 protected ServiceConnection newTransferenceServiceConnection() {
645 return null;
646 }
647
648 /**
649 * Helper class handling a callback from the {@link AccountManager} after the creation of
650 * a new ownCloud {@link Account} finished, successfully or not.
651 *
652 * At this moment, only called after the creation of the first account.
653 */
654 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
655
656 @Override
657 public void run(AccountManagerFuture<Bundle> future) {
658 FileActivity.this.mRedirectingToSetupAccount = false;
659 boolean accountWasSet = false;
660 if (future != null) {
661 try {
662 Bundle result;
663 result = future.getResult();
664 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
665 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
666 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
667 setAccount(new Account(name, type), false);
668 accountWasSet = true;
669 }
670 } catch (OperationCanceledException e) {
671 Log_OC.d(TAG, "Account creation canceled");
672
673 } catch (Exception e) {
674 Log_OC.e(TAG, "Account creation finished in exception: ", e);
675 }
676
677 } else {
678 Log_OC.e(TAG, "Account creation callback with null bundle");
679 }
680 if (!accountWasSet) {
681 moveTaskToBack(true);
682 }
683 }
684
685 }
686
687
688 /**
689 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
690 *
691 * Child classes must grant that state depending on the {@link Account} is updated.
692 */
693 protected void onAccountSet(boolean stateWasRecovered) {
694 if (getAccount() != null) {
695 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
696 mCapabilities = mStorageManager.getCapability(mAccount.name);
697
698 } else {
699 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
700 }
701 }
702
703
704 public FileDataStorageManager getStorageManager() {
705 return mStorageManager;
706 }
707
708
709 public OnRemoteOperationListener getRemoteOperationListener() {
710 return this;
711 }
712
713
714 public Handler getHandler() {
715 return mHandler;
716 }
717
718 public FileOperationsHelper getFileOperationsHelper() {
719 return mFileOperationsHelper;
720 }
721
722 /**
723 *
724 * @param operation Removal operation performed.
725 * @param result Result of the removal.
726 */
727 @Override
728 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
729 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the "
730 + "FileActivities ");
731
732 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
733
734 dismissLoadingDialog();
735
736 if (!result.isSuccess() && (
737 result.getCode() == ResultCode.UNAUTHORIZED ||
738 result.isIdPRedirection() ||
739 (result.isException() && result.getException() instanceof AuthenticatorException)
740 )) {
741
742 requestCredentialsUpdate();
743
744 if (result.getCode() == ResultCode.UNAUTHORIZED) {
745 dismissLoadingDialog();
746 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
747 operation, getResources()),
748 Toast.LENGTH_LONG);
749 t.show();
750 }
751
752 } else if (operation == null ||
753 operation instanceof CreateShareWithShareeOperation ||
754 operation instanceof UnshareOperation ||
755 operation instanceof SynchronizeFolderOperation ||
756 operation instanceof UpdateShareViaLinkOperation
757 ) {
758 if (result.isSuccess()) {
759 updateFileFromDB();
760
761 } else if (result.getCode() != ResultCode.CANCELLED) {
762 Toast t = Toast.makeText(this,
763 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
764 Toast.LENGTH_LONG);
765 t.show();
766 }
767
768 } else if (operation instanceof CreateShareViaLinkOperation) {
769 onCreateShareViaLinkOperationFinish((CreateShareViaLinkOperation) operation, result);
770
771 } else if (operation instanceof SynchronizeFileOperation) {
772 onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
773
774 } else if (operation instanceof GetSharesForFileOperation) {
775 if (result.isSuccess() || result.getCode() == ResultCode.SHARE_NOT_FOUND) {
776 updateFileFromDB();
777
778 } else {
779 Toast t = Toast.makeText(this,
780 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
781 Toast.LENGTH_LONG);
782 t.show();
783 }
784 }
785 }
786
787 protected void requestCredentialsUpdate() {
788 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
789 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
790 updateAccountCredentials.putExtra(
791 AuthenticatorActivity.EXTRA_ACTION,
792 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
793 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
794 startActivity(updateAccountCredentials);
795 }
796
797
798
799 private void onCreateShareViaLinkOperationFinish(CreateShareViaLinkOperation operation,
800 RemoteOperationResult result) {
801 if (result.isSuccess()) {
802 updateFileFromDB();
803
804 Intent sendIntent = operation.getSendIntentWithSubject(this);
805 if (sendIntent != null) {
806 startActivity(sendIntent);
807 }
808
809 } else {
810 // Detect Failure (403) --> needs Password
811 if (result.getCode() == ResultCode.SHARE_FORBIDDEN) {
812 String password = operation.getPassword();
813 if ((password == null || password.length() == 0) &&
814 getCapabilities().getFilesSharingPublicEnabled().isUnknown())
815 {
816 // Was tried without password, but not sure that it's optional. Try with password.
817 // Try with password before giving up.
818 // See also ShareFileFragment#OnShareViaLinkListener
819 SharePasswordDialogFragment dialog =
820 SharePasswordDialogFragment.newInstance(new OCFile(operation.getPath()), true);
821 dialog.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD);
822 } else {
823 Toast t = Toast.makeText(this,
824 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
825 Toast.LENGTH_LONG);
826 t.show();
827 }
828 } else {
829 Toast t = Toast.makeText(this,
830 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
831 Toast.LENGTH_LONG);
832 t.show();
833 }
834 }
835 }
836
837 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
838 RemoteOperationResult result) {
839 OCFile syncedFile = operation.getLocalFile();
840 if (!result.isSuccess()) {
841 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
842 Intent i = new Intent(this, ConflictsResolveActivity.class);
843 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
844 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
845 startActivity(i);
846 }
847
848 } else {
849 if (!operation.transferWasRequested()) {
850 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
851 operation, getResources()), Toast.LENGTH_LONG);
852 msg.show();
853 }
854 invalidateOptionsMenu();
855 }
856 }
857
858 protected void updateFileFromDB(){
859 OCFile file = getFile();
860 if (file != null) {
861 file = getStorageManager().getFileByPath(file.getRemotePath());
862 setFile(file);
863 }
864 }
865
866
867 /**
868 * Show loading dialog
869 */
870 public void showLoadingDialog(String message) {
871 // Construct dialog
872 LoadingDialog loading = new LoadingDialog(message);
873 FragmentManager fm = getSupportFragmentManager();
874 FragmentTransaction ft = fm.beginTransaction();
875 loading.show(ft, DIALOG_WAIT_TAG);
876
877 }
878
879
880 /**
881 * Dismiss loading dialog
882 */
883 public void dismissLoadingDialog() {
884 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
885 if (frag != null) {
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 // TODO re-enable when "Accounts" is available in Navigation Drawer
958 // public void closeDrawer() {
959 // mDrawerLayout.closeDrawers();
960 // }
961
962 public void allFilesOption(){
963 restart();
964 }
965
966 private class DrawerItemClickListener implements ListView.OnItemClickListener {
967 @Override
968 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
969 // TODO re-enable when "Accounts" is available in Navigation Drawer
970 // if (mShowAccounts && position > 0){
971 // position = position - 1;
972 // }
973 switch (position){
974 // TODO re-enable when "Accounts" is available in Navigation Drawer
975 // case 0: // Accounts
976 // mShowAccounts = !mShowAccounts;
977 // mNavigationDrawerAdapter.setShowAccounts(mShowAccounts);
978 // mNavigationDrawerAdapter.notifyDataSetChanged();
979 // break;
980
981 case 0: // All Files
982 allFilesOption();
983 mDrawerLayout.closeDrawers();
984 break;
985
986 // TODO Enable when "On Device" is recovered ?
987 // case 2:
988 // MainApp.showOnlyFilesOnDevice(true);
989 // mDrawerLayout.closeDrawers();
990 // break;
991
992 case 1: // Settings
993 Intent settingsIntent = new Intent(getApplicationContext(),
994 Preferences.class);
995 startActivity(settingsIntent);
996 mDrawerLayout.closeDrawers();
997 break;
998
999 case 2: // Logs
1000 Intent loggerIntent = new Intent(getApplicationContext(),
1001 LogHistoryActivity.class);
1002 startActivity(loggerIntent);
1003 mDrawerLayout.closeDrawers();
1004 break;
1005 }
1006 }
1007 }
1008 }