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