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