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