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