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