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