AccountVerificationController.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017 Mario Danic (mario@lovelyhq.com)
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.nextcloud.talk.controllers;
  21. import android.annotation.SuppressLint;
  22. import android.content.pm.ActivityInfo;
  23. import android.os.Bundle;
  24. import android.os.Handler;
  25. import android.text.TextUtils;
  26. import android.view.LayoutInflater;
  27. import android.view.View;
  28. import android.view.ViewGroup;
  29. import android.widget.TextView;
  30. import com.bluelinelabs.conductor.RouterTransaction;
  31. import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
  32. import com.nextcloud.talk.R;
  33. import com.nextcloud.talk.api.NcApi;
  34. import com.nextcloud.talk.application.NextcloudTalkApplication;
  35. import com.nextcloud.talk.controllers.base.BaseController;
  36. import com.nextcloud.talk.events.EventStatus;
  37. import com.nextcloud.talk.jobs.CapabilitiesWorker;
  38. import com.nextcloud.talk.jobs.PushRegistrationWorker;
  39. import com.nextcloud.talk.jobs.SignalingSettingsWorker;
  40. import com.nextcloud.talk.models.database.UserEntity;
  41. import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
  42. import com.nextcloud.talk.models.json.generic.Status;
  43. import com.nextcloud.talk.models.json.userprofile.UserProfileOverall;
  44. import com.nextcloud.talk.utils.ApiUtils;
  45. import com.nextcloud.talk.utils.ClosedInterfaceImpl;
  46. import com.nextcloud.talk.utils.bundle.BundleKeys;
  47. import com.nextcloud.talk.utils.database.user.UserUtils;
  48. import com.nextcloud.talk.utils.preferences.AppPreferences;
  49. import com.nextcloud.talk.utils.singletons.ApplicationWideMessageHolder;
  50. import org.greenrobot.eventbus.EventBus;
  51. import org.greenrobot.eventbus.Subscribe;
  52. import org.greenrobot.eventbus.ThreadMode;
  53. import java.net.CookieManager;
  54. import java.util.ArrayList;
  55. import java.util.List;
  56. import javax.inject.Inject;
  57. import androidx.annotation.NonNull;
  58. import androidx.work.Data;
  59. import androidx.work.OneTimeWorkRequest;
  60. import androidx.work.WorkManager;
  61. import autodagger.AutoInjector;
  62. import butterknife.BindView;
  63. import io.reactivex.CompletableObserver;
  64. import io.reactivex.Observer;
  65. import io.reactivex.android.schedulers.AndroidSchedulers;
  66. import io.reactivex.disposables.Disposable;
  67. import io.reactivex.schedulers.Schedulers;
  68. @AutoInjector(NextcloudTalkApplication.class)
  69. public class AccountVerificationController extends BaseController {
  70. public static final String TAG = "AccountVerificationController";
  71. @Inject
  72. NcApi ncApi;
  73. @Inject
  74. UserUtils userUtils;
  75. @Inject
  76. CookieManager cookieManager;
  77. @Inject
  78. AppPreferences appPreferences;
  79. @Inject
  80. EventBus eventBus;
  81. @BindView(R.id.progress_text)
  82. TextView progressText;
  83. private long internalAccountId = -1;
  84. private List<Disposable> disposables = new ArrayList<>();
  85. private String baseUrl;
  86. private String username;
  87. private String token;
  88. private boolean isAccountImport;
  89. private String originalProtocol;
  90. public AccountVerificationController(Bundle args) {
  91. super(args);
  92. if (args != null) {
  93. baseUrl = args.getString(BundleKeys.INSTANCE.getKEY_BASE_URL());
  94. username = args.getString(BundleKeys.INSTANCE.getKEY_USERNAME());
  95. token = args.getString(BundleKeys.INSTANCE.getKEY_TOKEN());
  96. if (args.containsKey(BundleKeys.INSTANCE.getKEY_IS_ACCOUNT_IMPORT())) {
  97. isAccountImport = true;
  98. }
  99. if (args.containsKey(BundleKeys.INSTANCE.getKEY_ORIGINAL_PROTOCOL())) {
  100. originalProtocol = args.getString(BundleKeys.INSTANCE.getKEY_ORIGINAL_PROTOCOL());
  101. }
  102. }
  103. }
  104. @Override
  105. protected void onAttach(@NonNull View view) {
  106. super.onAttach(view);
  107. eventBus.register(this);
  108. }
  109. @Override
  110. protected void onDetach(@NonNull View view) {
  111. super.onDetach(view);
  112. eventBus.unregister(this);
  113. }
  114. @Override
  115. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  116. return inflater.inflate(R.layout.controller_account_verification, container, false);
  117. }
  118. @Override
  119. protected void onViewBound(@NonNull View view) {
  120. super.onViewBound(view);
  121. NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
  122. if (getActivity() != null) {
  123. getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  124. }
  125. if (getActionBar() != null) {
  126. getActionBar().hide();
  127. }
  128. if (isAccountImport && !baseUrl.startsWith("http://") && !baseUrl.startsWith("https://") || (!TextUtils
  129. .isEmpty(originalProtocol) && !baseUrl.startsWith(originalProtocol))) {
  130. determineBaseUrlProtocol(true);
  131. } else {
  132. checkEverything();
  133. }
  134. }
  135. private void checkEverything() {
  136. String credentials = ApiUtils.getCredentials(username, token);
  137. cookieManager.getCookieStore().removeAll();
  138. findServerTalkApp(credentials);
  139. }
  140. private void determineBaseUrlProtocol(boolean checkForcedHttps) {
  141. cookieManager.getCookieStore().removeAll();
  142. String queryUrl;
  143. baseUrl = baseUrl.replace("http://", "").replace("https://", "");
  144. if (checkForcedHttps) {
  145. queryUrl = "https://" + baseUrl + ApiUtils.getUrlPostfixForStatus();
  146. } else {
  147. queryUrl = "http://" + baseUrl + ApiUtils.getUrlPostfixForStatus();
  148. }
  149. ncApi.getServerStatus(queryUrl)
  150. .subscribeOn(Schedulers.io())
  151. .observeOn(AndroidSchedulers.mainThread())
  152. .subscribe(new Observer<Status>() {
  153. @Override
  154. public void onSubscribe(Disposable d) {
  155. disposables.add(d);
  156. }
  157. @Override
  158. public void onNext(Status status) {
  159. if (checkForcedHttps) {
  160. baseUrl = "https://" + baseUrl;
  161. } else {
  162. baseUrl = "http://" + baseUrl;
  163. }
  164. if (isAccountImport) {
  165. getRouter().replaceTopController(RouterTransaction.with(new WebViewLoginController(baseUrl,
  166. false, username, ""))
  167. .pushChangeHandler(new HorizontalChangeHandler())
  168. .popChangeHandler(new HorizontalChangeHandler()));
  169. } else {
  170. checkEverything();
  171. }
  172. }
  173. @Override
  174. public void onError(Throwable e) {
  175. if (checkForcedHttps) {
  176. determineBaseUrlProtocol(false);
  177. } else {
  178. abortVerification();
  179. }
  180. }
  181. @Override
  182. public void onComplete() {
  183. }
  184. });
  185. }
  186. private void findServerTalkApp(String credentials) {
  187. ncApi.getCapabilities(credentials, ApiUtils.getUrlForCapabilities(baseUrl))
  188. .subscribeOn(Schedulers.io())
  189. .subscribe(new Observer<CapabilitiesOverall>() {
  190. @Override
  191. public void onSubscribe(Disposable d) {
  192. disposables.add(d);
  193. }
  194. @Override
  195. public void onNext(CapabilitiesOverall capabilitiesOverall) {
  196. boolean hasTalk =
  197. capabilitiesOverall.getOcs().getData().getCapabilities() != null
  198. && capabilitiesOverall.getOcs().getData().getCapabilities().getSpreedCapability() != null
  199. && capabilitiesOverall.getOcs().getData().getCapabilities().getSpreedCapability().getFeatures() != null
  200. && !capabilitiesOverall.getOcs().getData().getCapabilities().getSpreedCapability().getFeatures().isEmpty();
  201. if (hasTalk) {
  202. fetchProfile(credentials);
  203. } else {
  204. if (getActivity() != null && getResources() != null) {
  205. getActivity().runOnUiThread(() -> progressText.setText(
  206. String.format(
  207. getResources().getString(R.string.nc_nextcloud_talk_app_not_installed),
  208. getResources().getString(R.string.nc_app_product_name))));
  209. }
  210. ApplicationWideMessageHolder.getInstance().setMessageType(
  211. ApplicationWideMessageHolder.MessageType.SERVER_WITHOUT_TALK);
  212. abortVerification();
  213. }
  214. }
  215. @Override
  216. public void onError(Throwable e) {
  217. if (getActivity() != null && getResources() != null) {
  218. getActivity().runOnUiThread(() -> progressText.setText(
  219. String.format(
  220. getResources().getString(R.string.nc_nextcloud_talk_app_not_installed),
  221. getResources().getString(R.string.nc_app_product_name))));
  222. }
  223. ApplicationWideMessageHolder.getInstance().setMessageType(
  224. ApplicationWideMessageHolder.MessageType.SERVER_WITHOUT_TALK);
  225. abortVerification();
  226. }
  227. @Override
  228. public void onComplete() {
  229. }
  230. });
  231. }
  232. private void storeProfile(String displayName, String userId) {
  233. userUtils.createOrUpdateUser(username, token,
  234. baseUrl, displayName, null, Boolean.TRUE,
  235. userId, null, null,
  236. appPreferences.getTemporaryClientCertAlias(), null)
  237. .subscribeOn(Schedulers.io())
  238. .subscribe(new Observer<UserEntity>() {
  239. @Override
  240. public void onSubscribe(Disposable d) {
  241. disposables.add(d);
  242. }
  243. @SuppressLint("SetTextI18n")
  244. @Override
  245. public void onNext(UserEntity userEntity) {
  246. internalAccountId = userEntity.getId();
  247. if (new ClosedInterfaceImpl().isGooglePlayServicesAvailable()) {
  248. registerForPush();
  249. } else {
  250. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  251. getResources().getString(R.string.nc_push_disabled)));
  252. fetchAndStoreCapabilities();
  253. }
  254. }
  255. @SuppressLint("SetTextI18n")
  256. @Override
  257. public void onError(Throwable e) {
  258. progressText.setText(progressText.getText().toString() +
  259. "\n" +
  260. getResources().getString(
  261. R.string.nc_display_name_not_stored));
  262. abortVerification();
  263. }
  264. @Override
  265. public void onComplete() {
  266. }
  267. });
  268. }
  269. private void fetchProfile(String credentials) {
  270. ncApi.getUserProfile(credentials,
  271. ApiUtils.getUrlForUserProfile(baseUrl))
  272. .subscribeOn(Schedulers.io())
  273. .subscribe(new Observer<UserProfileOverall>() {
  274. @Override
  275. public void onSubscribe(Disposable d) {
  276. disposables.add(d);
  277. }
  278. @SuppressLint("SetTextI18n")
  279. @Override
  280. public void onNext(UserProfileOverall userProfileOverall) {
  281. String displayName = null;
  282. if (!TextUtils.isEmpty(userProfileOverall.getOcs().getData()
  283. .getDisplayName())) {
  284. displayName = userProfileOverall.getOcs().getData()
  285. .getDisplayName();
  286. } else if (!TextUtils.isEmpty(userProfileOverall.getOcs().getData()
  287. .getDisplayNameAlt())) {
  288. displayName = userProfileOverall.getOcs().getData()
  289. .getDisplayNameAlt();
  290. }
  291. if (!TextUtils.isEmpty(displayName)) {
  292. storeProfile(displayName, userProfileOverall.getOcs().getData().getUserId());
  293. } else {
  294. if (getActivity() != null) {
  295. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  296. getResources().getString(R.string.nc_display_name_not_fetched)));
  297. }
  298. abortVerification();
  299. }
  300. }
  301. @SuppressLint("SetTextI18n")
  302. @Override
  303. public void onError(Throwable e) {
  304. if (getActivity() != null) {
  305. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  306. getResources().getString(R.string.nc_display_name_not_fetched)));
  307. }
  308. abortVerification();
  309. }
  310. @Override
  311. public void onComplete() {
  312. }
  313. });
  314. }
  315. private void registerForPush() {
  316. OneTimeWorkRequest pushRegistrationWork = new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
  317. WorkManager.getInstance().enqueue(pushRegistrationWork);
  318. }
  319. @SuppressLint("SetTextI18n")
  320. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  321. public void onMessageEvent(EventStatus eventStatus) {
  322. if (eventStatus.getEventType().equals(EventStatus.EventType.PUSH_REGISTRATION)) {
  323. if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood() && getActivity() != null) {
  324. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  325. getResources().getString(R.string.nc_push_disabled)));
  326. }
  327. fetchAndStoreCapabilities();
  328. } else if (eventStatus.getEventType().equals(EventStatus.EventType.CAPABILITIES_FETCH)) {
  329. if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) {
  330. if (getActivity() != null) {
  331. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  332. getResources().getString(R.string.nc_capabilities_failed)));
  333. }
  334. abortVerification();
  335. } else if (internalAccountId == eventStatus.getUserId() && eventStatus.isAllGood()) {
  336. fetchAndStoreExternalSignalingSettings();
  337. }
  338. } else if (eventStatus.getEventType().equals(EventStatus.EventType.SIGNALING_SETTINGS)) {
  339. if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) {
  340. if (getActivity() != null) {
  341. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  342. getResources().getString(R.string.nc_external_server_failed)));
  343. }
  344. }
  345. proceedWithLogin();
  346. }
  347. }
  348. private void fetchAndStoreCapabilities() {
  349. Data userData = new Data.Builder()
  350. .putLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), internalAccountId)
  351. .build();
  352. OneTimeWorkRequest pushNotificationWork = new OneTimeWorkRequest.Builder(CapabilitiesWorker.class)
  353. .setInputData(userData)
  354. .build();
  355. WorkManager.getInstance().enqueue(pushNotificationWork);
  356. }
  357. private void fetchAndStoreExternalSignalingSettings() {
  358. Data userData = new Data.Builder()
  359. .putLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), internalAccountId)
  360. .build();
  361. OneTimeWorkRequest signalingSettings = new OneTimeWorkRequest.Builder(SignalingSettingsWorker.class)
  362. .setInputData(userData)
  363. .build();
  364. WorkManager.getInstance().enqueue(signalingSettings);
  365. }
  366. private void proceedWithLogin() {
  367. cookieManager.getCookieStore().removeAll();
  368. userUtils.disableAllUsersWithoutId(internalAccountId);
  369. if (getActivity() != null) {
  370. getActivity().runOnUiThread(() -> {
  371. if (userUtils.getUsers().size() == 1) {
  372. getRouter().setRoot(RouterTransaction.with(new
  373. ConversationsListController(new Bundle()))
  374. .pushChangeHandler(new HorizontalChangeHandler())
  375. .popChangeHandler(new HorizontalChangeHandler()));
  376. } else {
  377. if (isAccountImport) {
  378. ApplicationWideMessageHolder.getInstance().setMessageType(
  379. ApplicationWideMessageHolder.MessageType.ACCOUNT_WAS_IMPORTED);
  380. }
  381. getRouter().popToRoot();
  382. }
  383. });
  384. }
  385. }
  386. private void dispose() {
  387. for (int i = 0; i < disposables.size(); i++) {
  388. if (!disposables.get(i).isDisposed()) {
  389. disposables.get(i).dispose();
  390. }
  391. }
  392. }
  393. @Override
  394. protected void onDestroyView(@NonNull View view) {
  395. super.onDestroyView(view);
  396. if (getActivity() != null) {
  397. getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
  398. }
  399. }
  400. @Override
  401. public void onDestroy() {
  402. dispose();
  403. super.onDestroy();
  404. }
  405. private void abortVerification() {
  406. if (!isAccountImport) {
  407. if (internalAccountId != -1) {
  408. userUtils.deleteUserWithId(internalAccountId).subscribe(new CompletableObserver() {
  409. @Override
  410. public void onSubscribe(Disposable d) {
  411. }
  412. @Override
  413. public void onComplete() {
  414. if (getActivity() != null) {
  415. getActivity().runOnUiThread(() -> {
  416. new Handler().postDelayed(() -> getRouter().popToRoot(), 7500);
  417. });
  418. }
  419. }
  420. @Override
  421. public void onError(Throwable e) {
  422. }
  423. });
  424. } else {
  425. if (getActivity() != null) {
  426. getActivity().runOnUiThread(() -> {
  427. new Handler().postDelayed(() -> getRouter().popToRoot(), 7500);
  428. });
  429. }
  430. }
  431. } else {
  432. ApplicationWideMessageHolder.getInstance().setMessageType(
  433. ApplicationWideMessageHolder.MessageType.FAILED_TO_IMPORT_ACCOUNT);
  434. if (getActivity() != null) {
  435. getActivity().runOnUiThread(() -> new Handler().postDelayed(() -> {
  436. if (getRouter().hasRootController()) {
  437. if (getActivity() != null) {
  438. getRouter().popToRoot();
  439. }
  440. } else {
  441. if (userUtils.anyUserExists()) {
  442. getRouter().setRoot(RouterTransaction.with(new ConversationsListController(new Bundle()))
  443. .pushChangeHandler(new HorizontalChangeHandler())
  444. .popChangeHandler(new HorizontalChangeHandler()));
  445. } else {
  446. getRouter().setRoot(RouterTransaction.with(new ServerSelectionController())
  447. .pushChangeHandler(new HorizontalChangeHandler())
  448. .popChangeHandler(new HorizontalChangeHandler()));
  449. }
  450. }
  451. }, 7500));
  452. }
  453. }
  454. }
  455. }