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