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