Merge remote-tracking branch 'origin/develop' into develop
[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.Intent;
27 import android.net.Uri;
28 import android.os.Bundle;
29 import android.webkit.MimeTypeMap;
30
31 import com.actionbarsherlock.app.SherlockFragmentActivity;
32 import com.owncloud.android.MainApp;
33 import com.owncloud.android.R;
34 import com.owncloud.android.authentication.AccountUtils;
35 import com.owncloud.android.datamodel.OCFile;
36
37 import com.owncloud.android.lib.accounts.OwnCloudAccount;
38 import com.owncloud.android.lib.network.webdav.WebdavUtils;
39
40 import com.owncloud.android.utils.Log_OC;
41
42
43 /**
44 * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud {@link Account}s .
45 *
46 * @author David A. Velasco
47 */
48 public abstract class FileActivity extends SherlockFragmentActivity {
49
50 public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
51 public static final String EXTRA_ACCOUNT = "com.owncloud.android.ui.activity.ACCOUNT";
52 public static final String EXTRA_WAITING_TO_PREVIEW = "com.owncloud.android.ui.activity.WAITING_TO_PREVIEW";
53 public static final String EXTRA_FROM_NOTIFICATION= "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
54
55 public static final String TAG = FileActivity.class.getSimpleName();
56
57
58 /** OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located. */
59 private Account mAccount;
60
61 /** Main {@link OCFile} handled by the activity.*/
62 private OCFile mFile;
63
64 /** Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account} */
65 private boolean mRedirectingToSetupAccount = false;
66
67 /** Flag to signal when the value of mAccount was set */
68 private boolean mAccountWasSet;
69
70 /** Flag to signal when the value of mAccount was restored from a saved state */
71 private boolean mAccountWasRestored;
72
73 /** Flag to signal if the activity is launched by a notification */
74 private boolean mFromNotification;
75
76
77
78 /**
79 * Loads the ownCloud {@link Account} and main {@link OCFile} to be handled by the instance of
80 * the {@link FileActivity}.
81 *
82 * Grants that a valid ownCloud {@link Account} is associated to the instance, or that the user
83 * is requested to create a new one.
84 */
85 @Override
86 protected void onCreate(Bundle savedInstanceState) {
87 super.onCreate(savedInstanceState);
88 Account account;
89 if(savedInstanceState != null) {
90 account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
91 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
92 mFromNotification = savedInstanceState.getBoolean(FileActivity.EXTRA_FROM_NOTIFICATION);
93 } else {
94 account = getIntent().getParcelableExtra(FileActivity.EXTRA_ACCOUNT);
95 mFile = getIntent().getParcelableExtra(FileActivity.EXTRA_FILE);
96 mFromNotification = getIntent().getBooleanExtra(FileActivity.EXTRA_FROM_NOTIFICATION, false);
97 }
98
99 setAccount(account, savedInstanceState != null);
100
101 }
102
103
104 /**
105 * Since ownCloud {@link Account}s can be managed from the system setting menu,
106 * the existence of the {@link Account} associated to the instance must be checked
107 * every time it is restarted.
108 */
109 @Override
110 protected void onRestart() {
111 super.onRestart();
112 boolean validAccount = (mAccount != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), mAccount.name));
113 if (!validAccount) {
114 swapToDefaultAccount();
115 }
116
117 }
118
119
120 @Override
121 protected void onStart() {
122 super.onStart();
123 if (mAccountWasSet) {
124 onAccountSet(mAccountWasRestored);
125 }
126 }
127
128
129 /**
130 * Sets and validates the ownCloud {@link Account} associated to the Activity.
131 *
132 * If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
133 *
134 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
135 *
136 * @param account New {@link Account} to set.
137 * @param savedAccount When 'true', account was retrieved from a saved instance state.
138 */
139 private void setAccount(Account account, boolean savedAccount) {
140 Account oldAccount = mAccount;
141 boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
142 if (validAccount) {
143 mAccount = account;
144 mAccountWasSet = true;
145 mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
146
147 } else {
148 swapToDefaultAccount();
149 }
150 }
151
152
153 /**
154 * Tries to swap the current ownCloud {@link Account} for other valid and existing.
155 *
156 * If no valid ownCloud {@link Account} exists, the the user is requested
157 * to create a new ownCloud {@link Account}.
158 *
159 * POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
160 *
161 * @return 'True' if the checked {@link Account} was valid.
162 */
163 private void swapToDefaultAccount() {
164 // default to the most recently used account
165 Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
166 if (newAccount == null) {
167 /// no account available: force account creation
168 createFirstAccount();
169 mRedirectingToSetupAccount = true;
170 mAccountWasSet = false;
171 mAccountWasRestored = false;
172
173 } else {
174 mAccountWasSet = true;
175 mAccountWasRestored = (newAccount.equals(mAccount));
176 mAccount = newAccount;
177 }
178 }
179
180
181 /**
182 * Launches the account creation activity. To use when no ownCloud account is available
183 */
184 private void createFirstAccount() {
185 AccountManager am = AccountManager.get(getApplicationContext());
186 am.addAccount(MainApp.getAccountType(),
187 null,
188 null,
189 null,
190 this,
191 new AccountCreationCallback(),
192 null);
193 }
194
195
196 /**
197 * {@inheritDoc}
198 */
199 @Override
200 protected void onSaveInstanceState(Bundle outState) {
201 super.onSaveInstanceState(outState);
202 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
203 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
204 outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
205 }
206
207
208 /**
209 * Getter for the main {@link OCFile} handled by the activity.
210 *
211 * @return Main {@link OCFile} handled by the activity.
212 */
213 public OCFile getFile() {
214 return mFile;
215 }
216
217
218 /**
219 * Setter for the main {@link OCFile} handled by the activity.
220 *
221 * @param file Main {@link OCFile} to be handled by the activity.
222 */
223 public void setFile(OCFile file) {
224 mFile = file;
225 }
226
227
228 /**
229 * Getter for the ownCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
230 *
231 * @return OwnCloud {@link Account} where the main {@link OCFile} handled by the activity is located.
232 */
233 public Account getAccount() {
234 return mAccount;
235 }
236
237 /**
238 * @return Value of mFromNotification: True if the Activity is launched by a notification
239 */
240 public boolean fromNotification() {
241 return mFromNotification;
242 }
243
244 /**
245 * @return 'True' when the Activity is finishing to enforce the setup of a new account.
246 */
247 protected boolean isRedirectingToSetupAccount() {
248 return mRedirectingToSetupAccount;
249 }
250
251
252 /**
253 * @return 'True' if the server supports the Share API
254 */
255 public boolean isSharedSupported() {
256 if (getAccount() != null) {
257 AccountManager accountManager = AccountManager.get(this);
258 return Boolean.parseBoolean(accountManager.getUserData(getAccount(), OwnCloudAccount.Constants.KEY_SUPPORTS_SHARE_API));
259 }
260 return false;
261 }
262
263 /**
264 * Helper class handling a callback from the {@link AccountManager} after the creation of
265 * a new ownCloud {@link Account} finished, successfully or not.
266 *
267 * At this moment, only called after the creation of the first account.
268 *
269 * @author David A. Velasco
270 */
271 public class AccountCreationCallback implements AccountManagerCallback<Bundle> {
272
273 @Override
274 public void run(AccountManagerFuture<Bundle> future) {
275 FileActivity.this.mRedirectingToSetupAccount = false;
276 boolean accountWasSet = false;
277 if (future != null) {
278 try {
279 Bundle result;
280 result = future.getResult();
281 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
282 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
283 if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
284 setAccount(new Account(name, type), false);
285 accountWasSet = true;
286 }
287 } catch (OperationCanceledException e) {
288 Log_OC.d(TAG, "Account creation canceled");
289
290 } catch (Exception e) {
291 Log_OC.e(TAG, "Account creation finished in exception: ", e);
292 }
293
294 } else {
295 Log_OC.e(TAG, "Account creation callback with null bundle");
296 }
297 if (!accountWasSet) {
298 moveTaskToBack(true);
299 }
300 }
301
302 }
303
304
305 /**
306 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
307 *
308 * Child classes must grant that state depending on the {@link Account} is updated.
309 */
310 protected abstract void onAccountSet(boolean stateWasRecovered);
311
312
313
314 public void openFile(OCFile file) {
315 if (file != null) {
316 String storagePath = file.getStoragePath();
317 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
318
319 Intent intentForSavedMimeType = new Intent(Intent.ACTION_VIEW);
320 intentForSavedMimeType.setDataAndType(Uri.parse("file://"+ encodedStoragePath), file.getMimetype());
321 intentForSavedMimeType.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
322
323 Intent intentForGuessedMimeType = null;
324 if (storagePath.lastIndexOf('.') >= 0) {
325 String guessedMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
326 if (guessedMimeType != null && !guessedMimeType.equals(file.getMimetype())) {
327 intentForGuessedMimeType = new Intent(Intent.ACTION_VIEW);
328 intentForGuessedMimeType.setDataAndType(Uri.parse("file://"+ encodedStoragePath), guessedMimeType);
329 intentForGuessedMimeType.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
330 }
331 }
332
333 Intent chooserIntent = null;
334 if (intentForGuessedMimeType != null) {
335 chooserIntent = Intent.createChooser(intentForGuessedMimeType, getString(R.string.actionbar_open_with));
336 } else {
337 chooserIntent = Intent.createChooser(intentForSavedMimeType, getString(R.string.actionbar_open_with));
338 }
339
340 startActivity(chooserIntent);
341
342 } else {
343 Log_OC.wtf(TAG, "Trying to open a NULL OCFile");
344 }
345 }
346
347 }