9c11f0a87f11571c239bd8ed0cc3240f5bb7abae
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / Preferences.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 package com.owncloud.android.ui.activity;
19
20 import android.accounts.Account;
21 import android.accounts.AccountManager;
22 import android.accounts.AccountManagerCallback;
23 import android.accounts.AccountManagerFuture;
24 import android.content.Intent;
25 import android.content.SharedPreferences;
26 import android.content.pm.PackageInfo;
27 import android.content.pm.PackageManager.NameNotFoundException;
28 import android.net.Uri;
29 import android.os.Bundle;
30 import android.os.Handler;
31 import android.preference.CheckBoxPreference;
32 import android.preference.Preference;
33 import android.preference.Preference.OnPreferenceChangeListener;
34 import android.preference.Preference.OnPreferenceClickListener;
35 import android.preference.PreferenceCategory;
36 import android.preference.PreferenceManager;
37 import android.view.ContextMenu;
38 import android.view.ContextMenu.ContextMenuInfo;
39 import android.view.View;
40 import android.widget.AdapterView;
41 import android.widget.AdapterView.OnItemLongClickListener;
42 import android.widget.ListAdapter;
43 import android.widget.ListView;
44
45 import com.actionbarsherlock.app.ActionBar;
46 import com.actionbarsherlock.app.SherlockPreferenceActivity;
47 import com.actionbarsherlock.view.Menu;
48 import com.actionbarsherlock.view.MenuItem;
49 import com.owncloud.android.MainApp;
50 import com.owncloud.android.R;
51 import com.owncloud.android.authentication.AccountUtils;
52 import com.owncloud.android.authentication.AuthenticatorActivity;
53 import com.owncloud.android.datamodel.OCFile;
54 import com.owncloud.android.db.DbHandler;
55 import com.owncloud.android.lib.common.utils.Log_OC;
56 import com.owncloud.android.ui.LongClickableCheckBoxPreference;
57 import com.owncloud.android.utils.DisplayUtils;
58
59
60 /**
61 * An Activity that allows the user to change the application's settings.
62 *
63 * @author Bartek Przybylski
64 * @author David A. Velasco
65 */
66 public class Preferences extends SherlockPreferenceActivity implements AccountManagerCallback<Boolean> {
67
68 private static final String TAG = "OwnCloudPreferences";
69
70 private static final int ACTION_SELECT_UPLOAD_PATH = 1;
71 private static final int ACTION_SELECT_UPLOAD_VIDEO_PATH = 2;
72
73 private DbHandler mDbHandler;
74 private CheckBoxPreference pCode;
75 private Preference pAboutApp;
76
77 private PreferenceCategory mAccountsPrefCategory = null;
78 private final Handler mHandler = new Handler();
79 private String mAccountName;
80 private boolean mShowContextMenu = false;
81 private String mUploadPath;
82 private Preference mPrefInstantUploadPath;
83 private Preference mPrefInstantVideoUploadPath;
84 private String mUploadVideoPath;
85
86
87 @SuppressWarnings("deprecation")
88 @Override
89 public void onCreate(Bundle savedInstanceState) {
90 super.onCreate(savedInstanceState);
91 mDbHandler = new DbHandler(getBaseContext());
92 addPreferencesFromResource(R.xml.preferences);
93
94 ActionBar actionBar = getSherlock().getActionBar();
95 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
96 actionBar.setDisplayHomeAsUpEnabled(true);
97 actionBar.setTitle(R.string.actionbar_settings);
98
99 // Load the accounts category for adding the list of accounts
100 mAccountsPrefCategory = (PreferenceCategory) findPreference("accounts_category");
101
102 ListView listView = getListView();
103 listView.setOnItemLongClickListener(new OnItemLongClickListener() {
104 @Override
105 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
106 ListView listView = (ListView) parent;
107 ListAdapter listAdapter = listView.getAdapter();
108 Object obj = listAdapter.getItem(position);
109
110 if (obj != null && obj instanceof LongClickableCheckBoxPreference) {
111 mShowContextMenu = true;
112 mAccountName = ((LongClickableCheckBoxPreference) obj).getKey();
113
114 Preferences.this.openContextMenu(listView);
115
116 View.OnLongClickListener longListener = (View.OnLongClickListener) obj;
117 return longListener.onLongClick(view);
118 }
119 return false;
120 }
121 });
122
123 // Register context menu for list of preferences.
124 registerForContextMenu(getListView());
125
126 pCode = (CheckBoxPreference) findPreference("set_pincode");
127 if (pCode != null){
128 pCode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
129 @Override
130 public boolean onPreferenceChange(Preference preference, Object newValue) {
131 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
132 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "preferences");
133 i.putExtra(PinCodeActivity.EXTRA_NEW_STATE, newValue.toString());
134 startActivity(i);
135
136 return true;
137 }
138 });
139
140 }
141
142 PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference("more");
143
144 boolean helpEnabled = getResources().getBoolean(R.bool.help_enabled);
145 Preference pHelp = findPreference("help");
146 if (pHelp != null ){
147 if (helpEnabled) {
148 pHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
149 @Override
150 public boolean onPreferenceClick(Preference preference) {
151 String helpWeb =(String) getText(R.string.url_help);
152 if (helpWeb != null && helpWeb.length() > 0) {
153 Uri uriUrl = Uri.parse(helpWeb);
154 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
155 startActivity(intent);
156 }
157 return true;
158 }
159 });
160 } else {
161 preferenceCategory.removePreference(pHelp);
162 }
163
164 }
165
166
167 boolean recommendEnabled = getResources().getBoolean(R.bool.recommend_enabled);
168 Preference pRecommend = findPreference("recommend");
169 if (pRecommend != null){
170 if (recommendEnabled) {
171 pRecommend.setOnPreferenceClickListener(new OnPreferenceClickListener() {
172 @Override
173 public boolean onPreferenceClick(Preference preference) {
174
175 Intent intent = new Intent(Intent.ACTION_SENDTO);
176 intent.setType("text/plain");
177 intent.setData(Uri.parse(getString(R.string.mail_recommend)));
178 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
179
180 String appName = getString(R.string.app_name);
181 String downloadUrl = getString(R.string.url_app_download);
182 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(Preferences.this);
183 String username = currentAccount.name.substring(0, currentAccount.name.lastIndexOf('@'));
184
185 String recommendSubject = String.format(getString(R.string.recommend_subject), appName);
186 String recommendText = String.format(getString(R.string.recommend_text), appName, downloadUrl, username);
187
188 intent.putExtra(Intent.EXTRA_SUBJECT, recommendSubject);
189 intent.putExtra(Intent.EXTRA_TEXT, recommendText);
190 startActivity(intent);
191
192
193 return(true);
194
195 }
196 });
197 } else {
198 preferenceCategory.removePreference(pRecommend);
199 }
200
201 }
202
203 boolean feedbackEnabled = getResources().getBoolean(R.bool.feedback_enabled);
204 Preference pFeedback = findPreference("feedback");
205 if (pFeedback != null){
206 if (feedbackEnabled) {
207 pFeedback.setOnPreferenceClickListener(new OnPreferenceClickListener() {
208 @Override
209 public boolean onPreferenceClick(Preference preference) {
210 String feedbackMail =(String) getText(R.string.mail_feedback);
211 String feedback =(String) getText(R.string.prefs_feedback);
212 Intent intent = new Intent(Intent.ACTION_SENDTO);
213 intent.setType("text/plain");
214 intent.putExtra(Intent.EXTRA_SUBJECT, feedback);
215
216 intent.setData(Uri.parse(feedbackMail));
217 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
218 startActivity(intent);
219
220 return true;
221 }
222 });
223 } else {
224 preferenceCategory.removePreference(pFeedback);
225 }
226
227 }
228
229 boolean imprintEnabled = getResources().getBoolean(R.bool.imprint_enabled);
230 Preference pImprint = findPreference("imprint");
231 if (pImprint != null) {
232 if (imprintEnabled) {
233 pImprint.setOnPreferenceClickListener(new OnPreferenceClickListener() {
234 @Override
235 public boolean onPreferenceClick(Preference preference) {
236 String imprintWeb = (String) getText(R.string.url_imprint);
237 if (imprintWeb != null && imprintWeb.length() > 0) {
238 Uri uriUrl = Uri.parse(imprintWeb);
239 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
240 startActivity(intent);
241 }
242 //ImprintDialog.newInstance(true).show(preference.get, "IMPRINT_DIALOG");
243 return true;
244 }
245 });
246 } else {
247 preferenceCategory.removePreference(pImprint);
248 }
249 }
250
251 mPrefInstantUploadPath = findPreference("instant_upload_path");
252 if (mPrefInstantUploadPath != null){
253
254 mPrefInstantUploadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() {
255 @Override
256 public boolean onPreferenceClick(Preference preference) {
257 if (!mUploadPath.endsWith(OCFile.PATH_SEPARATOR)) {
258 mUploadPath += OCFile.PATH_SEPARATOR;
259 }
260 Intent intent = new Intent(Preferences.this, UploadPathActivity.class);
261 intent.putExtra(UploadPathActivity.KEY_INSTANT_UPLOAD_PATH, mUploadPath);
262 startActivityForResult(intent, ACTION_SELECT_UPLOAD_PATH);
263 return true;
264 }
265 });
266 }
267
268 mPrefInstantVideoUploadPath = findPreference("instant_video_upload_path");
269 if (mPrefInstantVideoUploadPath != null){
270
271 mPrefInstantVideoUploadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() {
272 @Override
273 public boolean onPreferenceClick(Preference preference) {
274 if (!mUploadVideoPath.endsWith(OCFile.PATH_SEPARATOR)) {
275 mUploadVideoPath += OCFile.PATH_SEPARATOR;
276 }
277 Intent intent = new Intent(Preferences.this, UploadPathActivity.class);
278 intent.putExtra(UploadPathActivity.KEY_INSTANT_UPLOAD_PATH, mUploadVideoPath);
279 startActivityForResult(intent, ACTION_SELECT_UPLOAD_VIDEO_PATH);
280 return true;
281 }
282 });
283 }
284
285 /* About App */
286 pAboutApp = (Preference) findPreference("about_app");
287 if (pAboutApp != null) {
288 pAboutApp.setTitle(String.format(getString(R.string.about_android), getString(R.string.app_name)));
289 PackageInfo pkg;
290 try {
291 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
292 pAboutApp.setSummary(String.format(getString(R.string.about_version), pkg.versionName));
293 } catch (NameNotFoundException e) {
294 Log_OC.e(TAG, "Error while showing about dialog", e);
295 }
296 }
297
298 loadInstantUploadPath();
299 loadInstantUploadVideoPath();
300
301 }
302
303 @Override
304 protected void onPause() {
305 super.onPause();
306 }
307
308 @Override
309 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
310
311 // Filter for only showing contextual menu when long press on the
312 // accounts
313 if (mShowContextMenu) {
314 getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
315 mShowContextMenu = false;
316 }
317 super.onCreateContextMenu(menu, v, menuInfo);
318 }
319
320 /**
321 * Called when the user clicked on an item into the context menu created at
322 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} for
323 * every ownCloud {@link Account} , containing 'secondary actions' for them.
324 *
325 * {@inheritDoc}
326 */
327 @Override
328 public boolean onContextItemSelected(android.view.MenuItem item) {
329 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
330 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
331 for (Account a : accounts) {
332 if (a.name.equals(mAccountName)) {
333 if (item.getItemId() == R.id.change_password) {
334
335 // Change account password
336 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
337 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, a);
338 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
339 AuthenticatorActivity.ACTION_UPDATE_TOKEN);
340 startActivity(updateAccountCredentials);
341
342 } else if (item.getItemId() == R.id.delete_account) {
343
344 // Remove account
345 am.removeAccount(a, this, mHandler);
346 }
347 }
348 }
349
350 return true;
351 }
352
353 @Override
354 public void run(AccountManagerFuture<Boolean> future) {
355 if (future.isDone()) {
356 Account a = AccountUtils.getCurrentOwnCloudAccount(this);
357 String accountName = "";
358 if (a == null) {
359 Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
360 if (accounts.length != 0)
361 accountName = accounts[0].name;
362 AccountUtils.setCurrentOwnCloudAccount(this, accountName);
363 }
364 addAccountsCheckboxPreferences();
365 }
366 }
367
368 @Override
369 protected void onResume() {
370 super.onResume();
371 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
372 boolean state = appPrefs.getBoolean("set_pincode", false);
373 pCode.setChecked(state);
374
375 // Populate the accounts category with the list of accounts
376 addAccountsCheckboxPreferences();
377 }
378
379 @Override
380 public boolean onCreateOptionsMenu(Menu menu) {
381 super.onCreateOptionsMenu(menu);
382 return true;
383 }
384
385 @Override
386 public boolean onMenuItemSelected(int featureId, MenuItem item) {
387 super.onMenuItemSelected(featureId, item);
388 Intent intent;
389
390 switch (item.getItemId()) {
391 case android.R.id.home:
392 intent = new Intent(getBaseContext(), FileDisplayActivity.class);
393 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
394 startActivity(intent);
395 break;
396 default:
397 Log_OC.w(TAG, "Unknown menu item triggered");
398 return false;
399 }
400 return true;
401 }
402
403 @Override
404 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
405 super.onActivityResult(requestCode, resultCode, data);
406
407 if (requestCode == ACTION_SELECT_UPLOAD_PATH && (resultCode == RESULT_OK ||
408 resultCode == UploadPathActivity.RESULT_OK_SET_UPLOAD_PATH)){
409
410 OCFile folderToUpload = (OCFile) data.getParcelableExtra(UploadPathActivity.EXTRA_CURRENT_FOLDER);
411
412 mUploadPath = folderToUpload.getRemotePath();
413
414 mUploadPath = DisplayUtils.getPathWithoutLastSlash(mUploadPath);
415
416 // Show the path on summary preference
417 mPrefInstantUploadPath.setSummary(mUploadPath);
418
419 saveInstantUploadPathOnPreferences();
420
421 } else if (requestCode == ACTION_SELECT_UPLOAD_VIDEO_PATH && (resultCode == RESULT_OK ||
422 resultCode == UploadPathActivity.RESULT_OK_SET_UPLOAD_PATH)){
423
424 OCFile folderToUploadVideo = (OCFile) data.getParcelableExtra(UploadPathActivity.EXTRA_CURRENT_FOLDER);
425
426 mUploadVideoPath = folderToUploadVideo.getRemotePath();
427
428 mUploadVideoPath = DisplayUtils.getPathWithoutLastSlash(mUploadVideoPath);
429
430 // Show the video path on summary preference
431 mPrefInstantVideoUploadPath.setSummary(mUploadVideoPath);
432
433 saveInstantUploadVideoPathOnPreferences();
434 }
435 }
436
437 @Override
438 protected void onDestroy() {
439 mDbHandler.close();
440 super.onDestroy();
441 }
442
443 /**
444 * Create the list of accounts that has been added into the app
445 */
446 @SuppressWarnings("deprecation")
447 private void addAccountsCheckboxPreferences() {
448
449 // Remove accounts in case list is refreshing for avoiding to have
450 // duplicate items
451 if (mAccountsPrefCategory.getPreferenceCount() > 0) {
452 mAccountsPrefCategory.removeAll();
453 }
454
455 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
456 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
457 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
458
459 if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
460 // Show create account screen if there isn't any account
461 am.addAccount(MainApp.getAccountType(), null, null, null, this,
462 null,
463 null);
464 }
465 else {
466
467 for (Account a : accounts) {
468 LongClickableCheckBoxPreference accountPreference = new LongClickableCheckBoxPreference(this);
469 accountPreference.setKey(a.name);
470 // Handle internationalized domain names
471 accountPreference.setTitle(DisplayUtils.convertIdn(a.name, false));
472 mAccountsPrefCategory.addPreference(accountPreference);
473
474 // Check the current account that is being used
475 if (a.name.equals(currentAccount.name)) {
476 accountPreference.setChecked(true);
477 } else {
478 accountPreference.setChecked(false);
479 }
480
481 accountPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
482 @Override
483 public boolean onPreferenceChange(Preference preference, Object newValue) {
484 String key = preference.getKey();
485 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
486 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
487 for (Account a : accounts) {
488 CheckBoxPreference p = (CheckBoxPreference) findPreference(a.name);
489 if (key.equals(a.name)) {
490 boolean accountChanged = !p.isChecked();
491 p.setChecked(true);
492 AccountUtils.setCurrentOwnCloudAccount(
493 getApplicationContext(),
494 a.name
495 );
496 if (accountChanged) {
497 // restart the main activity
498 Intent i = new Intent(
499 Preferences.this,
500 FileDisplayActivity.class
501 );
502 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
503 startActivity(i);
504 } else {
505 finish();
506 }
507 } else {
508 p.setChecked(false);
509 }
510 }
511 return (Boolean) newValue;
512 }
513 });
514
515 }
516
517 // Add Create Account preference at the end of account list if
518 // Multiaccount is enabled
519 if (getResources().getBoolean(R.bool.multiaccount_support)) {
520 createAddAccountPreference();
521 }
522
523 }
524 }
525
526 /**
527 * Create the preference for allow adding new accounts
528 */
529 private void createAddAccountPreference() {
530 Preference addAccountPref = new Preference(this);
531 addAccountPref.setKey("add_account");
532 addAccountPref.setTitle(getString(R.string.prefs_add_account));
533 mAccountsPrefCategory.addPreference(addAccountPref);
534
535 addAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
536 @Override
537 public boolean onPreferenceClick(Preference preference) {
538 AccountManager am = AccountManager.get(getApplicationContext());
539 am.addAccount(MainApp.getAccountType(), null, null, null, Preferences.this, null, null);
540 return true;
541 }
542 });
543
544 }
545
546 /**
547 * Load upload path set on preferences
548 */
549 private void loadInstantUploadPath() {
550 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
551 mUploadPath = appPrefs.getString("instant_upload_path", getString(R.string.instant_upload_path));
552 mPrefInstantUploadPath.setSummary(mUploadPath);
553 }
554
555 /**
556 * Save the "Instant Upload Path" on preferences
557 */
558 private void saveInstantUploadPathOnPreferences() {
559 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
560 SharedPreferences.Editor editor = appPrefs.edit();
561 editor.putString("instant_upload_path", mUploadPath);
562 editor.commit();
563 }
564
565 /**
566 * Load upload video path set on preferences
567 */
568 private void loadInstantUploadVideoPath() {
569 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
570 mUploadVideoPath = appPrefs.getString("instant_video_upload_path", getString(R.string.instant_upload_path));
571 mPrefInstantVideoUploadPath.setSummary(mUploadVideoPath);
572 }
573
574 /**
575 * Save the "Instant Video Upload Path" on preferences
576 */
577 private void saveInstantUploadVideoPathOnPreferences() {
578 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
579 SharedPreferences.Editor editor = appPrefs.edit();
580 editor.putString("instant_video_upload_path", mUploadVideoPath);
581 editor.commit();
582 }
583 }