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