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