Add NavigationDrawer to image preview
[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.ImageView;
48 import android.widget.LinearLayout;
49 import android.widget.ListView;
50 import android.widget.TextView;
51 import android.widget.Toast;
52
53 import com.owncloud.android.BuildConfig;
54 import com.owncloud.android.MainApp;
55 import com.owncloud.android.R;
56 import com.owncloud.android.authentication.AccountUtils;
57 import com.owncloud.android.authentication.AuthenticatorActivity;
58 import com.owncloud.android.datamodel.FileDataStorageManager;
59 import com.owncloud.android.datamodel.OCFile;
60 import com.owncloud.android.files.FileOperationsHelper;
61 import com.owncloud.android.files.services.FileDownloader;
62 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
63 import com.owncloud.android.files.services.FileUploader;
64 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
65 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
66 import com.owncloud.android.lib.common.operations.RemoteOperation;
67 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
68 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
69 import com.owncloud.android.lib.common.utils.Log_OC;
70 import com.owncloud.android.operations.CreateShareOperation;
71 import com.owncloud.android.operations.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.DisplayUtils;
80 import com.owncloud.android.utils.ErrorMessageAdapter;
81
82 import java.util.ArrayList;
83
84
85 /**
86 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud
87 * {@link Account}s .
88 */
89 public class FileActivity extends ActionBarActivity
90 implements OnRemoteOperationListener, ComponentsGetter {
91
92 public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
93 public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
94 public static final String EXTRA_WAITING_TO_PREVIEW =
95 "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
96 public static final String EXTRA_FROM_NOTIFICATION =
97 "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
98
99 public static final String TAG = FileActivity.class.getSimpleName();
100
101 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
102 private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
103 private static final String DIALOG_SHARE_PASSWORD = "DIALOG_SHARE_PASSWORD";
104 private static final String KEY_TRY_SHARE_AGAIN = "TRY_SHARE_AGAIN";
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 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 } 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 // load Account in the Drawer Title
307 // User-Icon
308 ImageView userIcon = (ImageView) navigationDrawerLayout.findViewById(R.id.drawer_userIcon);
309 userIcon.setImageResource(DisplayUtils.getSeasonalIconId());
310
311 // Username
312 TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username);
313 Account account = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
314
315 if (account != null) {
316 int lastAtPos = account.name.lastIndexOf("@");
317 username.setText(account.name.substring(0, lastAtPos));
318 }
319
320 // load slide menu items
321 mDrawerTitles = getResources().getStringArray(R.array.drawer_items);
322
323 // nav drawer content description from resources
324 mDrawerContentDescriptions = getResources().
325 getStringArray(R.array.drawer_content_descriptions);
326
327 // nav drawer items
328 mDrawerItems = new ArrayList<NavigationDrawerItem>();
329 // adding nav drawer items to array
330 // Accounts
331 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[0], mDrawerContentDescriptions[0]));
332 // All Files
333 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[1], mDrawerContentDescriptions[1]));
334
335 // TODO Enable when "On Device" is recovered
336 // On Device
337 //mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[2],
338 // mDrawerContentDescriptions[2]));
339
340 // Settings
341 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[2], mDrawerContentDescriptions[2]));
342 // Logs
343 if (BuildConfig.DEBUG) {
344 mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[3],
345 mDrawerContentDescriptions[3]));
346 }
347
348 // setting the nav drawer list adapter
349 mNavigationDrawerAdapter = new NavigationDrawerListAdapter(getApplicationContext(), this,
350 mDrawerItems);
351 mDrawerList.setAdapter(mNavigationDrawerAdapter);
352
353 mDrawerToggle = new ActionBarDrawerToggle(
354 this,
355 mDrawerLayout,
356 R.drawable.ic_drawer,
357 R.string.drawer_open,
358 R.string.drawer_close) {
359
360 /** Called when a drawer has settled in a completely closed state. */
361 public void onDrawerClosed(View view) {
362 super.onDrawerClosed(view);
363 getSupportActionBar().setDisplayShowTitleEnabled(true);
364 getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
365 //initFragmentsWithFile();
366 invalidateOptionsMenu();
367 }
368
369 /** Called when a drawer has settled in a completely open state. */
370 public void onDrawerOpened(View drawerView) {
371 super.onDrawerOpened(drawerView);
372 getSupportActionBar().setTitle(R.string.drawer_open);
373 getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
374 invalidateOptionsMenu();
375 }
376 };
377
378 mDrawerToggle.setDrawerIndicatorEnabled(true);
379 // Set the list's click listener
380 mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
381
382 // Set the drawer toggle as the DrawerListener
383 mDrawerLayout.setDrawerListener(mDrawerToggle);
384 }
385
386 /**
387 * Sets and validates the ownCloud {@link Account} associated to the Activity.
388 *
389 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
390 *
391 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
392 *
393 * @param account New {@link Account} to set.
394 * @param savedAccount When 'true', account was retrieved from a saved instance state.
395 */
396 protected void setAccount(Account account, boolean savedAccount) {
397 Account oldAccount = mAccount;
398 boolean validAccount =
399 (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(),
400 account.name));
401 if (validAccount) {
402 mAccount = account;
403 mAccountWasSet = true;
404 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
405
406 } else {
407 swapToDefaultAccount();
408 }
409 }
410
411
412 /**
413 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
414 *
415 * If no valid ownCloud {@link Account} exists, the the user is requested
416 * to create a new ownCloud {@link Account}.
417 *
418 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
419 */
420 private void swapToDefaultAccount() {
421 // default to the most recently used account
422 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
423 if (newAccount == null) {
424 /// no account available: force account creation
425 createFirstAccount();
426 mRedirectingToSetupAccount = true;
427 mAccountWasSet = false;
428 mAccountWasRestored = false;
429
430 } else {
431 mAccountWasSet = true;
432 mAccountWasRestored = (newAccount.equals(mAccount));
433 mAccount = newAccount;
434 }
435 }
436
437
438 /**
439 * Launches the account creation activity. To use when no ownCloud account is available
440 */
441 private void createFirstAccount() {
442 AccountManager am = AccountManager.get(getApplicationContext());
443 am.addAccount(MainApp.getAccountType(),
444 null,
445 null,
446 null,
447 this,
448 new AccountCreationCallback(),
449 null);
450 }
451
452
453 /**
454 * {@inheritDoc}
455 */
456 @Override
457 protected void onSaveInstanceState(Bundle outState) {
458 super.onSaveInstanceState(outState);
459 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
460 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
461 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
462 outState.putBoolean(KEY_TRY_SHARE_AGAIN, mTryShareAgain);
463 }
464
465
466 /**
467 * Getter for the main {@link OCFile} handled by the activity.
468 *
469 * @return Main {@link OCFile} handled by the activity.
470 */
471 public OCFile getFile() {
472 return mFile;
473 }
474
475
476 /**
477 * Setter for the main {@link OCFile} handled by the activity.
478 *
479 * @param file Main {@link OCFile} to be handled by the activity.
480 */
481 public void setFile(OCFile file) {
482 mFile = file;
483 }
484
485
486 /**
487 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity
488 * is located.
489 *
490 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity
491 * is located.
492 */
493 public Account getAccount() {
494 return mAccount;
495 }
496
497 protected void setAccount(Account account) {
498 mAccount = account;
499 }
500
501 /**
502 * @return Value of mFromNotification: True if the Activity is launched by a notification
503 */
504 public boolean fromNotification() {
505 return mFromNotification;
506 }
507
508 /**
509 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
510 */
511 protected boolean isRedirectingToSetupAccount() {
512 return mRedirectingToSetupAccount;
513 }
514
515 public boolean isTryShareAgain(){
516 return mTryShareAgain;
517 }
518
519 public void setTryShareAgain(boolean tryShareAgain) {
520 mTryShareAgain = tryShareAgain;
521 }
522
523 public OperationsServiceBinder getOperationsServiceBinder() {
524 return mOperationsServiceBinder;
525 }
526
527 protected ServiceConnection newTransferenceServiceConnection() {
528 return null;
529 }
530
531 /**
532 * Helper class handling a callback from the {@link AccountManager} after the creation of
533 * a new ownCloud {@link Account} finished, successfully or not.
534 *
535 * At this moment, only called after the creation of the first account.
536 */
537 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
538
539 @Override
540 public void run(AccountManagerFuture<Bundle> future) {
541 FileActivity.this.mRedirectingToSetupAccount = false;
542 boolean accountWasSet = false;
543 if (future != null) {
544 try {
545 Bundle result;
546 result = future.getResult();
547 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
548 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
549 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
550 setAccount(new Account(name, type), false);
551 accountWasSet = true;
552 }
553 } catch (OperationCanceledException e) {
554 Log_OC.d(TAG, "Account creation canceled");
555
556 } catch (Exception e) {
557 Log_OC.e(TAG, "Account creation finished in exception: ", e);
558 }
559
560 } else {
561 Log_OC.e(TAG, "Account creation callback with null bundle");
562 }
563 if (!accountWasSet) {
564 moveTaskToBack(true);
565 }
566 }
567
568 }
569
570
571 /**
572 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
573 *
574 * Child classes must grant that state depending on the {@link Account} is updated.
575 */
576 protected void onAccountSet(boolean stateWasRecovered) {
577 if (getAccount() != null) {
578 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
579
580 } else {
581 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
582 }
583 }
584
585
586 public FileDataStorageManager getStorageManager() {
587 return mStorageManager;
588 }
589
590
591 public OnRemoteOperationListener getRemoteOperationListener() {
592 return this;
593 }
594
595
596 public Handler getHandler() {
597 return mHandler;
598 }
599
600 public FileOperationsHelper getFileOperationsHelper() {
601 return mFileOperationsHelper;
602 }
603
604 /**
605 *
606 * @param operation Removal operation performed.
607 * @param result Result of the removal.
608 */
609 @Override
610 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
611 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the " +
612 "FileActivities ");
613
614 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
615
616 if (!result.isSuccess() && (
617 result.getCode() == ResultCode.UNAUTHORIZED ||
618 result.isIdPRedirection() ||
619 (result.isException() && result.getException() instanceof AuthenticatorException)
620 )) {
621
622 requestCredentialsUpdate();
623
624 if (result.getCode() == ResultCode.UNAUTHORIZED) {
625 dismissLoadingDialog();
626 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
627 operation, getResources()),
628 Toast.LENGTH_LONG);
629 t.show();
630 }
631 mTryShareAgain = false;
632
633 } else if (operation instanceof CreateShareOperation) {
634 onCreateShareOperationFinish((CreateShareOperation) operation, result);
635
636 } else if (operation instanceof UnshareLinkOperation) {
637 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
638
639 } else if (operation instanceof SynchronizeFolderOperation) {
640 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
641
642 }
643 }
644
645 protected void requestCredentialsUpdate() {
646 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
647 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
648 updateAccountCredentials.putExtra(
649 AuthenticatorActivity.EXTRA_ACTION,
650 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
651 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
652 startActivity(updateAccountCredentials);
653 }
654
655
656 private void onCreateShareOperationFinish(CreateShareOperation operation,
657 RemoteOperationResult result) {
658 dismissLoadingDialog();
659 if (result.isSuccess()) {
660 mTryShareAgain = false;
661 updateFileFromDB();
662
663 Intent sendIntent = operation.getSendIntent();
664 startActivity(sendIntent);
665 } else {
666 // Detect Failure (403) --> needs Password
667 if (result.getCode() == ResultCode.SHARE_FORBIDDEN) {
668 if (!isTryShareAgain()) {
669 SharePasswordDialogFragment dialog =
670 SharePasswordDialogFragment.newInstance(new OCFile(operation.getPath()),
671 operation.getSendIntent());
672 dialog.show(getSupportFragmentManager(), DIALOG_SHARE_PASSWORD);
673 } else {
674 Toast t = Toast.makeText(this,
675 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
676 Toast.LENGTH_LONG);
677 t.show();
678 mTryShareAgain = false;
679 }
680 } else {
681 Toast t = Toast.makeText(this,
682 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
683 Toast.LENGTH_LONG);
684 t.show();
685 }
686 }
687 }
688
689
690 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation,
691 RemoteOperationResult result) {
692 dismissLoadingDialog();
693
694 if (result.isSuccess()){
695 updateFileFromDB();
696
697 } else {
698 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
699 operation, getResources()), Toast.LENGTH_LONG);
700 t.show();
701 }
702 }
703
704 private void onSynchronizeFolderOperationFinish(
705 SynchronizeFolderOperation operation, RemoteOperationResult result
706 ) {
707 if (!result.isSuccess() && result.getCode() != ResultCode.CANCELLED){
708 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result,
709 operation, getResources()), Toast.LENGTH_LONG);
710 t.show();
711 }
712 }
713
714 protected void updateFileFromDB(){
715 OCFile file = getFile();
716 if (file != null) {
717 file = getStorageManager().getFileByPath(file.getRemotePath());
718 setFile(file);
719 }
720 }
721
722 /**
723 * Show loading dialog
724 */
725 public void showLoadingDialog() {
726 // Construct dialog
727 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
728 FragmentManager fm = getSupportFragmentManager();
729 FragmentTransaction ft = fm.beginTransaction();
730 loading.show(ft, DIALOG_WAIT_TAG);
731
732 }
733
734
735 /**
736 * Dismiss loading dialog
737 */
738 public void dismissLoadingDialog(){
739 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
740 if (frag != null) {
741 LoadingDialog loading = (LoadingDialog) frag;
742 loading.dismiss();
743 }
744 }
745
746
747 private void doOnResumeAndBound() {
748 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
749 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
750 if (waitingForOpId <= Integer.MAX_VALUE) {
751 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId,
752 this);
753 if (!wait ) {
754 dismissLoadingDialog();
755 }
756 }
757 }
758
759
760 /**
761 * Implements callback methods for service binding. Passed as a parameter to {
762 */
763 private class OperationsServiceConnection implements ServiceConnection {
764
765 @Override
766 public void onServiceConnected(ComponentName component, IBinder service) {
767 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
768 Log_OC.d(TAG, "Operations service connected");
769 mOperationsServiceBinder = (OperationsServiceBinder) service;
770 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
771 dismissLoadingDialog();
772 }*/
773 doOnResumeAndBound();
774
775 } else {
776 return;
777 }
778 }
779
780
781 @Override
782 public void onServiceDisconnected(ComponentName component) {
783 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
784 Log_OC.d(TAG, "Operations service disconnected");
785 mOperationsServiceBinder = null;
786 // TODO whatever could be waiting for the service is unbound
787 }
788 }
789 }
790
791
792 @Override
793 public FileDownloaderBinder getFileDownloaderBinder() {
794 return mDownloaderBinder;
795 }
796
797
798 @Override
799 public FileUploaderBinder getFileUploaderBinder() {
800 return mUploaderBinder;
801 }
802
803
804 public void restart(){
805 Intent i = new Intent(this, FileDisplayActivity.class);
806 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
807 startActivity(i);
808 }
809
810 public void closeDrawer() {
811 mDrawerLayout.closeDrawers();
812 }
813
814 private class DrawerItemClickListener implements ListView.OnItemClickListener {
815 @Override
816 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
817 if (mShowAccounts && position > 0){
818 position = position - 1;
819 }
820 switch (position){
821 case 0: // Accounts
822 mShowAccounts = !mShowAccounts;
823 mNavigationDrawerAdapter.setShowAccounts(mShowAccounts);
824 mNavigationDrawerAdapter.notifyDataSetChanged();
825 break;
826
827 case 1: // All Files
828 // TODO Enable when "On Device" is recovered ?
829 //MainApp.showOnlyFilesOnDevice(false);
830 mDrawerLayout.closeDrawers();
831 break;
832
833 // TODO Enable when "On Device" is recovered ?
834 // case 2:
835 // MainApp.showOnlyFilesOnDevice(true);
836 // mDrawerLayout.closeDrawers();
837 // break;
838
839 case 2: // Settings
840 Intent settingsIntent = new Intent(getApplicationContext(),
841 Preferences.class);
842 startActivity(settingsIntent);
843 break;
844
845 case 3: // Logs
846 Intent loggerIntent = new Intent(getApplicationContext(),
847 LogHistoryActivity.class);
848 startActivity(loggerIntent);
849 break;
850 }
851 }
852 }
853 }