SettingsController.java 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Andy Scherzinger
  5. * @author Mario Danic
  6. * @author Tim Krüger
  7. * Copyright (C) 2021 Tim Krüger <t@timkrueger.me>
  8. * Copyright (C) 2021 Andy Scherzinger <info@andy-scherzinger.de>
  9. * Copyright (C) 2017 Mario Danic (mario@lovelyhq.com)
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation, either version 3 of the License, or
  14. * at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. package com.nextcloud.talk.controllers;
  25. import android.animation.Animator;
  26. import android.animation.AnimatorListenerAdapter;
  27. import android.app.KeyguardManager;
  28. import android.content.Context;
  29. import android.content.DialogInterface;
  30. import android.content.Intent;
  31. import android.content.pm.PackageManager;
  32. import android.content.res.ColorStateList;
  33. import android.graphics.PorterDuff;
  34. import android.media.Ringtone;
  35. import android.media.RingtoneManager;
  36. import android.net.Uri;
  37. import android.os.Build;
  38. import android.os.Bundle;
  39. import android.provider.Settings;
  40. import android.security.KeyChain;
  41. import android.text.Editable;
  42. import android.text.InputType;
  43. import android.text.TextUtils;
  44. import android.text.TextWatcher;
  45. import android.util.Log;
  46. import android.view.LayoutInflater;
  47. import android.view.View;
  48. import android.view.ViewGroup;
  49. import android.view.WindowManager;
  50. import android.widget.Button;
  51. import android.widget.Checkable;
  52. import android.widget.EditText;
  53. import android.widget.ImageView;
  54. import android.widget.LinearLayout;
  55. import android.widget.RelativeLayout;
  56. import android.widget.TextView;
  57. import android.widget.Toast;
  58. import com.bluelinelabs.conductor.Controller;
  59. import com.bluelinelabs.conductor.RouterTransaction;
  60. import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
  61. import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler;
  62. import com.facebook.drawee.view.SimpleDraweeView;
  63. import com.google.android.material.card.MaterialCardView;
  64. import com.google.android.material.textfield.TextInputLayout;
  65. import com.nextcloud.talk.BuildConfig;
  66. import com.nextcloud.talk.R;
  67. import com.nextcloud.talk.api.NcApi;
  68. import com.nextcloud.talk.application.NextcloudTalkApplication;
  69. import com.nextcloud.talk.controllers.base.BaseController;
  70. import com.nextcloud.talk.jobs.AccountRemovalWorker;
  71. import com.nextcloud.talk.jobs.ContactAddressBookWorker;
  72. import com.nextcloud.talk.models.database.CapabilitiesUtil;
  73. import com.nextcloud.talk.models.database.UserEntity;
  74. import com.nextcloud.talk.models.json.generic.GenericOverall;
  75. import com.nextcloud.talk.models.json.userprofile.UserProfileOverall;
  76. import com.nextcloud.talk.utils.ApiUtils;
  77. import com.nextcloud.talk.utils.DisplayUtils;
  78. import com.nextcloud.talk.utils.LoggingUtils;
  79. import com.nextcloud.talk.utils.NotificationUtils;
  80. import com.nextcloud.talk.utils.SecurityUtils;
  81. import com.nextcloud.talk.utils.bundle.BundleKeys;
  82. import com.nextcloud.talk.utils.database.user.UserUtils;
  83. import com.nextcloud.talk.utils.preferences.AppPreferences;
  84. import com.nextcloud.talk.utils.preferences.MagicUserInputModule;
  85. import com.nextcloud.talk.utils.singletons.ApplicationWideMessageHolder;
  86. import com.yarolegovich.lovelydialog.LovelySaveStateHandler;
  87. import com.yarolegovich.lovelydialog.LovelyStandardDialog;
  88. import com.yarolegovich.mp.MaterialChoicePreference;
  89. import com.yarolegovich.mp.MaterialEditTextPreference;
  90. import com.yarolegovich.mp.MaterialPreferenceCategory;
  91. import com.yarolegovich.mp.MaterialPreferenceScreen;
  92. import com.yarolegovich.mp.MaterialStandardPreference;
  93. import com.yarolegovich.mp.MaterialSwitchPreference;
  94. import net.orange_box.storebox.listeners.OnPreferenceValueChangedListener;
  95. import java.net.URI;
  96. import java.net.URISyntaxException;
  97. import java.util.ArrayList;
  98. import java.util.Arrays;
  99. import java.util.List;
  100. import java.util.Locale;
  101. import java.util.Objects;
  102. import javax.inject.Inject;
  103. import androidx.annotation.NonNull;
  104. import androidx.annotation.Nullable;
  105. import androidx.appcompat.app.AlertDialog;
  106. import androidx.core.content.ContextCompat;
  107. import androidx.core.view.ViewCompat;
  108. import androidx.emoji.widget.EmojiTextView;
  109. import androidx.work.OneTimeWorkRequest;
  110. import androidx.work.WorkManager;
  111. import autodagger.AutoInjector;
  112. import butterknife.BindView;
  113. import butterknife.OnClick;
  114. import io.reactivex.Observer;
  115. import io.reactivex.android.schedulers.AndroidSchedulers;
  116. import io.reactivex.disposables.Disposable;
  117. import io.reactivex.schedulers.Schedulers;
  118. import okhttp3.MediaType;
  119. import okhttp3.RequestBody;
  120. @AutoInjector(NextcloudTalkApplication.class)
  121. public class SettingsController extends BaseController {
  122. public static final String TAG = "SettingsController";
  123. private static final int ID_REMOVE_ACCOUNT_WARNING_DIALOG = 0;
  124. @BindView(R.id.settings_screen)
  125. MaterialPreferenceScreen settingsScreen;
  126. @BindView(R.id.settings_proxy_port_edit)
  127. MaterialEditTextPreference proxyPortEditText;
  128. @BindView(R.id.settings_licence)
  129. MaterialStandardPreference licenceButton;
  130. @BindView(R.id.settings_privacy)
  131. MaterialStandardPreference privacyButton;
  132. @BindView(R.id.settings_source_code)
  133. MaterialStandardPreference sourceCodeButton;
  134. @BindView(R.id.settings_version)
  135. MaterialStandardPreference versionInfo;
  136. @BindView(R.id.avatarContainer)
  137. RelativeLayout avatarContainer;
  138. @BindView(R.id.avatar_image)
  139. SimpleDraweeView avatarImageView;
  140. @BindView(R.id.display_name_text)
  141. EmojiTextView displayNameTextView;
  142. @BindView(R.id.base_url_text)
  143. TextView baseUrlTextView;
  144. @BindView(R.id.server_age_warning_text_card)
  145. MaterialCardView serverAgeCardView;
  146. @BindView(R.id.server_age_warning_text)
  147. TextView serverAgeTextView;
  148. @BindView(R.id.server_age_warning_icon)
  149. ImageView serverAgeIcon;
  150. @BindView(R.id.settings_notifications_category)
  151. MaterialPreferenceCategory notificationsCategory;
  152. @BindView(R.id.settings_call_sound)
  153. MaterialStandardPreference settingsCallSound;
  154. @BindView(R.id.settings_message_sound)
  155. MaterialStandardPreference settingsMessageSound;
  156. @BindView(R.id.settings_remove_account)
  157. MaterialStandardPreference removeAccountButton;
  158. @BindView(R.id.settings_reauthorize)
  159. MaterialStandardPreference reauthorizeButton;
  160. @BindView(R.id.message_view)
  161. MaterialPreferenceCategory messageView;
  162. @BindView(R.id.settings_client_cert)
  163. MaterialStandardPreference certificateSetup;
  164. @BindView(R.id.settings_incognito_keyboard)
  165. MaterialSwitchPreference incognitoKeyboardSwitchPreference;
  166. @BindView(R.id.settings_screen_security)
  167. MaterialSwitchPreference screenSecuritySwitchPreference;
  168. @BindView(R.id.settings_screen_lock)
  169. MaterialSwitchPreference screenLockSwitchPreference;
  170. @BindView(R.id.settings_screen_lock_timeout)
  171. MaterialChoicePreference screenLockTimeoutChoicePreference;
  172. @BindView(R.id.settings_phone_book_integration)
  173. MaterialSwitchPreference phoneBookIntegrationPreference;
  174. @BindView(R.id.settings_read_privacy)
  175. MaterialSwitchPreference readPrivacyPreference;
  176. @BindView(R.id.message_text)
  177. TextView messageText;
  178. @Inject
  179. AppPreferences appPreferences;
  180. @Inject
  181. NcApi ncApi;
  182. @Inject
  183. UserUtils userUtils;
  184. @Inject
  185. Context context;
  186. private LovelySaveStateHandler saveStateHandler;
  187. private UserEntity currentUser;
  188. private String credentials;
  189. private OnPreferenceValueChangedListener<String> proxyTypeChangeListener;
  190. private OnPreferenceValueChangedListener<Boolean> proxyCredentialsChangeListener;
  191. private OnPreferenceValueChangedListener<Boolean> screenSecurityChangeListener;
  192. private OnPreferenceValueChangedListener<Boolean> screenLockChangeListener;
  193. private OnPreferenceValueChangedListener<String> screenLockTimeoutChangeListener;
  194. private OnPreferenceValueChangedListener<String> themeChangeListener;
  195. private OnPreferenceValueChangedListener<Boolean> readPrivacyChangeListener;
  196. private OnPreferenceValueChangedListener<Boolean> phoneBookIntegrationChangeListener;
  197. private Disposable profileQueryDisposable;
  198. private Disposable dbQueryDisposable;
  199. @NonNull
  200. @Override
  201. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  202. return inflater.inflate(R.layout.controller_settings, container, false);
  203. }
  204. private void getCurrentUser() {
  205. currentUser = userUtils.getCurrentUser();
  206. credentials = ApiUtils.getCredentials(currentUser.getUsername(), currentUser.getToken());
  207. }
  208. @Override
  209. protected void onViewBound(@NonNull View view) {
  210. super.onViewBound(view);
  211. setHasOptionsMenu(true);
  212. ViewCompat.setTransitionName(avatarImageView, "userAvatar.transitionTag");
  213. NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
  214. getCurrentUser();
  215. if (saveStateHandler == null) {
  216. saveStateHandler = new LovelySaveStateHandler();
  217. }
  218. appPreferences.registerProxyTypeListener(proxyTypeChangeListener = new ProxyTypeChangeListener());
  219. appPreferences.registerProxyCredentialsListener(proxyCredentialsChangeListener = new ProxyCredentialsChangeListener());
  220. appPreferences.registerScreenSecurityListener(screenSecurityChangeListener = new ScreenSecurityChangeListener());
  221. appPreferences.registerScreenLockListener(screenLockChangeListener = new ScreenLockListener());
  222. appPreferences.registerScreenLockTimeoutListener(screenLockTimeoutChangeListener = new ScreenLockTimeoutListener());
  223. appPreferences.registerThemeChangeListener(themeChangeListener = new ThemeChangeListener());
  224. appPreferences.registerPhoneBookIntegrationChangeListener(
  225. phoneBookIntegrationChangeListener = new PhoneBookIntegrationChangeListener(this));
  226. appPreferences.registerReadPrivacyChangeListener(readPrivacyChangeListener = new ReadPrivacyChangeListener());
  227. List<String> listWithIntFields = new ArrayList<>();
  228. listWithIntFields.add("proxy_port");
  229. settingsScreen.setUserInputModule(new MagicUserInputModule(getActivity(), listWithIntFields));
  230. settingsScreen.setVisibilityController(R.id.settings_proxy_use_credentials,
  231. Arrays.asList(R.id.settings_proxy_username_edit, R.id.settings_proxy_password_edit),
  232. true);
  233. if (!TextUtils.isEmpty(getResources().getString(R.string.nc_gpl3_url))) {
  234. licenceButton.addPreferenceClickListener(view1 -> {
  235. Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().
  236. getString(R.string.nc_gpl3_url)));
  237. startActivity(browserIntent);
  238. });
  239. } else {
  240. licenceButton.setVisibility(View.GONE);
  241. }
  242. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
  243. incognitoKeyboardSwitchPreference.setVisibility(View.GONE);
  244. }
  245. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
  246. screenLockSwitchPreference.setVisibility(View.GONE);
  247. screenLockTimeoutChoicePreference.setVisibility(View.GONE);
  248. } else {
  249. screenLockSwitchPreference.setSummary(String.format(Locale.getDefault(),
  250. getResources().getString(R.string.nc_settings_screen_lock_desc),
  251. getResources().getString(R.string.nc_app_product_name)));
  252. }
  253. if (!TextUtils.isEmpty(getResources().getString(R.string.nc_privacy_url))) {
  254. privacyButton.addPreferenceClickListener(view12 -> {
  255. Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().
  256. getString(R.string.nc_privacy_url)));
  257. startActivity(browserIntent);
  258. });
  259. } else {
  260. privacyButton.setVisibility(View.GONE);
  261. }
  262. if (!TextUtils.isEmpty(getResources().getString(R.string.nc_source_code_url))) {
  263. sourceCodeButton.addPreferenceClickListener(view13 -> {
  264. Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().
  265. getString(R.string.nc_source_code_url)));
  266. startActivity(browserIntent);
  267. });
  268. } else {
  269. sourceCodeButton.setVisibility(View.GONE);
  270. }
  271. versionInfo.setSummary("v" + BuildConfig.VERSION_NAME);
  272. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  273. settingsCallSound.setOnClickListener(v -> {
  274. Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
  275. intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID);
  276. intent.putExtra(Settings.EXTRA_CHANNEL_ID,
  277. NotificationUtils.INSTANCE.getNOTIFICATION_CHANNEL_CALLS_V4());
  278. startActivity(intent);
  279. });
  280. settingsMessageSound.setOnClickListener(v -> {
  281. Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
  282. intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID);
  283. intent.putExtra(Settings.EXTRA_CHANNEL_ID,
  284. NotificationUtils.INSTANCE.getNOTIFICATION_CHANNEL_MESSAGES_V3());
  285. startActivity(intent);
  286. });
  287. } else {
  288. settingsCallSound.setOnClickListener(v -> {
  289. Bundle bundle = new Bundle();
  290. bundle.putBoolean(BundleKeys.INSTANCE.getKEY_ARE_CALL_SOUNDS(), true);
  291. getRouter().pushController(RouterTransaction.with(new RingtoneSelectionController(bundle))
  292. .pushChangeHandler(new HorizontalChangeHandler())
  293. .popChangeHandler(new HorizontalChangeHandler()));
  294. });
  295. settingsMessageSound.setOnClickListener(v -> {
  296. Bundle bundle = new Bundle();
  297. bundle.putBoolean(BundleKeys.INSTANCE.getKEY_ARE_CALL_SOUNDS(), false);
  298. getRouter().pushController(RouterTransaction.with(new RingtoneSelectionController(bundle))
  299. .pushChangeHandler(new HorizontalChangeHandler())
  300. .popChangeHandler(new HorizontalChangeHandler()));
  301. });
  302. }
  303. if (CapabilitiesUtil.isPhoneBookIntegrationAvailable(userUtils.getCurrentUser())) {
  304. phoneBookIntegrationPreference.setVisibility(View.VISIBLE);
  305. } else {
  306. phoneBookIntegrationPreference.setVisibility(View.GONE);
  307. }
  308. String host = null;
  309. int port = -1;
  310. URI uri;
  311. try {
  312. uri = new URI(currentUser.getBaseUrl());
  313. host = uri.getHost();
  314. port = uri.getPort();
  315. } catch (URISyntaxException e) {
  316. Log.e(TAG, "Failed to create uri");
  317. }
  318. String finalHost = host;
  319. int finalPort = port;
  320. certificateSetup.addPreferenceClickListener(v -> KeyChain.choosePrivateKeyAlias(Objects.requireNonNull(getActivity()), alias -> {
  321. String finalAlias = alias;
  322. getActivity().runOnUiThread(() -> {
  323. if (finalAlias != null) {
  324. certificateSetup.setTitle(R.string.nc_client_cert_change);
  325. } else {
  326. certificateSetup.setTitle(R.string.nc_client_cert_setup);
  327. }
  328. });
  329. if (alias == null) {
  330. alias = "";
  331. }
  332. userUtils.createOrUpdateUser(null, null, null, null, null, null, null, currentUser.getId(),
  333. null, alias, null);
  334. }, new String[]{"RSA", "EC"}, null, finalHost, finalPort, currentUser.getClientCertificate
  335. ()));
  336. }
  337. private void showLovelyDialog(int dialogId, Bundle savedInstanceState) {
  338. if (dialogId == ID_REMOVE_ACCOUNT_WARNING_DIALOG) {
  339. showRemoveAccountWarning(savedInstanceState);
  340. }
  341. }
  342. @OnClick(R.id.settings_version)
  343. void sendLogs() {
  344. if (getResources().getBoolean(R.bool.nc_is_debug)) {
  345. LoggingUtils.INSTANCE.sendMailWithAttachment(context);
  346. }
  347. }
  348. @Override
  349. protected void onSaveViewState(@NonNull View view, @NonNull Bundle outState) {
  350. saveStateHandler.saveInstanceState(outState);
  351. super.onSaveViewState(view, outState);
  352. }
  353. @Override
  354. protected void onRestoreViewState(@NonNull View view, @NonNull Bundle savedViewState) {
  355. super.onRestoreViewState(view, savedViewState);
  356. if (LovelySaveStateHandler.wasDialogOnScreen(savedViewState)) {
  357. //Dialog won't be restarted automatically, so we need to call this method.
  358. //Each dialog knows how to restore its state
  359. showLovelyDialog(LovelySaveStateHandler.getSavedDialogId(savedViewState), savedViewState);
  360. }
  361. }
  362. private void showRemoveAccountWarning(Bundle savedInstanceState) {
  363. if (getActivity() != null) {
  364. new LovelyStandardDialog(getActivity(), LovelyStandardDialog.ButtonLayout.HORIZONTAL)
  365. .setTopColorRes(R.color.nc_darkRed)
  366. .setIcon(DisplayUtils.getTintedDrawable(getResources(),
  367. R.drawable.ic_delete_black_24dp, R.color.bg_default))
  368. .setPositiveButtonColor(context.getResources().getColor(R.color.nc_darkRed))
  369. .setTitle(R.string.nc_settings_remove_account)
  370. .setMessage(R.string.nc_settings_remove_confirmation)
  371. .setPositiveButton(R.string.nc_settings_remove, new View.OnClickListener() {
  372. @Override
  373. public void onClick(View v) {
  374. removeCurrentAccount();
  375. }
  376. })
  377. .setNegativeButton(R.string.nc_cancel, null)
  378. .setInstanceStateHandler(ID_REMOVE_ACCOUNT_WARNING_DIALOG, saveStateHandler)
  379. .setSavedInstanceState(savedInstanceState)
  380. .show();
  381. }
  382. }
  383. private void removeCurrentAccount() {
  384. boolean otherUserExists = userUtils.scheduleUserForDeletionWithId(currentUser.getId());
  385. OneTimeWorkRequest accountRemovalWork = new OneTimeWorkRequest.Builder(AccountRemovalWorker.class).build();
  386. WorkManager.getInstance().enqueue(accountRemovalWork);
  387. if (otherUserExists && getView() != null) {
  388. onViewBound(getView());
  389. onAttach(getView());
  390. } else if (!otherUserExists) {
  391. getRouter().setRoot(RouterTransaction.with(
  392. new ServerSelectionController())
  393. .pushChangeHandler(new VerticalChangeHandler())
  394. .popChangeHandler(new VerticalChangeHandler()));
  395. }
  396. }
  397. private String getRingtoneName(Context context, Uri ringtoneUri) {
  398. if (ringtoneUri == null) {
  399. return getResources().getString(R.string.nc_settings_no_ringtone);
  400. } else if (ringtoneUri.toString().equals(NotificationUtils.INSTANCE.getDEFAULT_CALL_RINGTONE_URI()) ||
  401. ringtoneUri.toString().equals(NotificationUtils.INSTANCE.getDEFAULT_MESSAGE_RINGTONE_URI())) {
  402. return getResources().getString(R.string.nc_settings_default_ringtone);
  403. } else {
  404. Ringtone r = RingtoneManager.getRingtone(context, ringtoneUri);
  405. return r.getTitle(context);
  406. }
  407. }
  408. @Override
  409. protected void onAttach(@NonNull View view) {
  410. super.onAttach(view);
  411. if (getActionBar() != null) {
  412. getActionBar().show();
  413. }
  414. dispose(null);
  415. getCurrentUser();
  416. if (!TextUtils.isEmpty(currentUser.getClientCertificate())) {
  417. certificateSetup.setTitle(R.string.nc_client_cert_change);
  418. } else {
  419. certificateSetup.setTitle(R.string.nc_client_cert_setup);
  420. }
  421. ((Checkable) screenSecuritySwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getIsScreenSecured());
  422. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  423. ((Checkable) incognitoKeyboardSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getIsKeyboardIncognito());
  424. }
  425. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  426. ((Checkable) incognitoKeyboardSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getIsKeyboardIncognito());
  427. }
  428. if (CapabilitiesUtil.isReadStatusAvailable(userUtils.getCurrentUser())) {
  429. ((Checkable) readPrivacyPreference.findViewById(R.id.mp_checkable)).setChecked(!CapabilitiesUtil.isReadStatusPrivate(currentUser));
  430. } else {
  431. readPrivacyPreference.setVisibility(View.GONE);
  432. }
  433. ((Checkable) phoneBookIntegrationPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.isPhoneBookIntegrationEnabled());
  434. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  435. KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
  436. if (keyguardManager.isKeyguardSecure()) {
  437. screenLockSwitchPreference.setEnabled(true);
  438. screenLockTimeoutChoicePreference.setEnabled(true);
  439. ((Checkable) screenLockSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.getIsScreenLocked());
  440. screenLockTimeoutChoicePreference.setEnabled(appPreferences.getIsScreenLocked());
  441. if (appPreferences.getIsScreenLocked()) {
  442. screenLockTimeoutChoicePreference.setAlpha(1.0f);
  443. } else {
  444. screenLockTimeoutChoicePreference.setAlpha(0.38f);
  445. }
  446. screenLockSwitchPreference.setAlpha(1.0f);
  447. } else {
  448. screenLockSwitchPreference.setEnabled(false);
  449. screenLockTimeoutChoicePreference.setEnabled(false);
  450. appPreferences.removeScreenLock();
  451. appPreferences.removeScreenLockTimeout();
  452. ((Checkable) screenLockSwitchPreference.findViewById(R.id.mp_checkable)).setChecked(false);
  453. screenLockSwitchPreference.setAlpha(0.38f);
  454. screenLockTimeoutChoicePreference.setAlpha(0.38f);
  455. }
  456. }
  457. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  458. notificationsCategory.setTitle(getResources().getString(R.string.nc_settings_notification_sounds_post_oreo));
  459. }
  460. Uri callRingtoneUri = NotificationUtils.INSTANCE.getCallRingtoneUri(view.getContext(), appPreferences);
  461. settingsCallSound.setSummary(getRingtoneName(view.getContext(), callRingtoneUri));
  462. Uri messageRingtoneUri = NotificationUtils.INSTANCE.getMessageRingtoneUri(view.getContext(), appPreferences);
  463. settingsMessageSound.setSummary(getRingtoneName(view.getContext(), messageRingtoneUri));
  464. if ("No proxy".equals(appPreferences.getProxyType()) || appPreferences.getProxyType() == null) {
  465. hideProxySettings();
  466. } else {
  467. showProxySettings();
  468. }
  469. if (appPreferences.getProxyCredentials()) {
  470. showProxyCredentials();
  471. } else {
  472. hideProxyCredentials();
  473. }
  474. if (currentUser != null) {
  475. baseUrlTextView.setText(Uri.parse(currentUser.getBaseUrl()).getHost());
  476. if (CapabilitiesUtil.isServerEOL(currentUser)) {
  477. serverAgeTextView.setTextColor(ContextCompat.getColor(context, R.color.nc_darkRed));
  478. serverAgeTextView.setText(R.string.nc_settings_server_eol);
  479. serverAgeIcon.setColorFilter(ContextCompat.getColor(context, R.color.nc_darkRed),
  480. PorterDuff.Mode.SRC_IN);
  481. } else if (CapabilitiesUtil.isServerAlmostEOL(currentUser)) {
  482. serverAgeTextView.setTextColor(ContextCompat.getColor(context, R.color.nc_darkYellow));
  483. serverAgeTextView.setText(R.string.nc_settings_server_almost_eol);
  484. serverAgeIcon.setColorFilter(ContextCompat.getColor(context, R.color.nc_darkYellow),
  485. PorterDuff.Mode.SRC_IN);
  486. } else {
  487. serverAgeCardView.setVisibility(View.GONE);
  488. }
  489. reauthorizeButton.addPreferenceClickListener(view14 -> {
  490. getRouter().pushController(RouterTransaction.with(
  491. new WebViewLoginController(currentUser.getBaseUrl(), true))
  492. .pushChangeHandler(new VerticalChangeHandler())
  493. .popChangeHandler(new VerticalChangeHandler()));
  494. });
  495. if (currentUser.getDisplayName() != null) {
  496. displayNameTextView.setText(currentUser.getDisplayName());
  497. }
  498. DisplayUtils.loadAvatarImage(currentUser, avatarImageView, false);
  499. profileQueryDisposable = ncApi.getUserProfile(credentials,
  500. ApiUtils.getUrlForUserProfile(currentUser.getBaseUrl()))
  501. .subscribeOn(Schedulers.io())
  502. .observeOn(AndroidSchedulers.mainThread())
  503. .subscribe(userProfileOverall -> {
  504. String displayName = null;
  505. if (!TextUtils.isEmpty(userProfileOverall.getOcs().getData()
  506. .getDisplayName())) {
  507. displayName = userProfileOverall.getOcs().getData()
  508. .getDisplayName();
  509. } else if (!TextUtils.isEmpty(userProfileOverall.getOcs().getData()
  510. .getDisplayNameAlt())) {
  511. displayName = userProfileOverall.getOcs().getData()
  512. .getDisplayNameAlt();
  513. }
  514. if ((!TextUtils.isEmpty(displayName) && !displayName.equals(currentUser.getDisplayName()))) {
  515. dbQueryDisposable = userUtils.createOrUpdateUser(null,
  516. null,
  517. null, displayName, null, null,
  518. null, currentUser.getId(), null, null, null)
  519. .subscribeOn(Schedulers.io())
  520. .observeOn(AndroidSchedulers.mainThread())
  521. .subscribe(userEntityResult -> {
  522. displayNameTextView.setText(userEntityResult.getDisplayName());
  523. },
  524. throwable -> {
  525. dispose(dbQueryDisposable);
  526. }, () -> dispose(dbQueryDisposable));
  527. }
  528. }, throwable -> {
  529. dispose(profileQueryDisposable);
  530. }, () -> dispose(profileQueryDisposable));
  531. removeAccountButton.addPreferenceClickListener(view1 -> {
  532. showLovelyDialog(ID_REMOVE_ACCOUNT_WARNING_DIALOG, null);
  533. });
  534. }
  535. if (ApplicationWideMessageHolder.getInstance().getMessageType() != null) {
  536. switch (ApplicationWideMessageHolder.getInstance().getMessageType()) {
  537. case ACCOUNT_UPDATED_NOT_ADDED:
  538. messageText.setTextColor(getResources().getColor(R.color.colorPrimary));
  539. messageText.setText(getResources().getString(R.string.nc_settings_account_updated));
  540. messageView.setVisibility(View.VISIBLE);
  541. break;
  542. case SERVER_WITHOUT_TALK:
  543. messageText.setTextColor(getResources().getColor(R.color.nc_darkRed));
  544. messageText.setText(getResources().getString(R.string.nc_settings_wrong_account));
  545. messageView.setVisibility(View.VISIBLE);
  546. case ACCOUNT_WAS_IMPORTED:
  547. messageText.setTextColor(getResources().getColor(R.color.colorPrimary));
  548. messageText.setText(getResources().getString(R.string.nc_Server_account_imported));
  549. messageView.setVisibility(View.VISIBLE);
  550. break;
  551. case FAILED_TO_IMPORT_ACCOUNT:
  552. messageText.setTextColor(getResources().getColor(R.color.nc_darkRed));
  553. messageText.setText(getResources().getString(R.string.nc_server_failed_to_import_account));
  554. messageView.setVisibility(View.VISIBLE);
  555. break;
  556. default:
  557. messageView.setVisibility(View.GONE);
  558. break;
  559. }
  560. ApplicationWideMessageHolder.getInstance().setMessageType(null);
  561. messageView.animate()
  562. .translationY(0)
  563. .alpha(0.0f)
  564. .setDuration(2500)
  565. .setStartDelay(5000)
  566. .setListener(new AnimatorListenerAdapter() {
  567. @Override
  568. public void onAnimationEnd(Animator animation) {
  569. super.onAnimationEnd(animation);
  570. if (messageView != null) {
  571. messageView.setVisibility(View.GONE);
  572. }
  573. }
  574. });
  575. } else {
  576. if (messageView != null) {
  577. messageView.setVisibility(View.GONE);
  578. }
  579. }
  580. avatarContainer.setOnClickListener(v ->
  581. getRouter()
  582. .pushController((RouterTransaction.with(new ProfileController())
  583. .pushChangeHandler(new HorizontalChangeHandler())
  584. .popChangeHandler(new HorizontalChangeHandler()))));
  585. }
  586. @Override
  587. public void onDestroy() {
  588. if (appPreferences != null) {
  589. appPreferences.unregisterProxyTypeListener(proxyTypeChangeListener);
  590. appPreferences.unregisterProxyCredentialsListener(proxyCredentialsChangeListener);
  591. appPreferences.unregisterScreenSecurityListener(screenSecurityChangeListener);
  592. appPreferences.unregisterScreenLockListener(screenLockChangeListener);
  593. appPreferences.unregisterScreenLockTimeoutListener(screenLockTimeoutChangeListener);
  594. appPreferences.unregisterThemeChangeListener(themeChangeListener);
  595. appPreferences.unregisterReadPrivacyChangeListener(readPrivacyChangeListener);
  596. appPreferences.unregisterPhoneBookIntegrationChangeListener(phoneBookIntegrationChangeListener);
  597. }
  598. super.onDestroy();
  599. }
  600. private void hideProxySettings() {
  601. appPreferences.removeProxyHost();
  602. appPreferences.removeProxyPort();
  603. appPreferences.removeProxyCredentials();
  604. appPreferences.removeProxyUsername();
  605. appPreferences.removeProxyPassword();
  606. settingsScreen.findViewById(R.id.settings_proxy_host_edit).setVisibility(View.GONE);
  607. settingsScreen.findViewById(R.id.settings_proxy_port_edit).setVisibility(View.GONE);
  608. settingsScreen.findViewById(R.id.settings_proxy_use_credentials).setVisibility(View.GONE);
  609. settingsScreen.findViewById(R.id.settings_proxy_username_edit).setVisibility(View.GONE);
  610. settingsScreen.findViewById(R.id.settings_proxy_password_edit).setVisibility(View.GONE);
  611. }
  612. private void showProxySettings() {
  613. settingsScreen.findViewById(R.id.settings_proxy_host_edit).setVisibility(View.VISIBLE);
  614. settingsScreen.findViewById(R.id.settings_proxy_port_edit).setVisibility(View.VISIBLE);
  615. settingsScreen.findViewById(R.id.settings_proxy_use_credentials).setVisibility(View.VISIBLE);
  616. }
  617. private void showProxyCredentials() {
  618. settingsScreen.findViewById(R.id.settings_proxy_username_edit).setVisibility(View.VISIBLE);
  619. settingsScreen.findViewById(R.id.settings_proxy_password_edit).setVisibility(View.VISIBLE);
  620. }
  621. private void hideProxyCredentials() {
  622. appPreferences.removeProxyUsername();
  623. appPreferences.removeProxyPassword();
  624. settingsScreen.findViewById(R.id.settings_proxy_username_edit).setVisibility(View.GONE);
  625. settingsScreen.findViewById(R.id.settings_proxy_password_edit).setVisibility(View.GONE);
  626. }
  627. private void dispose(@Nullable Disposable disposable) {
  628. if (disposable != null && !disposable.isDisposed()) {
  629. disposable.dispose();
  630. } else if (disposable == null) {
  631. if (profileQueryDisposable != null && !profileQueryDisposable.isDisposed()) {
  632. profileQueryDisposable.dispose();
  633. profileQueryDisposable = null;
  634. } else if (profileQueryDisposable != null) {
  635. profileQueryDisposable = null;
  636. }
  637. if (dbQueryDisposable != null && !dbQueryDisposable.isDisposed()) {
  638. dbQueryDisposable.dispose();
  639. dbQueryDisposable = null;
  640. } else if (dbQueryDisposable != null) {
  641. dbQueryDisposable = null;
  642. }
  643. }
  644. }
  645. @Override
  646. protected String getTitle() {
  647. return getResources().getString(R.string.nc_settings);
  648. }
  649. @Override
  650. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  651. if (requestCode == ContactAddressBookWorker.REQUEST_PERMISSION &&
  652. grantResults.length > 0 &&
  653. grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  654. WorkManager
  655. .getInstance()
  656. .enqueue(new OneTimeWorkRequest.Builder(ContactAddressBookWorker.class).build());
  657. checkForPhoneNumber();
  658. } else {
  659. appPreferences.setPhoneBookIntegration(false);
  660. ((Checkable) phoneBookIntegrationPreference.findViewById(R.id.mp_checkable)).setChecked(appPreferences.isPhoneBookIntegrationEnabled());
  661. Toast.makeText(context, context.getResources().getString(
  662. R.string.no_phone_book_integration_due_to_permissions),
  663. Toast.LENGTH_LONG).show();
  664. }
  665. }
  666. private class ScreenLockTimeoutListener implements OnPreferenceValueChangedListener<String> {
  667. @Override
  668. public void onChanged(String newValue) {
  669. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  670. SecurityUtils.createKey(appPreferences.getScreenLockTimeout());
  671. }
  672. }
  673. }
  674. private class ScreenLockListener implements OnPreferenceValueChangedListener<Boolean> {
  675. @Override
  676. public void onChanged(Boolean newValue) {
  677. screenLockTimeoutChoicePreference.setEnabled(newValue);
  678. if (newValue) {
  679. screenLockTimeoutChoicePreference.setAlpha(1.0f);
  680. } else {
  681. screenLockTimeoutChoicePreference.setAlpha(0.38f);
  682. }
  683. }
  684. }
  685. private class ScreenSecurityChangeListener implements OnPreferenceValueChangedListener<Boolean> {
  686. @Override
  687. public void onChanged(Boolean newValue) {
  688. if (newValue) {
  689. if (getActivity() != null) {
  690. getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
  691. }
  692. } else {
  693. if (getActivity() != null) {
  694. getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
  695. }
  696. }
  697. }
  698. }
  699. private class ProxyCredentialsChangeListener implements OnPreferenceValueChangedListener<Boolean> {
  700. @Override
  701. public void onChanged(Boolean newValue) {
  702. if (newValue) {
  703. showProxyCredentials();
  704. } else {
  705. hideProxyCredentials();
  706. }
  707. }
  708. }
  709. private class ProxyTypeChangeListener implements OnPreferenceValueChangedListener<String> {
  710. @Override
  711. public void onChanged(String newValue) {
  712. if ("No proxy".equals(newValue)) {
  713. hideProxySettings();
  714. } else {
  715. switch (newValue) {
  716. case "HTTP":
  717. if (proxyPortEditText != null) {
  718. proxyPortEditText.setValue("3128");
  719. }
  720. break;
  721. case "DIRECT":
  722. if (proxyPortEditText != null) {
  723. proxyPortEditText.setValue("8080");
  724. }
  725. break;
  726. case "SOCKS":
  727. if (proxyPortEditText != null) {
  728. proxyPortEditText.setValue("1080");
  729. }
  730. break;
  731. default:
  732. break;
  733. }
  734. showProxySettings();
  735. }
  736. }
  737. }
  738. private class ThemeChangeListener implements OnPreferenceValueChangedListener<String> {
  739. @Override
  740. public void onChanged(String newValue) {
  741. NextcloudTalkApplication.Companion.setAppTheme(newValue);
  742. }
  743. }
  744. private class PhoneBookIntegrationChangeListener implements OnPreferenceValueChangedListener<Boolean> {
  745. private final Controller controller;
  746. public PhoneBookIntegrationChangeListener(Controller controller) {
  747. this.controller = controller;
  748. }
  749. @Override
  750. public void onChanged(Boolean isEnabled) {
  751. if (isEnabled) {
  752. if(ContactAddressBookWorker.Companion.checkPermission(controller, context)){
  753. checkForPhoneNumber();
  754. }
  755. } else {
  756. ContactAddressBookWorker.Companion.deleteAll();
  757. }
  758. }
  759. }
  760. private void checkForPhoneNumber() {
  761. ncApi.getUserData(
  762. ApiUtils.getCredentials(currentUser.getUsername(), currentUser.getToken()),
  763. ApiUtils.getUrlForUserProfile(currentUser.getBaseUrl())
  764. ).subscribeOn(Schedulers.io())
  765. .observeOn(AndroidSchedulers.mainThread())
  766. .subscribe(new Observer<UserProfileOverall>() {
  767. @Override
  768. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  769. }
  770. @Override
  771. public void onNext(@io.reactivex.annotations.NonNull UserProfileOverall userProfileOverall) {
  772. if (userProfileOverall.getOcs().getData().getPhone().isEmpty()) {
  773. askForPhoneNumber();
  774. } else {
  775. Log.d(TAG, "phone number already set");
  776. }
  777. }
  778. @Override
  779. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  780. }
  781. @Override
  782. public void onComplete() {
  783. }
  784. });
  785. }
  786. private void askForPhoneNumber() {
  787. final LinearLayout phoneNumberLayoutWrapper = new LinearLayout(getActivity());
  788. phoneNumberLayoutWrapper.setOrientation(LinearLayout.VERTICAL);
  789. phoneNumberLayoutWrapper.setPadding(50, 0, 50, 0);
  790. final TextInputLayout phoneNumberInputLayout = new TextInputLayout(getActivity());
  791. final EditText phoneNumberField = new EditText(getActivity());
  792. phoneNumberInputLayout.setHelperTextColor(ColorStateList.valueOf(getResources().getColor(R.color.nc_darkRed)));
  793. phoneNumberField.setInputType(InputType.TYPE_CLASS_PHONE);
  794. phoneNumberField.setText("+");
  795. phoneNumberField.addTextChangedListener(new TextWatcher() {
  796. public void afterTextChanged(Editable s) {
  797. }
  798. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  799. }
  800. public void onTextChanged(CharSequence s, int start, int before, int count) {
  801. phoneNumberInputLayout.setHelperText("");
  802. }
  803. });
  804. phoneNumberInputLayout.addView(phoneNumberField);
  805. phoneNumberLayoutWrapper.addView(phoneNumberInputLayout);
  806. AlertDialog dialog = new AlertDialog.Builder(getActivity())
  807. .setTitle(R.string.nc_settings_phone_book_integration_phone_number_dialog_title)
  808. .setMessage(R.string.nc_settings_phone_book_integration_phone_number_dialog_description)
  809. .setView(phoneNumberLayoutWrapper)
  810. .setPositiveButton(context.getResources().getString(R.string.nc_common_set), null)
  811. .setNegativeButton(context.getResources().getString(R.string.nc_common_skip), null)
  812. .create();
  813. dialog.setOnShowListener(new DialogInterface.OnShowListener() {
  814. @Override
  815. public void onShow(DialogInterface dialogInterface) {
  816. Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
  817. button.setOnClickListener(new View.OnClickListener() {
  818. @Override
  819. public void onClick(View view) {
  820. setPhoneNumber(phoneNumberInputLayout, dialog);
  821. }
  822. });
  823. }
  824. });
  825. dialog.show();
  826. }
  827. private void setPhoneNumber(TextInputLayout textInputLayout, AlertDialog dialog) {
  828. String phoneNumber = textInputLayout.getEditText().getText().toString();
  829. ncApi.setUserData(ApiUtils.getCredentials(currentUser.getUsername(), currentUser.getToken()),
  830. ApiUtils.getUrlForUserData(currentUser.getBaseUrl(), currentUser.getUserId()), "phone", phoneNumber
  831. ).subscribeOn(Schedulers.io())
  832. .observeOn(AndroidSchedulers.mainThread())
  833. .subscribe(new Observer<GenericOverall>() {
  834. @Override
  835. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  836. }
  837. @Override
  838. public void onNext(@io.reactivex.annotations.NonNull GenericOverall genericOverall) {
  839. int statusCode = genericOverall.ocs.meta.statusCode;
  840. if (statusCode == 200) {
  841. dialog.dismiss();
  842. Toast.makeText(context, context.getResources().getString(
  843. R.string.nc_settings_phone_book_integration_phone_number_dialog_success),
  844. Toast.LENGTH_LONG).show();
  845. } else {
  846. textInputLayout.setHelperText(context.getResources().getString(
  847. R.string.nc_settings_phone_book_integration_phone_number_dialog_invalid));
  848. Log.d(TAG, "failed to set phoneNumber. statusCode=" + statusCode);
  849. }
  850. }
  851. @Override
  852. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  853. textInputLayout.setHelperText(context.getResources().getString(
  854. R.string.nc_settings_phone_book_integration_phone_number_dialog_invalid));
  855. Log.e(TAG, "setPhoneNumber error", e);
  856. }
  857. @Override
  858. public void onComplete() {
  859. }
  860. });
  861. }
  862. private class ReadPrivacyChangeListener implements OnPreferenceValueChangedListener<Boolean> {
  863. @Override
  864. public void onChanged(Boolean newValue) {
  865. String booleanValue = newValue ? "0" : "1";
  866. String json = "{\"key\": \"read_status_privacy\", \"value\" : " + booleanValue + "}";
  867. ncApi.setReadStatusPrivacy(
  868. ApiUtils.getCredentials(currentUser.getUsername(), currentUser.getToken()),
  869. ApiUtils.getUrlForUserSettings(currentUser.getBaseUrl()),
  870. RequestBody.create(MediaType.parse("application/json"), json))
  871. .subscribeOn(Schedulers.io())
  872. .observeOn(AndroidSchedulers.mainThread())
  873. .subscribe(new Observer<GenericOverall>() {
  874. @Override
  875. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  876. }
  877. @Override
  878. public void onNext(@io.reactivex.annotations.NonNull GenericOverall genericOverall) {
  879. }
  880. @Override
  881. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  882. appPreferences.setReadPrivacy(!newValue);
  883. ((Checkable) readPrivacyPreference.findViewById(R.id.mp_checkable)).setChecked(!newValue);
  884. }
  885. @Override
  886. public void onComplete() {
  887. }
  888. });
  889. }
  890. }
  891. }