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