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