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