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