SettingsActivity.java 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author David A. Velasco
  6. * @author Chris Narkiewicz
  7. *
  8. * Copyright (C) 2011 Bartek Przybylski
  9. * Copyright (C) 2016 ownCloud Inc.
  10. * Copyright (C) 2016 Nextcloud
  11. * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
  12. *
  13. * This program is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License version 2,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. package com.owncloud.android.ui.activity;
  27. import android.app.Activity;
  28. import android.content.Intent;
  29. import android.content.SharedPreferences;
  30. import android.content.pm.PackageInfo;
  31. import android.content.pm.PackageManager.NameNotFoundException;
  32. import android.content.res.Configuration;
  33. import android.graphics.drawable.ColorDrawable;
  34. import android.net.Uri;
  35. import android.os.Build;
  36. import android.os.Bundle;
  37. import android.preference.ListPreference;
  38. import android.preference.Preference;
  39. import android.preference.PreferenceCategory;
  40. import android.preference.PreferenceManager;
  41. import android.preference.PreferenceScreen;
  42. import android.preference.SwitchPreference;
  43. import android.text.TextUtils;
  44. import android.view.Menu;
  45. import android.view.MenuInflater;
  46. import android.view.MenuItem;
  47. import android.view.View;
  48. import android.view.ViewGroup;
  49. import android.webkit.URLUtil;
  50. import com.nextcloud.client.account.User;
  51. import com.nextcloud.client.account.UserAccountManager;
  52. import com.nextcloud.client.di.Injectable;
  53. import com.nextcloud.client.etm.EtmActivity;
  54. import com.nextcloud.client.logger.ui.LogsActivity;
  55. import com.nextcloud.client.network.ClientFactory;
  56. import com.nextcloud.client.preferences.AppPreferences;
  57. import com.nextcloud.client.preferences.AppPreferencesImpl;
  58. import com.nextcloud.client.preferences.DarkMode;
  59. import com.owncloud.android.BuildConfig;
  60. import com.owncloud.android.MainApp;
  61. import com.owncloud.android.R;
  62. import com.owncloud.android.authentication.AuthenticatorActivity;
  63. import com.owncloud.android.authentication.PassCodeManager;
  64. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  65. import com.owncloud.android.datamodel.ExternalLinksProvider;
  66. import com.owncloud.android.datastorage.DataStorageProvider;
  67. import com.owncloud.android.datastorage.StoragePoint;
  68. import com.owncloud.android.lib.common.ExternalLink;
  69. import com.owncloud.android.lib.common.ExternalLinkType;
  70. import com.owncloud.android.lib.common.utils.Log_OC;
  71. import com.owncloud.android.providers.DocumentsStorageProvider;
  72. import com.owncloud.android.ui.asynctasks.LoadingVersionNumberTask;
  73. import com.owncloud.android.utils.DeviceCredentialUtils;
  74. import com.owncloud.android.utils.DisplayUtils;
  75. import com.owncloud.android.utils.EncryptionUtils;
  76. import com.owncloud.android.utils.MimeTypeUtil;
  77. import com.owncloud.android.utils.ThemeUtils;
  78. import java.util.ArrayList;
  79. import java.util.List;
  80. import javax.inject.Inject;
  81. import androidx.annotation.LayoutRes;
  82. import androidx.annotation.NonNull;
  83. import androidx.annotation.RequiresApi;
  84. import androidx.annotation.VisibleForTesting;
  85. import androidx.appcompat.app.ActionBar;
  86. import androidx.appcompat.app.AlertDialog;
  87. import androidx.appcompat.app.AppCompatDelegate;
  88. /**
  89. * An Activity that allows the user to change the application's settings.
  90. *
  91. * It proxies the necessary calls via {@link androidx.appcompat.app.AppCompatDelegate} to be used with AppCompat.
  92. */
  93. public class SettingsActivity extends ThemedPreferenceActivity
  94. implements StorageMigration.StorageMigrationProgressListener, LoadingVersionNumberTask.VersionDevInterface,
  95. Injectable {
  96. private static final String TAG = SettingsActivity.class.getSimpleName();
  97. public static final String PREFERENCE_LOCK= "lock";
  98. public static final String LOCK_NONE = "none";
  99. public static final String LOCK_PASSCODE = "passcode";
  100. public static final String LOCK_DEVICE_CREDENTIALS = "device_credentials";
  101. public final static String PREFERENCE_USE_FINGERPRINT = "use_fingerprint";
  102. public static final String PREFERENCE_SHOW_MEDIA_SCAN_NOTIFICATIONS = "show_media_scan_notifications";
  103. private static final int ACTION_REQUEST_PASSCODE = 5;
  104. private static final int ACTION_CONFIRM_PASSCODE = 6;
  105. private static final int ACTION_CONFIRM_DEVICE_CREDENTIALS = 7;
  106. private static final int ACTION_REQUEST_CODE_DAVDROID_SETUP = 10;
  107. private static final int TRUE_VALUE = 1;
  108. private static final String DAV_PATH = "/remote.php/dav";
  109. public static final String SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI = "SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI";
  110. private Uri serverBaseUri;
  111. private ListPreference lock;
  112. private SwitchPreference showHiddenFiles;
  113. private AppCompatDelegate delegate;
  114. private ListPreference prefStoragePath;
  115. private String storagePath;
  116. private String pendingLock;
  117. private User user;
  118. @Inject ArbitraryDataProvider arbitraryDataProvider;
  119. @Inject AppPreferences preferences;
  120. @Inject UserAccountManager accountManager;
  121. @Inject ClientFactory clientFactory;
  122. @SuppressWarnings("deprecation")
  123. @Override
  124. public void onCreate(Bundle savedInstanceState) {
  125. if (ThemeUtils.themingEnabled(this)) {
  126. setTheme(R.style.FallbackThemingTheme);
  127. }
  128. getDelegate().installViewFactory();
  129. getDelegate().onCreate(savedInstanceState);
  130. super.onCreate(savedInstanceState);
  131. addPreferencesFromResource(R.xml.preferences);
  132. setupActionBar();
  133. // Register context menu for list of preferences.
  134. registerForContextMenu(getListView());
  135. int accentColor = ThemeUtils.primaryAccentColor(this);
  136. String appVersion = getAppVersion();
  137. PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("preference_screen");
  138. user = accountManager.getUser();
  139. // retrieve user's base uri
  140. setupBaseUri();
  141. // General
  142. setupGeneralCategory(accentColor);
  143. // Synced folders
  144. setupAutoUploadCategory(accentColor, preferenceScreen);
  145. // Details
  146. setupDetailsCategory(accentColor, preferenceScreen);
  147. // More
  148. setupMoreCategory(accentColor);
  149. // About
  150. setupAboutCategory(accentColor, appVersion);
  151. // Dev
  152. setupDevCategory(accentColor, preferenceScreen);
  153. }
  154. private void setupDevCategory(int accentColor, PreferenceScreen preferenceScreen) {
  155. // Dev category
  156. PreferenceCategory preferenceCategoryDev = (PreferenceCategory) findPreference("dev_category");
  157. if (getResources().getBoolean(R.bool.is_beta)) {
  158. preferenceCategoryDev.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_dev),
  159. accentColor));
  160. /* Link to dev apks */
  161. Preference pDevLink = findPreference("dev_link");
  162. if (pDevLink != null) {
  163. if (getResources().getBoolean(R.bool.dev_version_direct_download_enabled)) {
  164. pDevLink.setOnPreferenceClickListener(preference -> {
  165. FileActivity.checkForNewDevVersion(this, getApplicationContext());
  166. return true;
  167. });
  168. } else {
  169. preferenceCategoryDev.removePreference(pDevLink);
  170. }
  171. }
  172. /* Link to dev changelog */
  173. Preference pChangelogLink = findPreference("changelog_link");
  174. if (pChangelogLink != null) {
  175. pChangelogLink.setOnPreferenceClickListener(preference -> {
  176. DisplayUtils.startLinkIntent(this, R.string.dev_changelog);
  177. return true;
  178. });
  179. }
  180. /* Engineering Test Mode */
  181. Preference pEtm = findPreference("etm");
  182. if (pEtm != null) {
  183. pEtm.setOnPreferenceClickListener(preference -> {
  184. EtmActivity.launch(this);
  185. return true;
  186. });
  187. }
  188. } else {
  189. preferenceScreen.removePreference(preferenceCategoryDev);
  190. }
  191. }
  192. private void setupAboutCategory(int accentColor, String appVersion) {
  193. PreferenceCategory preferenceCategoryAbout = (PreferenceCategory) findPreference("about");
  194. preferenceCategoryAbout.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_about),
  195. accentColor));
  196. /* About App */
  197. Preference pAboutApp = findPreference("about_app");
  198. if (pAboutApp != null) {
  199. pAboutApp.setTitle(String.format(getString(R.string.about_android), getString(R.string.app_name)));
  200. String buildNumber = getResources().getString(R.string.buildNumber);
  201. if (TextUtils.isEmpty(buildNumber)) {
  202. pAboutApp.setSummary(String.format(getString(R.string.about_version), appVersion));
  203. } else {
  204. pAboutApp.setSummary(String.format(getString(R.string.about_version_with_build),
  205. appVersion,
  206. buildNumber));
  207. }
  208. }
  209. // license
  210. boolean licenseEnabled = getResources().getBoolean(R.bool.license_enabled);
  211. Preference licensePreference = findPreference("license");
  212. if (licensePreference != null) {
  213. if (licenseEnabled) {
  214. licensePreference.setSummary(R.string.prefs_gpl_v2);
  215. licensePreference.setOnPreferenceClickListener(preference -> {
  216. DisplayUtils.startLinkIntent(this, R.string.license_url);
  217. return true;
  218. });
  219. } else {
  220. preferenceCategoryAbout.removePreference(licensePreference);
  221. }
  222. }
  223. // privacy
  224. boolean privacyEnabled = getResources().getBoolean(R.bool.privacy_enabled);
  225. Preference privacyPreference = findPreference("privacy");
  226. if (privacyPreference != null) {
  227. if (privacyEnabled && URLUtil.isValidUrl(getString(R.string.privacy_url))) {
  228. privacyPreference.setOnPreferenceClickListener(preference -> {
  229. try {
  230. Uri privacyUrl = Uri.parse(getString(R.string.privacy_url));
  231. String mimeType = MimeTypeUtil.getBestMimeTypeByFilename(privacyUrl.getLastPathSegment());
  232. Intent intent;
  233. if ("application/pdf".equals(mimeType)) {
  234. intent = new Intent(Intent.ACTION_VIEW, privacyUrl);
  235. DisplayUtils.startIntentIfAppAvailable(intent, this, R.string.no_pdf_app_available);
  236. } else {
  237. intent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
  238. intent.putExtra(ExternalSiteWebView.EXTRA_TITLE,
  239. getResources().getString(R.string.privacy));
  240. intent.putExtra(ExternalSiteWebView.EXTRA_URL, privacyUrl.toString());
  241. intent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, false);
  242. intent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, -1);
  243. }
  244. startActivity(intent);
  245. } catch (Exception e) {
  246. Log_OC.e(TAG, "Could not parse privacy url");
  247. preferenceCategoryAbout.removePreference(privacyPreference);
  248. }
  249. return true;
  250. });
  251. } else {
  252. preferenceCategoryAbout.removePreference(privacyPreference);
  253. }
  254. }
  255. // source code
  256. boolean sourcecodeEnabled = getResources().getBoolean(R.bool.sourcecode_enabled);
  257. Preference sourcecodePreference = findPreference("sourcecode");
  258. if (sourcecodePreference != null) {
  259. if (sourcecodeEnabled) {
  260. sourcecodePreference.setOnPreferenceClickListener(preference -> {
  261. DisplayUtils.startLinkIntent(this, R.string.sourcecode_url);
  262. return true;
  263. });
  264. } else {
  265. preferenceCategoryAbout.removePreference(sourcecodePreference);
  266. }
  267. }
  268. }
  269. private void setupMoreCategory(int accentColor) {
  270. PreferenceCategory preferenceCategoryMore = (PreferenceCategory) findPreference("more");
  271. preferenceCategoryMore.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_more),
  272. accentColor));
  273. setupCalendarPreference(preferenceCategoryMore);
  274. setupContactsBackupPreference(preferenceCategoryMore);
  275. setupE2EMnemonicPreference(preferenceCategoryMore);
  276. setupHelpPreference(preferenceCategoryMore);
  277. setupRecommendPreference(preferenceCategoryMore);
  278. setupLoggingPreference(preferenceCategoryMore);
  279. setupImprintPreference(preferenceCategoryMore);
  280. loadExternalSettingLinks(preferenceCategoryMore);
  281. }
  282. private void setupImprintPreference(PreferenceCategory preferenceCategoryMore) {
  283. boolean imprintEnabled = getResources().getBoolean(R.bool.imprint_enabled);
  284. Preference pImprint = findPreference("imprint");
  285. if (pImprint != null) {
  286. if (imprintEnabled) {
  287. pImprint.setOnPreferenceClickListener(preference -> {
  288. String imprintWeb = getString(R.string.url_imprint);
  289. if (!imprintWeb.isEmpty()) {
  290. Uri uriUrl = Uri.parse(imprintWeb);
  291. Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
  292. DisplayUtils.startIntentIfAppAvailable(intent, this, R.string.no_browser_available);
  293. }
  294. //ImprintDialog.newInstance(true).show(preference.get, "IMPRINT_DIALOG");
  295. return true;
  296. });
  297. } else {
  298. preferenceCategoryMore.removePreference(pImprint);
  299. }
  300. }
  301. }
  302. private void setupLoggingPreference(PreferenceCategory preferenceCategoryMore) {
  303. boolean loggerEnabled = getResources().getBoolean(R.bool.logger_enabled) || BuildConfig.DEBUG;
  304. Preference pLogger = findPreference("logger");
  305. if (pLogger != null) {
  306. if (loggerEnabled) {
  307. pLogger.setOnPreferenceClickListener(preference -> {
  308. Intent loggerIntent = new Intent(getApplicationContext(), LogsActivity.class);
  309. startActivity(loggerIntent);
  310. return true;
  311. });
  312. } else {
  313. preferenceCategoryMore.removePreference(pLogger);
  314. }
  315. }
  316. }
  317. private void setupRecommendPreference(PreferenceCategory preferenceCategoryMore) {
  318. boolean recommendEnabled = getResources().getBoolean(R.bool.recommend_enabled);
  319. Preference pRecommend = findPreference("recommend");
  320. if (pRecommend != null) {
  321. if (recommendEnabled) {
  322. pRecommend.setOnPreferenceClickListener(preference -> {
  323. Intent intent = new Intent(Intent.ACTION_SEND);
  324. intent.setType("text/plain");
  325. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  326. String appName = getString(R.string.app_name);
  327. String downloadUrlGooglePlayStore = getString(R.string.url_app_download);
  328. String downloadUrlFDroid = getString(R.string.fdroid_link);
  329. String downloadUrls = String.format(getString(R.string.recommend_urls),
  330. downloadUrlGooglePlayStore, downloadUrlFDroid);
  331. String recommendSubject = String.format(getString(R.string.recommend_subject), appName);
  332. String recommendText = String.format(getString(R.string.recommend_text),
  333. appName, downloadUrls);
  334. intent.putExtra(Intent.EXTRA_SUBJECT, recommendSubject);
  335. intent.putExtra(Intent.EXTRA_TEXT, recommendText);
  336. startActivity(intent);
  337. return true;
  338. });
  339. } else {
  340. preferenceCategoryMore.removePreference(pRecommend);
  341. }
  342. }
  343. }
  344. private void setupE2EMnemonicPreference(PreferenceCategory preferenceCategoryMore) {
  345. String mnemonic = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.MNEMONIC);
  346. Preference pMnemonic = findPreference("mnemonic");
  347. if (pMnemonic != null) {
  348. if (!mnemonic.isEmpty() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  349. if (DeviceCredentialUtils.areCredentialsAvailable(this)) {
  350. pMnemonic.setOnPreferenceClickListener(preference -> {
  351. Intent i = new Intent(MainApp.getAppContext(), RequestCredentialsActivity.class);
  352. i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
  353. startActivityForResult(i, PassCodeManager.PASSCODE_ACTIVITY);
  354. return true;
  355. });
  356. } else {
  357. pMnemonic.setEnabled(false);
  358. pMnemonic.setSummary(R.string.prefs_e2e_no_device_credentials);
  359. }
  360. } else {
  361. preferenceCategoryMore.removePreference(pMnemonic);
  362. }
  363. }
  364. }
  365. private void setupHelpPreference(PreferenceCategory preferenceCategoryMore) {
  366. boolean helpEnabled = getResources().getBoolean(R.bool.help_enabled);
  367. Preference pHelp = findPreference("help");
  368. if (pHelp != null) {
  369. if (helpEnabled) {
  370. pHelp.setOnPreferenceClickListener(preference -> {
  371. String helpWeb = getString(R.string.url_help);
  372. if (!helpWeb.isEmpty()) {
  373. Uri uriUrl = Uri.parse(helpWeb);
  374. Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
  375. DisplayUtils.startIntentIfAppAvailable(intent, this, R.string.no_browser_available);
  376. }
  377. return true;
  378. });
  379. } else {
  380. preferenceCategoryMore.removePreference(pHelp);
  381. }
  382. }
  383. }
  384. private void setupContactsBackupPreference(PreferenceCategory preferenceCategoryMore) {
  385. boolean contactsBackupEnabled = !getResources().getBoolean(R.bool.show_drawer_contacts_backup)
  386. && getResources().getBoolean(R.bool.contacts_backup);
  387. Preference pContactsBackup = findPreference("contacts");
  388. if (pContactsBackup != null) {
  389. if (contactsBackupEnabled) {
  390. pContactsBackup.setOnPreferenceClickListener(preference -> {
  391. ContactsPreferenceActivity.startActivityWithoutSidebar(this);
  392. return true;
  393. });
  394. } else {
  395. preferenceCategoryMore.removePreference(pContactsBackup);
  396. }
  397. }
  398. }
  399. private void setupCalendarPreference(PreferenceCategory preferenceCategoryMore) {
  400. boolean calendarContactsEnabled = getResources().getBoolean(R.bool.davdroid_integration_enabled);
  401. Preference pCalendarContacts = findPreference("calendar_contacts");
  402. if (pCalendarContacts != null) {
  403. if (calendarContactsEnabled) {
  404. final Activity activity = this;
  405. pCalendarContacts.setOnPreferenceClickListener(preference -> {
  406. try {
  407. launchDavDroidLogin();
  408. } catch (Throwable t) {
  409. Log_OC.e(TAG, "Base Uri for account could not be resolved to call DAVdroid!", t);
  410. DisplayUtils.showSnackMessage(
  411. activity,
  412. R.string.prefs_calendar_contacts_address_resolve_error
  413. );
  414. }
  415. return true;
  416. });
  417. } else {
  418. preferenceCategoryMore.removePreference(pCalendarContacts);
  419. }
  420. }
  421. }
  422. private void setupDetailsCategory(int accentColor, PreferenceScreen preferenceScreen) {
  423. PreferenceCategory preferenceCategoryDetails = (PreferenceCategory) findPreference("details");
  424. preferenceCategoryDetails.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_details),
  425. accentColor));
  426. boolean fPassCodeEnabled = getResources().getBoolean(R.bool.passcode_enabled);
  427. boolean fDeviceCredentialsEnabled = getResources().getBoolean(R.bool.device_credentials_enabled);
  428. boolean fShowHiddenFilesEnabled = getResources().getBoolean(R.bool.show_hidden_files_enabled);
  429. boolean fSyncedFolderLightEnabled = getResources().getBoolean(R.bool.syncedFolder_light);
  430. boolean fShowMediaScanNotifications = preferences.isShowMediaScanNotifications();
  431. setupLockPreference(preferenceCategoryDetails, fPassCodeEnabled, fDeviceCredentialsEnabled);
  432. setupHiddenFilesPreference(preferenceCategoryDetails, fShowHiddenFilesEnabled);
  433. setupShowMediaScanNotifications(preferenceCategoryDetails, fShowMediaScanNotifications);
  434. if (!fPassCodeEnabled && !fDeviceCredentialsEnabled && !fShowHiddenFilesEnabled && fSyncedFolderLightEnabled
  435. && fShowMediaScanNotifications) {
  436. preferenceScreen.removePreference(preferenceCategoryDetails);
  437. }
  438. }
  439. private void setupShowMediaScanNotifications(PreferenceCategory preferenceCategoryDetails,
  440. boolean fShowMediaScanNotifications) {
  441. SwitchPreference mShowMediaScanNotifications = (SwitchPreference) findPreference(PREFERENCE_SHOW_MEDIA_SCAN_NOTIFICATIONS);
  442. if (fShowMediaScanNotifications) {
  443. preferenceCategoryDetails.removePreference(mShowMediaScanNotifications);
  444. }
  445. }
  446. private void setupHiddenFilesPreference(PreferenceCategory preferenceCategoryDetails,
  447. boolean fShowHiddenFilesEnabled) {
  448. showHiddenFiles = (SwitchPreference) findPreference("show_hidden_files");
  449. if (fShowHiddenFilesEnabled) {
  450. showHiddenFiles.setOnPreferenceClickListener(preference -> {
  451. preferences.setShowHiddenFilesEnabled(showHiddenFiles.isChecked());
  452. return true;
  453. });
  454. } else {
  455. preferenceCategoryDetails.removePreference(showHiddenFiles);
  456. }
  457. }
  458. private void setupLockPreference(PreferenceCategory preferenceCategoryDetails,
  459. boolean passCodeEnabled,
  460. boolean deviceCredentialsEnabled) {
  461. lock = (ListPreference) findPreference(PREFERENCE_LOCK);
  462. if (lock != null && (passCodeEnabled || deviceCredentialsEnabled)) {
  463. ArrayList<String> lockEntries = new ArrayList<>(3);
  464. lockEntries.add(getString(R.string.prefs_lock_none));
  465. lockEntries.add(getString(R.string.prefs_lock_using_passcode));
  466. lockEntries.add(getString(R.string.prefs_lock_using_device_credentials));
  467. ArrayList<String> lockValues = new ArrayList<>(3);
  468. lockValues.add(LOCK_NONE);
  469. lockValues.add(LOCK_PASSCODE);
  470. lockValues.add(LOCK_DEVICE_CREDENTIALS);
  471. if (!passCodeEnabled) {
  472. lockEntries.remove(1);
  473. lockValues.remove(1);
  474. } else if (!deviceCredentialsEnabled || Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
  475. !DeviceCredentialUtils.areCredentialsAvailable(getApplicationContext())) {
  476. lockEntries.remove(2);
  477. lockValues.remove(2);
  478. }
  479. String[] lockEntriesArr = new String[lockEntries.size()];
  480. lockEntriesArr = lockEntries.toArray(lockEntriesArr);
  481. String[] lockValuesArr = new String[lockValues.size()];
  482. lockValuesArr = lockValues.toArray(lockValuesArr);
  483. lock.setEntries(lockEntriesArr);
  484. lock.setEntryValues(lockValuesArr);
  485. lock.setSummary(lock.getEntry());
  486. lock.setOnPreferenceChangeListener((preference, o) -> {
  487. pendingLock = LOCK_NONE;
  488. String oldValue = ((ListPreference) preference).getValue();
  489. String newValue = (String) o;
  490. if (!oldValue.equals(newValue)) {
  491. if (LOCK_NONE.equals(oldValue)) {
  492. enableLock(newValue);
  493. } else {
  494. pendingLock = newValue;
  495. disableLock(oldValue);
  496. }
  497. }
  498. return false;
  499. });
  500. } else {
  501. preferenceCategoryDetails.removePreference(lock);
  502. }
  503. }
  504. private void setupAutoUploadCategory(int accentColor, PreferenceScreen preferenceScreen) {
  505. PreferenceCategory preferenceCategorySyncedFolders =
  506. (PreferenceCategory) findPreference("synced_folders_category");
  507. preferenceCategorySyncedFolders.setTitle(ThemeUtils.getColoredTitle(getString(R.string.drawer_synced_folders),
  508. accentColor));
  509. if (!getResources().getBoolean(R.bool.syncedFolder_light)) {
  510. preferenceScreen.removePreference(preferenceCategorySyncedFolders);
  511. } else {
  512. // Upload on WiFi
  513. final ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  514. final SwitchPreference pUploadOnWifiCheckbox = (SwitchPreference) findPreference("synced_folder_on_wifi");
  515. pUploadOnWifiCheckbox.setChecked(
  516. arbitraryDataProvider.getBooleanValue(user.toPlatformAccount(), SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI));
  517. pUploadOnWifiCheckbox.setOnPreferenceClickListener(preference -> {
  518. arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI,
  519. String.valueOf(pUploadOnWifiCheckbox.isChecked()));
  520. return true;
  521. });
  522. Preference pSyncedFolder = findPreference("synced_folders_configure_folders");
  523. if (pSyncedFolder != null) {
  524. if (getResources().getBoolean(R.bool.syncedFolder_light)
  525. && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  526. pSyncedFolder.setOnPreferenceClickListener(preference -> {
  527. Intent syncedFoldersIntent = new Intent(getApplicationContext(), SyncedFoldersActivity.class);
  528. syncedFoldersIntent.putExtra(SyncedFoldersActivity.EXTRA_SHOW_SIDEBAR, false);
  529. startActivity(syncedFoldersIntent);
  530. return true;
  531. });
  532. } else {
  533. preferenceCategorySyncedFolders.removePreference(pSyncedFolder);
  534. }
  535. }
  536. }
  537. }
  538. private void enableLock(String lock) {
  539. pendingLock = LOCK_NONE;
  540. if (LOCK_PASSCODE.equals(lock)) {
  541. Intent i = new Intent(getApplicationContext(), PassCodeActivity.class);
  542. i.setAction(PassCodeActivity.ACTION_REQUEST_WITH_RESULT);
  543. startActivityForResult(i, ACTION_REQUEST_PASSCODE);
  544. } else if (LOCK_DEVICE_CREDENTIALS.equals(lock)){
  545. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
  546. !DeviceCredentialUtils.areCredentialsAvailable(getApplicationContext())) {
  547. DisplayUtils.showSnackMessage(this, R.string.prefs_lock_device_credentials_not_setup);
  548. } else {
  549. DisplayUtils.showSnackMessage(this, R.string.prefs_lock_device_credentials_enabled);
  550. changeLockSetting(LOCK_DEVICE_CREDENTIALS);
  551. }
  552. }
  553. }
  554. private void changeLockSetting(String value) {
  555. lock.setValue(value);
  556. lock.setSummary(lock.getEntry());
  557. DocumentsStorageProvider.notifyRootsChanged(this);
  558. }
  559. private void disableLock(String lock) {
  560. if (LOCK_PASSCODE.equals(lock)) {
  561. Intent i = new Intent(getApplicationContext(), PassCodeActivity.class);
  562. i.setAction(PassCodeActivity.ACTION_CHECK_WITH_RESULT);
  563. startActivityForResult(i, ACTION_CONFIRM_PASSCODE);
  564. } else if (LOCK_DEVICE_CREDENTIALS.equals(lock)) {
  565. Intent i = new Intent(getApplicationContext(), RequestCredentialsActivity.class);
  566. startActivityForResult(i, ACTION_CONFIRM_DEVICE_CREDENTIALS);
  567. }
  568. }
  569. private void setupGeneralCategory(int accentColor) {
  570. PreferenceCategory preferenceCategoryGeneral = (PreferenceCategory) findPreference("general");
  571. preferenceCategoryGeneral.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_general),
  572. accentColor));
  573. prefStoragePath = (ListPreference) findPreference(AppPreferencesImpl.STORAGE_PATH);
  574. if (prefStoragePath != null) {
  575. StoragePoint[] storageOptions = DataStorageProvider.getInstance().getAvailableStoragePoints();
  576. String[] entries = new String[storageOptions.length];
  577. String[] values = new String[storageOptions.length];
  578. for (int i = 0; i < storageOptions.length; ++i) {
  579. entries[i] = storageOptions[i].getDescription();
  580. values[i] = storageOptions[i].getPath();
  581. }
  582. prefStoragePath.setEntries(entries);
  583. prefStoragePath.setEntryValues(values);
  584. prefStoragePath.setOnPreferenceChangeListener((preference, newValue) -> {
  585. String newPath = (String) newValue;
  586. if (storagePath.equals(newPath)) {
  587. return true;
  588. }
  589. StorageMigration storageMigration = new StorageMigration(this, storagePath, newPath);
  590. storageMigration.setStorageMigrationProgressListener(this);
  591. storageMigration.migrate();
  592. return false;
  593. });
  594. }
  595. loadStoragePath();
  596. ListPreference themePref = (ListPreference) findPreference("darkMode");
  597. List<String> themeEntries = new ArrayList<>(3);
  598. themeEntries.add(getString(R.string.prefs_value_theme_light));
  599. themeEntries.add(getString(R.string.prefs_value_theme_dark));
  600. themeEntries.add(getString(R.string.prefs_value_theme_system));
  601. List<String> themeValues = new ArrayList<>(3);
  602. themeValues.add(DarkMode.LIGHT.name());
  603. themeValues.add(DarkMode.DARK.name());
  604. themeValues.add(DarkMode.SYSTEM.name());
  605. themePref.setEntries(themeEntries.toArray(new String[0]));
  606. themePref.setEntryValues(themeValues.toArray(new String[0]));
  607. if (TextUtils.isEmpty(themePref.getEntry())) {
  608. themePref.setValue(DarkMode.SYSTEM.name());
  609. themePref.setSummary(TextUtils.isEmpty(themePref.getEntry()) ? DarkMode.SYSTEM.name() : themePref.getEntry());
  610. }
  611. themePref.setOnPreferenceChangeListener((preference, newValue) -> {
  612. DarkMode mode = DarkMode.valueOf((String) newValue);
  613. preferences.setDarkThemeMode(mode);
  614. MainApp.setAppTheme(mode);
  615. return true;
  616. });
  617. }
  618. private String getAppVersion() {
  619. String temp;
  620. try {
  621. PackageInfo pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
  622. temp = pkg.versionName;
  623. } catch (NameNotFoundException e) {
  624. temp = "";
  625. Log_OC.e(TAG, "Error while showing about dialog", e);
  626. }
  627. return temp;
  628. }
  629. @Override
  630. public boolean onOptionsItemSelected(MenuItem item) {
  631. finish();
  632. return super.onOptionsItemSelected(item);
  633. }
  634. private void setupActionBar() {
  635. ActionBar actionBar = getDelegate().getSupportActionBar();
  636. if (actionBar != null) {
  637. ThemeUtils.setColoredTitle(actionBar, getString(R.string.actionbar_settings), this);
  638. ThemeUtils.colorStatusBar(this);
  639. actionBar.setBackgroundDrawable(new ColorDrawable(ThemeUtils.primaryAppbarColor(this)));
  640. actionBar.setDisplayHomeAsUpEnabled(true);
  641. ThemeUtils.tintBackButton(actionBar, this);
  642. }
  643. }
  644. private void launchDavDroidLogin() {
  645. Intent davDroidLoginIntent = new Intent();
  646. davDroidLoginIntent.setClassName("at.bitfire.davdroid", "at.bitfire.davdroid.ui.setup.LoginActivity");
  647. if (getPackageManager().resolveActivity(davDroidLoginIntent, 0) != null) {
  648. // arguments
  649. if (serverBaseUri != null) {
  650. davDroidLoginIntent.putExtra("url", serverBaseUri.toString() + DAV_PATH);
  651. davDroidLoginIntent.putExtra("loginFlow", TRUE_VALUE);
  652. davDroidLoginIntent.setData(Uri.parse(serverBaseUri.toString() + AuthenticatorActivity.WEB_LOGIN));
  653. davDroidLoginIntent.putExtra("davPath", DAV_PATH);
  654. }
  655. davDroidLoginIntent.putExtra("username", UserAccountManager.getUsername(user.toPlatformAccount()));
  656. startActivityForResult(davDroidLoginIntent, ACTION_REQUEST_CODE_DAVDROID_SETUP);
  657. } else {
  658. // DAVdroid not installed
  659. Intent installIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=at.bitfire.davdroid"));
  660. // launch market(s)
  661. if (installIntent.resolveActivity(getPackageManager()) != null) {
  662. startActivity(installIntent);
  663. } else {
  664. // no f-droid market app or Play store installed --> launch browser for f-droid url
  665. Intent downloadIntent = new Intent(Intent.ACTION_VIEW,
  666. Uri.parse("https://f-droid.org/repository/browse/?fdid=at.bitfire.davdroid"));
  667. DisplayUtils.startIntentIfAppAvailable(downloadIntent, this, R.string.no_browser_available);
  668. DisplayUtils.showSnackMessage(this, R.string.prefs_calendar_contacts_no_store_error);
  669. }
  670. }
  671. }
  672. private void setupBaseUri() {
  673. // retrieve and set user's base URI
  674. Thread t = new Thread(() -> {
  675. try {
  676. serverBaseUri = clientFactory.create(user).getBaseUri();
  677. } catch (Exception e) {
  678. Log_OC.e(TAG, "Error retrieving user's base URI", e);
  679. }
  680. });
  681. t.start();
  682. }
  683. @Override
  684. public boolean onCreateOptionsMenu(Menu menu) {
  685. super.onCreateOptionsMenu(menu);
  686. return true;
  687. }
  688. @Override
  689. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  690. super.onActivityResult(requestCode, resultCode, data);
  691. if (requestCode == ACTION_REQUEST_PASSCODE && resultCode == RESULT_OK) {
  692. String passcode = data.getStringExtra(PassCodeActivity.KEY_PASSCODE);
  693. if (passcode != null && passcode.length() == 4) {
  694. SharedPreferences.Editor appPrefs = PreferenceManager
  695. .getDefaultSharedPreferences(getApplicationContext()).edit();
  696. for (int i = 1; i <= 4; ++i) {
  697. appPrefs.putString(PassCodeActivity.PREFERENCE_PASSCODE_D + i, passcode.substring(i - 1, i));
  698. }
  699. appPrefs.apply();
  700. changeLockSetting(LOCK_PASSCODE);
  701. DisplayUtils.showSnackMessage(this, R.string.pass_code_stored);
  702. }
  703. } else if (requestCode == ACTION_CONFIRM_PASSCODE && resultCode == RESULT_OK) {
  704. if (data.getBooleanExtra(PassCodeActivity.KEY_CHECK_RESULT, false)) {
  705. changeLockSetting(LOCK_NONE);
  706. DisplayUtils.showSnackMessage(this, R.string.pass_code_removed);
  707. if (!LOCK_NONE.equals(pendingLock)) {
  708. enableLock(pendingLock);
  709. }
  710. }
  711. } else if (requestCode == ACTION_REQUEST_CODE_DAVDROID_SETUP && resultCode == RESULT_OK) {
  712. DisplayUtils.showSnackMessage(this, R.string.prefs_calendar_contacts_sync_setup_successful);
  713. } else if (requestCode == ACTION_CONFIRM_DEVICE_CREDENTIALS && resultCode == RESULT_OK &&
  714. Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
  715. data.getIntExtra(RequestCredentialsActivity.KEY_CHECK_RESULT,
  716. RequestCredentialsActivity.KEY_CHECK_RESULT_FALSE) ==
  717. RequestCredentialsActivity.KEY_CHECK_RESULT_TRUE) {
  718. changeLockSetting(LOCK_NONE);
  719. DisplayUtils.showSnackMessage(this, R.string.credentials_disabled);
  720. if (!LOCK_NONE.equals(pendingLock)) {
  721. enableLock(pendingLock);
  722. }
  723. } else if (requestCode == PassCodeManager.PASSCODE_ACTIVITY && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  724. handleMnemonicRequest(data);
  725. }
  726. }
  727. @RequiresApi(api = Build.VERSION_CODES.M)
  728. @VisibleForTesting
  729. public void handleMnemonicRequest(Intent data) {
  730. if (data == null) {
  731. DisplayUtils.showSnackMessage(this, "Error retrieving mnemonic!");
  732. } else {
  733. if (data.getIntExtra(RequestCredentialsActivity.KEY_CHECK_RESULT,
  734. RequestCredentialsActivity.KEY_CHECK_RESULT_FALSE) ==
  735. RequestCredentialsActivity.KEY_CHECK_RESULT_TRUE) {
  736. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  737. String mnemonic = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.MNEMONIC);
  738. int accentColor = ThemeUtils.primaryAccentColor(this);
  739. AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.FallbackTheming_Dialog);
  740. AlertDialog alertDialog = builder.setTitle(R.string.prefs_e2e_mnemonic)
  741. .setMessage(mnemonic)
  742. .setPositiveButton(R.string.common_ok, (dialog, which) -> dialog.dismiss())
  743. .create();
  744. alertDialog.show();
  745. alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(accentColor);
  746. }
  747. }
  748. }
  749. @Override
  750. @NonNull
  751. public MenuInflater getMenuInflater() {
  752. return getDelegate().getMenuInflater();
  753. }
  754. @Override
  755. public void setContentView(@LayoutRes int layoutResID) {
  756. getDelegate().setContentView(layoutResID);
  757. }
  758. @Override
  759. public void setContentView(View view) {
  760. getDelegate().setContentView(view);
  761. }
  762. @Override
  763. public void setContentView(View view, ViewGroup.LayoutParams params) {
  764. getDelegate().setContentView(view, params);
  765. }
  766. @Override
  767. public void addContentView(View view, ViewGroup.LayoutParams params) {
  768. getDelegate().addContentView(view, params);
  769. }
  770. @Override
  771. protected void onPostResume() {
  772. super.onPostResume();
  773. getDelegate().onPostResume();
  774. }
  775. @Override
  776. protected void onTitleChanged(CharSequence title, int color) {
  777. super.onTitleChanged(title, color);
  778. getDelegate().setTitle(title);
  779. }
  780. @Override
  781. public void onConfigurationChanged(Configuration newConfig) {
  782. super.onConfigurationChanged(newConfig);
  783. getDelegate().onConfigurationChanged(newConfig);
  784. }
  785. @Override
  786. protected void onPostCreate(Bundle savedInstanceState) {
  787. super.onPostCreate(savedInstanceState);
  788. getDelegate().onPostCreate(savedInstanceState);
  789. }
  790. @Override
  791. protected void onDestroy() {
  792. super.onDestroy();
  793. getDelegate().onDestroy();
  794. }
  795. @Override
  796. protected void onStop() {
  797. super.onStop();
  798. getDelegate().onStop();
  799. }
  800. public void invalidateOptionsMenu() {
  801. getDelegate().invalidateOptionsMenu();
  802. }
  803. private AppCompatDelegate getDelegate() {
  804. if (delegate == null) {
  805. delegate = AppCompatDelegate.create(this, null);
  806. }
  807. return delegate;
  808. }
  809. private void loadExternalSettingLinks(PreferenceCategory preferenceCategory) {
  810. if (getBaseContext().getResources().getBoolean(R.bool.show_external_links)) {
  811. ExternalLinksProvider externalLinksProvider = new ExternalLinksProvider(getContentResolver());
  812. for (final ExternalLink link : externalLinksProvider.getExternalLink(ExternalLinkType.SETTINGS)) {
  813. // only add if it does not exist, in case activity is re-used
  814. if (findPreference(link.id.toString()) == null) {
  815. Preference p = new Preference(this);
  816. p.setTitle(link.name);
  817. p.setKey(link.id.toString());
  818. p.setOnPreferenceClickListener(preference -> {
  819. Intent externalWebViewIntent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
  820. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE, link.name);
  821. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, link.url);
  822. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, false);
  823. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, link.id);
  824. startActivity(externalWebViewIntent);
  825. return true;
  826. });
  827. preferenceCategory.addPreference(p);
  828. }
  829. }
  830. }
  831. }
  832. /**
  833. * Save storage path
  834. */
  835. private void saveStoragePath(String newStoragePath) {
  836. SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  837. storagePath = newStoragePath;
  838. MainApp.setStoragePath(storagePath);
  839. SharedPreferences.Editor editor = appPrefs.edit();
  840. editor.putString(AppPreferencesImpl.STORAGE_PATH, storagePath);
  841. editor.apply();
  842. String storageDescription = DataStorageProvider.getInstance().getStorageDescriptionByPath(storagePath);
  843. prefStoragePath.setSummary(storageDescription);
  844. prefStoragePath.setValue(newStoragePath);
  845. }
  846. /**
  847. * Load storage path set on preferences
  848. */
  849. private void loadStoragePath() {
  850. SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  851. // Load storage path from shared preferences. Use private internal storage by default.
  852. storagePath = appPrefs.getString(AppPreferencesImpl.STORAGE_PATH,
  853. getApplicationContext().getFilesDir().getAbsolutePath());
  854. String storageDescription = DataStorageProvider.getInstance().getStorageDescriptionByPath(storagePath);
  855. prefStoragePath.setSummary(storageDescription);
  856. }
  857. @Override
  858. public void onStorageMigrationFinished(String storagePath, boolean succeed) {
  859. if (succeed) {
  860. saveStoragePath(storagePath);
  861. }
  862. }
  863. @Override
  864. public void onCancelMigration() {
  865. // Migration was canceled so we don't do anything
  866. }
  867. @Override
  868. public void returnVersion(Integer latestVersion) {
  869. FileActivity.showDevSnackbar(this, latestVersion, true, false);
  870. }
  871. }