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