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