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