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