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