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