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