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