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