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