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