Merge branch 'develop' into cancel_transfer_for_deleted_users
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2015 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import android.accounts.Account;
22 import android.accounts.AccountManager;
23 import android.accounts.AccountManagerCallback;
24 import android.accounts.AccountManagerFuture;
25 import android.accounts.AuthenticatorException;
26 import android.accounts.OnAccountsUpdateListener;
27 import android.accounts.OperationCanceledException;
28 import android.content.ComponentName;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.ServiceConnection;
32 import android.os.Bundle;
33 import android.os.Handler;
34 import android.os.IBinder;
35 import android.support.v4.app.Fragment;
36 import android.support.v4.app.FragmentManager;
37 import android.support.v4.app.FragmentTransaction;
38 import android.widget.Toast;
39
40 import com.actionbarsherlock.app.SherlockFragmentActivity;
41 import com.owncloud.android.MainApp;
42 import com.owncloud.android.R;
43 import com.owncloud.android.authentication.AccountUtils;
44 import com.owncloud.android.authentication.AuthenticatorActivity;
45 import com.owncloud.android.datamodel.FileDataStorageManager;
46 import com.owncloud.android.datamodel.OCFile;
47 import com.owncloud.android.files.FileOperationsHelper;
48 import com.owncloud.android.files.services.FileDownloader;
49 import com.owncloud.android.files.services.FileUploader;
50 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
51 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
52 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
53 import com.owncloud.android.lib.common.operations.RemoteOperation;
54 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
55 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
56 import com.owncloud.android.lib.common.utils.Log_OC;
57 import com.owncloud.android.operations.CreateShareOperation;
58 import com.owncloud.android.operations.SynchronizeFolderOperation;
59 import com.owncloud.android.operations.UnshareLinkOperation;
60
61 import com.owncloud.android.services.OperationsService;
62 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
63 import com.owncloud.android.ui.dialog.LoadingDialog;
64 import com.owncloud.android.utils.ErrorMessageAdapter;
65
66
67 /**
68 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
69 *
70 * @author David A. Velasco
71 */
72 public class FileActivity extends SherlockFragmentActivity
73 implements OnRemoteOperationListener, ComponentsGetter, OnAccountsUpdateListener {
74
75 public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
76 public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
77 public static final String EXTRA_WAITING_TO_PREVIEW = "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
78 public static final String EXTRA_FROM_NOTIFICATION= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
79
80 public static final String TAG = FileActivity.class.getSimpleName();
81
82 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
83 private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
84
85 protected static final long DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS = 200;
86
87
88 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
89 private Account mAccount;
90
91 /** Main {@link OCFile} handled by the activity.*/
92 private OCFile mFile;
93
94 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
95 private boolean mRedirectingToSetupAccount = false;
96
97 /** Flag to signal when the value of mAccount was set */
98 private boolean mAccountWasSet;
99
100 /** Flag to signal when the value of mAccount was restored from a saved state */
101 private boolean mAccountWasRestored;
102
103 /** Flag to signal if the activity is launched by a notification */
104 private boolean mFromNotification;
105
106 /** Messages handler associated to the main thread and the life cycle of the activity */
107 private Handler mHandler;
108
109 /** Access point to the cached database for the current ownCloud {@link Account} */
110 private FileDataStorageManager mStorageManager = null;
111
112 private FileOperationsHelper mFileOperationsHelper;
113
114 private ServiceConnection mOperationsServiceConnection = null;
115
116 private OperationsServiceBinder mOperationsServiceBinder = null;
117
118 protected FileDownloaderBinder mDownloaderBinder = null;
119 protected FileUploaderBinder mUploaderBinder = null;
120 private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
121
122
123 /**
124 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
125 * the {@link FileActivity}.
126 *
127 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
128 * is requested to create a new one.
129 */
130 @Override
131 protected void onCreate(Bundle savedInstanceState) {
132 super.onCreate(savedInstanceState);
133 mHandler = new Handler();
134 mFileOperationsHelper = new FileOperationsHelper(this);
135 Account account;
136 if(savedInstanceState != null) {
137 account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
138 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
139 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
140 mFileOperationsHelper.setOpIdWaitingFor(
141 savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID, Long.MAX_VALUE)
142 );
143 } else {
144 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
145 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
146 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION, false);
147 }
148
149 setAccount(account, savedInstanceState != null);
150
151 mOperationsServiceConnection = new OperationsServiceConnection();
152 bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection, Context.BIND_AUTO_CREATE);
153
154 mDownloadServiceConnection = newTransferenceServiceConnection();
155 if (mDownloadServiceConnection != null) {
156 bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection, Context.BIND_AUTO_CREATE);
157 }
158 mUploadServiceConnection = newTransferenceServiceConnection();
159 if (mUploadServiceConnection != null) {
160 bindService(new Intent(this, FileUploader.class), mUploadServiceConnection, Context.BIND_AUTO_CREATE);
161 }
162
163 // add AccountsUpdatedListener
164 AccountManager am = AccountManager.get(getApplicationContext());
165 am.addOnAccountsUpdatedListener(this, null, false);
166
167 }
168
169
170 /**
171 * Since ownCloud {@link Account}s can be managed from the system setting menu,
172 * the existence of the {@link Account} associated to the instance must be checked
173 * every time it is restarted.
174 */
175 @Override
176 protected void onRestart() {
177 super.onRestart();
178 boolean validAccount = (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name));
179 if (!validAccount) {
180 swapToDefaultAccount();
181 }
182 }
183
184
185 @Override
186 protected void onStart() {
187 super.onStart();
188
189 if (mAccountWasSet) {
190 onAccountSet(mAccountWasRestored);
191 }
192 }
193
194 @Override
195 protected void onResume() {
196 super.onResume();
197
198 if (mOperationsServiceBinder != null) {
199 doOnResumeAndBound();
200 }
201
202 }
203
204 @Override
205 protected void onPause() {
206
207 if (mOperationsServiceBinder != null) {
208 mOperationsServiceBinder.removeOperationListener(this);
209 }
210
211 super.onPause();
212 }
213
214
215 @Override
216 protected void onDestroy() {
217 if (mOperationsServiceConnection != null) {
218 unbindService(mOperationsServiceConnection);
219 mOperationsServiceBinder = null;
220 }
221 if (mDownloadServiceConnection != null) {
222 unbindService(mDownloadServiceConnection);
223 mDownloadServiceConnection = null;
224 }
225 if (mUploadServiceConnection != null) {
226 unbindService(mUploadServiceConnection);
227 mUploadServiceConnection = null;
228 }
229
230 // remove AccountsUpdatedListener
231 AccountManager am = AccountManager.get(getApplicationContext());
232 am.removeOnAccountsUpdatedListener(this);
233
234 super.onDestroy();
235 }
236
237
238 /**
239 * Sets and validates the ownCloud {@link Account} associated to the Activity.
240 *
241 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
242 *
243 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
244 *
245 * @param account New {@link Account} to set.
246 * @param savedAccount When 'true', account was retrieved from a saved instance state.
247 */
248 private void setAccount(Account account, boolean savedAccount) {
249 Account oldAccount = mAccount;
250 boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
251 if (validAccount) {
252 mAccount = account;
253 mAccountWasSet = true;
254 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
255
256 } else {
257 swapToDefaultAccount();
258 }
259 }
260
261
262 /**
263 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
264 *
265 * If no valid ownCloud {@link Account} exists, the the user is requested
266 * to create a new ownCloud {@link Account}.
267 *
268 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
269 */
270 private void swapToDefaultAccount() {
271 // default to the most recently used account
272 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
273 if (newAccount == null) {
274 /// no account available: force account creation
275 createFirstAccount();
276 mRedirectingToSetupAccount = true;
277 mAccountWasSet = false;
278 mAccountWasRestored = false;
279
280 } else {
281 mAccountWasSet = true;
282 mAccountWasRestored = (newAccount.equals(mAccount));
283 mAccount = newAccount;
284 }
285 }
286
287
288 /**
289 * Launches the account creation activity. To use when no ownCloud account is available
290 */
291 private void createFirstAccount() {
292 AccountManager am = AccountManager.get(getApplicationContext());
293 am.addAccount(MainApp.getAccountType(),
294 null,
295 null,
296 null,
297 this,
298 new AccountCreationCallback(),
299 null);
300 am.addOnAccountsUpdatedListener(this, null, true);
301 }
302
303
304 /**
305 * {@inheritDoc}
306 */
307 @Override
308 protected void onSaveInstanceState(Bundle outState) {
309 super.onSaveInstanceState(outState);
310 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
311 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
312 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
313 outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
314 }
315
316
317 /**
318 * Getter for the main {@link OCFile} handled by the activity.
319 *
320 * @return Main {@link OCFile} handled by the activity.
321 */
322 public OCFile getFile() {
323 return mFile;
324 }
325
326
327 /**
328 * Setter for the main {@link OCFile} handled by the activity.
329 *
330 * @param file Main {@link OCFile} to be handled by the activity.
331 */
332 public void setFile(OCFile file) {
333 mFile = file;
334 }
335
336
337 /**
338 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
339 *
340 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
341 */
342 public Account getAccount() {
343 return mAccount;
344 }
345
346 /**
347 * @return Value of mFromNotification: True if the Activity is launched by a notification
348 */
349 public boolean fromNotification() {
350 return mFromNotification;
351 }
352
353 /**
354 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
355 */
356 protected boolean isRedirectingToSetupAccount() {
357 return mRedirectingToSetupAccount;
358 }
359
360
361 public OperationsServiceBinder getOperationsServiceBinder() {
362 return mOperationsServiceBinder;
363 }
364
365 protected ServiceConnection newTransferenceServiceConnection() {
366 return null;
367 }
368
369 @Override
370 public void onAccountsUpdated(Account[] accounts) {
371 // detect a change in the list of accounts
372 Log_OC.d(TAG, "onAccountsUpdated");
373 mDownloaderBinder.reviewDownloads();
374 mUploaderBinder.reviewUploads();
375 }
376
377
378 /**
379 * Helper class handling a callback from the {@link AccountManager} after the creation of
380 * a new ownCloud {@link Account} finished, successfully or not.
381 *
382 * At this moment, only called after the creation of the first account.
383 *
384 * @author David A. Velasco
385 */
386 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
387
388 @Override
389 public void run(AccountManagerFuture<Bundle> future) {
390 FileActivity.this.mRedirectingToSetupAccount = false;
391 boolean accountWasSet = false;
392 if (future != null) {
393 try {
394 Bundle result;
395 result = future.getResult();
396 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
397 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
398 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
399 setAccount(new Account(name, type), false);
400 accountWasSet = true;
401 }
402 } catch (OperationCanceledException e) {
403 Log_OC.d(TAG, "Account creation canceled");
404
405 } catch (Exception e) {
406 Log_OC.e(TAG, "Account creation finished in exception: ", e);
407 }
408
409 } else {
410 Log_OC.e(TAG, "Account creation callback with null bundle");
411 }
412 if (!accountWasSet) {
413 moveTaskToBack(true);
414 }
415 }
416
417 }
418
419
420 /**
421 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
422 *
423 * Child classes must grant that state depending on the {@link Account} is updated.
424 */
425 protected void onAccountSet(boolean stateWasRecovered) {
426 if (getAccount() != null) {
427 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
428
429 } else {
430 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
431 }
432 }
433
434
435 public FileDataStorageManager getStorageManager() {
436 return mStorageManager;
437 }
438
439
440 public OnRemoteOperationListener getRemoteOperationListener() {
441 return this;
442 }
443
444
445 public Handler getHandler() {
446 return mHandler;
447 }
448
449 public FileOperationsHelper getFileOperationsHelper() {
450 return mFileOperationsHelper;
451 }
452
453 /**
454 *
455 * @param operation Removal operation performed.
456 * @param result Result of the removal.
457 */
458 @Override
459 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
460 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
461
462 mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);
463
464 if (!result.isSuccess() && (
465 result.getCode() == ResultCode.UNAUTHORIZED ||
466 result.isIdPRedirection() ||
467 (result.isException() && result.getException() instanceof AuthenticatorException)
468 )) {
469
470 requestCredentialsUpdate();
471
472 if (result.getCode() == ResultCode.UNAUTHORIZED) {
473 dismissLoadingDialog();
474 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
475 Toast.LENGTH_LONG);
476 t.show();
477 }
478
479 } else if (operation instanceof CreateShareOperation) {
480 onCreateShareOperationFinish((CreateShareOperation) operation, result);
481
482 } else if (operation instanceof UnshareLinkOperation) {
483 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
484
485 } else if (operation instanceof SynchronizeFolderOperation) {
486 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
487
488 }
489 }
490
491 protected void requestCredentialsUpdate() {
492 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
493 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
494 updateAccountCredentials.putExtra(
495 AuthenticatorActivity.EXTRA_ACTION,
496 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
497 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
498 startActivity(updateAccountCredentials);
499 }
500
501
502 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
503 dismissLoadingDialog();
504 if (result.isSuccess()) {
505 updateFileFromDB();
506
507 Intent sendIntent = operation.getSendIntent();
508 startActivity(sendIntent);
509
510 } else {
511 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
512 Toast.LENGTH_LONG);
513 t.show();
514 }
515 }
516
517
518 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
519 dismissLoadingDialog();
520
521 if (result.isSuccess()){
522 updateFileFromDB();
523
524 } else {
525 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
526 Toast.LENGTH_LONG);
527 t.show();
528 }
529 }
530
531 private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation, RemoteOperationResult result) {
532 if (!result.isSuccess() && result.getCode() != ResultCode.CANCELLED){
533 Toast t = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
534 Toast.LENGTH_LONG);
535 t.show();
536 }
537 }
538
539 protected void updateFileFromDB(){
540 OCFile file = getFile();
541 if (file != null) {
542 file = getStorageManager().getFileByPath(file.getRemotePath());
543 setFile(file);
544 }
545 }
546
547 /**
548 * Show loading dialog
549 */
550 public void showLoadingDialog() {
551 // Construct dialog
552 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
553 FragmentManager fm = getSupportFragmentManager();
554 FragmentTransaction ft = fm.beginTransaction();
555 loading.show(ft, DIALOG_WAIT_TAG);
556
557 }
558
559
560 /**
561 * Dismiss loading dialog
562 */
563 public void dismissLoadingDialog(){
564 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
565 if (frag != null) {
566 LoadingDialog loading = (LoadingDialog) frag;
567 loading.dismiss();
568 }
569 }
570
571
572 private void doOnResumeAndBound() {
573 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
574 long waitingForOpId = mFileOperationsHelper.getOpIdWaitingFor();
575 if (waitingForOpId <= Integer.MAX_VALUE) {
576 boolean wait = mOperationsServiceBinder.dispatchResultIfFinished((int)waitingForOpId, this);
577 if (!wait ) {
578 dismissLoadingDialog();
579 }
580 }
581 }
582
583
584 /**
585 * Implements callback methods for service binding. Passed as a parameter to {
586 */
587 private class OperationsServiceConnection implements ServiceConnection {
588
589 @Override
590 public void onServiceConnected(ComponentName component, IBinder service) {
591 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
592 Log_OC.d(TAG, "Operations service connected");
593 mOperationsServiceBinder = (OperationsServiceBinder) service;
594 /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
595 dismissLoadingDialog();
596 }*/
597 doOnResumeAndBound();
598
599 } else {
600 return;
601 }
602 }
603
604
605 @Override
606 public void onServiceDisconnected(ComponentName component) {
607 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
608 Log_OC.d(TAG, "Operations service disconnected");
609 mOperationsServiceBinder = null;
610 // TODO whatever could be waiting for the service is unbound
611 }
612 }
613 }
614
615
616 @Override
617 public FileDownloaderBinder getFileDownloaderBinder() {
618 return mDownloaderBinder;
619 }
620
621
622 @Override
623 public FileUploaderBinder getFileUploaderBinder() {
624 return mUploaderBinder;
625 }
626
627
628 }