28f7875089251d44dadee1168791ab5ab098184c
[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.operations.common.OnRemoteOperationListener;
46 import com.owncloud.android.lib.operations.common.RemoteOperation;
47 import com.owncloud.android.lib.operations.common.RemoteOperationResult;
48 import com.owncloud.android.lib.operations.common.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 if (mAccountWasSet) {
155 onAccountSet(mAccountWasRestored);
156 }
157 }
158
159
160 @Override
161 protected void onStop() {
162 super.onStop();
163 }
164
165
166 @Override
167 protected void onDestroy() {
168 super.onDestroy();
169 if (mOperationsServiceConnection != null) {
170 if (mOperationsServiceBinder != null) {
171 mOperationsServiceBinder.removeOperationListener(this);
172 mOperationsServiceBinder = null;
173 }
174 unbindService(mOperationsServiceConnection);
175 }
176 }
177
178
179 /**
180 * Sets and validates the ownCloud {@link Account} associated to the Activity.
181 *
182 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
183 *
184 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
185 *
186 * @param account New {@link Account} to set.
187 * @param savedAccount When 'true', account was retrieved from a saved instance state.
188 */
189 private void setAccount(Account account, boolean savedAccount) {
190 Account oldAccount = mAccount;
191 boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
192 if (validAccount) {
193 mAccount = account;
194 mAccountWasSet = true;
195 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
196
197 } else {
198 swapToDefaultAccount();
199 }
200 }
201
202
203 /**
204 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
205 *
206 * If no valid ownCloud {@link Account} exists, the the user is requested
207 * to create a new ownCloud {@link Account}.
208 *
209 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
210 *
211 * @return 'True' if the checked {@link Account} was valid.
212 */
213 private void swapToDefaultAccount() {
214 // default to the most recently used account
215 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
216 if (newAccount == null) {
217 /// no account available: force account creation
218 createFirstAccount();
219 mRedirectingToSetupAccount = true;
220 mAccountWasSet = false;
221 mAccountWasRestored = false;
222
223 } else {
224 mAccountWasSet = true;
225 mAccountWasRestored = (newAccount.equals(mAccount));
226 mAccount = newAccount;
227 }
228 }
229
230
231 /**
232 * Launches the account creation activity. To use when no ownCloud account is available
233 */
234 private void createFirstAccount() {
235 AccountManager am = AccountManager.get(getApplicationContext());
236 am.addAccount(MainApp.getAccountType(),
237 null,
238 null,
239 null,
240 this,
241 new AccountCreationCallback(),
242 null);
243 }
244
245
246 /**
247 * {@inheritDoc}
248 */
249 @Override
250 protected void onSaveInstanceState(Bundle outState) {
251 super.onSaveInstanceState(outState);
252 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
253 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
254 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
255 }
256
257
258 /**
259 * Getter for the main {@link OCFile} handled by the activity.
260 *
261 * @return Main {@link OCFile} handled by the activity.
262 */
263 public OCFile getFile() {
264 return mFile;
265 }
266
267
268 /**
269 * Setter for the main {@link OCFile} handled by the activity.
270 *
271 * @param file Main {@link OCFile} to be handled by the activity.
272 */
273 public void setFile(OCFile file) {
274 mFile = file;
275 }
276
277
278 /**
279 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
280 *
281 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
282 */
283 public Account getAccount() {
284 return mAccount;
285 }
286
287 /**
288 * @return Value of mFromNotification: True if the Activity is launched by a notification
289 */
290 public boolean fromNotification() {
291 return mFromNotification;
292 }
293
294 /**
295 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
296 */
297 protected boolean isRedirectingToSetupAccount() {
298 return mRedirectingToSetupAccount;
299 }
300
301
302 /**
303 * Helper class handling a callback from the {@link AccountManager} after the creation of
304 * a new ownCloud {@link Account} finished, successfully or not.
305 *
306 * At this moment, only called after the creation of the first account.
307 *
308 * @author David A. Velasco
309 */
310 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
311
312 @Override
313 public void run(AccountManagerFuture<Bundle> future) {
314 FileActivity.this.mRedirectingToSetupAccount = false;
315 boolean accountWasSet = false;
316 if (future != null) {
317 try {
318 Bundle result;
319 result = future.getResult();
320 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
321 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
322 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
323 setAccount(new Account(name, type), false);
324 accountWasSet = true;
325 }
326 } catch (OperationCanceledException e) {
327 Log_OC.d(TAG, "Account creation canceled");
328
329 } catch (Exception e) {
330 Log_OC.e(TAG, "Account creation finished in exception: ", e);
331 }
332
333 } else {
334 Log_OC.e(TAG, "Account creation callback with null bundle");
335 }
336 if (!accountWasSet) {
337 moveTaskToBack(true);
338 }
339 }
340
341 }
342
343
344 /**
345 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
346 *
347 * Child classes must grant that state depending on the {@link Account} is updated.
348 */
349 protected void onAccountSet(boolean stateWasRecovered) {
350 if (getAccount() != null) {
351 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
352
353 } else {
354 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
355 }
356 }
357
358
359 public FileDataStorageManager getStorageManager() {
360 return mStorageManager;
361 }
362
363
364 public OnRemoteOperationListener getRemoteOperationListener() {
365 return this;
366 }
367
368
369 public Handler getHandler() {
370 return mHandler;
371 }
372
373 public FileOperationsHelper getFileOperationsHelper() {
374 return mFileOperationsHelper;
375 }
376
377 /**
378 *
379 * @param operation Removal operation performed.
380 * @param result Result of the removal.
381 */
382 @Override
383 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
384 Log_OC.d(TAG, "Received result of operation in FileActivity - common behaviour for all the FileActivities ");
385 if (operation instanceof CreateShareOperation) {
386 onCreateShareOperationFinish((CreateShareOperation) operation, result);
387
388 } else if (operation instanceof UnshareLinkOperation) {
389 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
390
391 }
392 }
393
394 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
395 dismissLoadingDialog();
396 if (result.isSuccess()) {
397 updateFileFromDB();
398
399 Intent sendIntent = operation.getSendIntent();
400 startActivity(sendIntent);
401
402 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) { // Error --> SHARE_NOT_FOUND
403 Toast t = Toast.makeText(this, getString(R.string.share_link_file_no_exist), Toast.LENGTH_LONG);
404 t.show();
405 } else { // Generic error
406 // Show a Message, operation finished without success
407 Toast t = Toast.makeText(this, getString(R.string.share_link_file_error), Toast.LENGTH_LONG);
408 t.show();
409 }
410 }
411
412
413 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
414 dismissLoadingDialog();
415
416 if (result.isSuccess()){
417 updateFileFromDB();
418
419 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) { // Error --> SHARE_NOT_FOUND
420 Toast t = Toast.makeText(this, getString(R.string.unshare_link_file_no_exist), Toast.LENGTH_LONG);
421 t.show();
422 } else { // Generic error
423 // Show a Message, operation finished without success
424 Toast t = Toast.makeText(this, getString(R.string.unshare_link_file_error), Toast.LENGTH_LONG);
425 t.show();
426 }
427
428 }
429
430
431 private void updateFileFromDB(){
432 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
433 if (file != null) {
434 setFile(file);
435 }
436 }
437
438 /**
439 * Show loading dialog
440 */
441 public void showLoadingDialog() {
442 // Construct dialog
443 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
444 FragmentManager fm = getSupportFragmentManager();
445 FragmentTransaction ft = fm.beginTransaction();
446 loading.show(ft, DIALOG_WAIT_TAG);
447
448 }
449
450
451 /**
452 * Dismiss loading dialog
453 */
454 public void dismissLoadingDialog(){
455 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
456 if (frag != null) {
457 LoadingDialog loading = (LoadingDialog) frag;
458 loading.dismiss();
459 }
460 }
461
462
463 /**
464 * Implements callback methods for service binding. Passed as a parameter to {
465 */
466 private class OperationsServiceConnection implements ServiceConnection {
467
468 @Override
469 public void onServiceConnected(ComponentName component, IBinder service) {
470 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
471 Log_OC.d(TAG, "Operations service connected");
472 mOperationsServiceBinder = (OperationsServiceBinder) service;
473 mOperationsServiceBinder.addOperationListener(FileActivity.this, mHandler);
474 if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
475 dismissLoadingDialog();
476 }
477
478 } else {
479 return;
480 }
481 }
482
483
484 @Override
485 public void onServiceDisconnected(ComponentName component) {
486 if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
487 Log_OC.d(TAG, "Operations service disconnected");
488 mOperationsServiceBinder = null;
489 // TODO whatever could be waiting for the service is unbound
490 }
491 }
492 };
493
494 }