AccountVerificationController.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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.content.pm.ActivityInfo;
  22. import android.os.Bundle;
  23. import android.os.Handler;
  24. import android.text.TextUtils;
  25. import android.view.LayoutInflater;
  26. import android.view.View;
  27. import android.view.ViewGroup;
  28. import android.widget.TextView;
  29. import com.bluelinelabs.conductor.RouterTransaction;
  30. import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
  31. import com.nextcloud.talk.R;
  32. import com.nextcloud.talk.api.NcApi;
  33. import com.nextcloud.talk.application.NextcloudTalkApplication;
  34. import com.nextcloud.talk.controllers.base.BaseController;
  35. import com.nextcloud.talk.events.EventStatus;
  36. import com.nextcloud.talk.jobs.CapabilitiesWorker;
  37. import com.nextcloud.talk.jobs.PushRegistrationWorker;
  38. import com.nextcloud.talk.jobs.SignalingSettingsJob;
  39. import com.nextcloud.talk.models.database.UserEntity;
  40. import com.nextcloud.talk.models.json.generic.Status;
  41. import com.nextcloud.talk.models.json.rooms.RoomsOverall;
  42. import com.nextcloud.talk.models.json.userprofile.UserProfileOverall;
  43. import com.nextcloud.talk.utils.ApiUtils;
  44. import com.nextcloud.talk.utils.ClosedInterfaceImpl;
  45. import com.nextcloud.talk.utils.bundle.BundleKeys;
  46. import com.nextcloud.talk.utils.database.user.UserUtils;
  47. import com.nextcloud.talk.utils.preferences.AppPreferences;
  48. import com.nextcloud.talk.utils.singletons.ApplicationWideMessageHolder;
  49. import io.reactivex.android.schedulers.AndroidSchedulers;
  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.disposables.Disposable;
  66. import io.reactivex.schedulers.Schedulers;
  67. @AutoInjector(NextcloudTalkApplication.class)
  68. public class AccountVerificationController extends BaseController {
  69. public static final String TAG = "AccountVerificationController";
  70. @Inject
  71. NcApi ncApi;
  72. @Inject
  73. UserUtils userUtils;
  74. @Inject
  75. CookieManager cookieManager;
  76. @Inject
  77. AppPreferences appPreferences;
  78. @Inject
  79. EventBus eventBus;
  80. @BindView(R.id.progress_text)
  81. TextView progressText;
  82. private long internalAccountId = -1;
  83. private List<Disposable> disposables = new ArrayList<>();
  84. private String baseUrl;
  85. private String username;
  86. private String token;
  87. private boolean isAccountImport;
  88. private String originalProtocol;
  89. public AccountVerificationController(Bundle args) {
  90. super(args);
  91. if (args != null) {
  92. baseUrl = args.getString(BundleKeys.KEY_BASE_URL);
  93. username = args.getString(BundleKeys.KEY_USERNAME);
  94. token = args.getString(BundleKeys.KEY_TOKEN);
  95. if (args.containsKey(BundleKeys.KEY_IS_ACCOUNT_IMPORT)) {
  96. isAccountImport = true;
  97. }
  98. if (args.containsKey(BundleKeys.KEY_ORIGINAL_PROTOCOL)) {
  99. originalProtocol = args.getString(BundleKeys.KEY_ORIGINAL_PROTOCOL);
  100. }
  101. }
  102. }
  103. @Override
  104. protected void onAttach(@NonNull View view) {
  105. super.onAttach(view);
  106. eventBus.register(this);
  107. }
  108. @Override
  109. protected void onDetach(@NonNull View view) {
  110. super.onDetach(view);
  111. eventBus.unregister(this);
  112. }
  113. @Override
  114. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  115. return inflater.inflate(R.layout.controller_account_verification, container, false);
  116. }
  117. @Override
  118. protected void onViewBound(@NonNull View view) {
  119. super.onViewBound(view);
  120. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  121. if (getActivity() != null) {
  122. getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  123. }
  124. if (getActionBar() != null) {
  125. getActionBar().hide();
  126. }
  127. if (isAccountImport && !baseUrl.startsWith("http://") && !baseUrl.startsWith("https://") || (!TextUtils
  128. .isEmpty(originalProtocol) && !baseUrl.startsWith(originalProtocol))) {
  129. determineBaseUrlProtocol(true);
  130. } else {
  131. checkEverything();
  132. }
  133. }
  134. private void checkEverything() {
  135. String credentials = ApiUtils.getCredentials(username, token);
  136. cookieManager.getCookieStore().removeAll();
  137. findServerTalkApp(credentials);
  138. }
  139. private void determineBaseUrlProtocol(boolean checkForcedHttps) {
  140. cookieManager.getCookieStore().removeAll();
  141. String queryUrl;
  142. baseUrl = baseUrl.replace("http://", "").replace("https://", "");
  143. if (checkForcedHttps) {
  144. queryUrl = "https://" + baseUrl + ApiUtils.getUrlPostfixForStatus();
  145. } else {
  146. queryUrl = "http://" + baseUrl + ApiUtils.getUrlPostfixForStatus();
  147. }
  148. ncApi.getServerStatus(queryUrl)
  149. .subscribeOn(Schedulers.newThread())
  150. .observeOn(AndroidSchedulers.mainThread())
  151. .subscribe(new Observer<Status>() {
  152. @Override
  153. public void onSubscribe(Disposable d) {
  154. disposables.add(d);
  155. }
  156. @Override
  157. public void onNext(Status status) {
  158. if (checkForcedHttps) {
  159. baseUrl = "https://" + baseUrl;
  160. } else {
  161. baseUrl = "http://" + baseUrl;
  162. }
  163. if (isAccountImport) {
  164. getRouter().pushController(RouterTransaction.with(new WebViewLoginController(baseUrl,
  165. false, username, "")));
  166. } else {
  167. checkEverything();
  168. }
  169. }
  170. @Override
  171. public void onError(Throwable e) {
  172. if (checkForcedHttps) {
  173. determineBaseUrlProtocol(false);
  174. } else {
  175. abortVerification();
  176. }
  177. }
  178. @Override
  179. public void onComplete() {
  180. }
  181. });
  182. }
  183. private void findServerTalkApp(String credentials) {
  184. ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(baseUrl))
  185. .subscribeOn(Schedulers.newThread())
  186. .subscribe(new Observer<RoomsOverall>() {
  187. @Override
  188. public void onSubscribe(Disposable d) {
  189. disposables.add(d);
  190. }
  191. @Override
  192. public void onNext(RoomsOverall roomsOverall) {
  193. fetchProfile(credentials);
  194. }
  195. @Override
  196. public void onError(Throwable e) {
  197. if (getActivity() != null && getResources() != null) {
  198. getActivity().runOnUiThread(() -> progressText.setText(String.format(getResources().getString(
  199. R.string.nc_nextcloud_talk_app_not_installed), getResources().getString(R.string.nc_app_name))));
  200. }
  201. ApplicationWideMessageHolder.getInstance().setMessageType(
  202. ApplicationWideMessageHolder.MessageType.SERVER_WITHOUT_TALK);
  203. abortVerification();
  204. }
  205. @Override
  206. public void onComplete() {
  207. }
  208. });
  209. }
  210. private void storeProfile(String displayName, String userId) {
  211. userUtils.createOrUpdateUser(username, token,
  212. baseUrl, displayName, null, true,
  213. userId, null, null,
  214. appPreferences.getTemporaryClientCertAlias(), null)
  215. .subscribeOn(Schedulers.newThread())
  216. .subscribe(new Observer<UserEntity>() {
  217. @Override
  218. public void onSubscribe(Disposable d) {
  219. disposables.add(d);
  220. }
  221. @Override
  222. public void onNext(UserEntity userEntity) {
  223. internalAccountId = userEntity.getId();
  224. if (new ClosedInterfaceImpl().isGooglePlayServicesAvailable()) {
  225. registerForPush();
  226. } else {
  227. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  228. getResources().getString(R.string.nc_push_disabled)));
  229. fetchAndStoreCapabilities();
  230. }
  231. }
  232. @Override
  233. public void onError(Throwable e) {
  234. progressText.setText(progressText.getText().toString() +
  235. "\n" +
  236. getResources().getString(
  237. R.string.nc_display_name_not_stored));
  238. abortVerification();
  239. }
  240. @Override
  241. public void onComplete() {
  242. }
  243. });
  244. }
  245. private void fetchProfile(String credentials) {
  246. ncApi.getUserProfile(credentials,
  247. ApiUtils.getUrlForUserProfile(baseUrl))
  248. .subscribeOn(Schedulers.newThread())
  249. .subscribe(new Observer<UserProfileOverall>() {
  250. @Override
  251. public void onSubscribe(Disposable d) {
  252. disposables.add(d);
  253. }
  254. @Override
  255. public void onNext(UserProfileOverall userProfileOverall) {
  256. String displayName = null;
  257. if (!TextUtils.isEmpty(userProfileOverall.getOcs().getData()
  258. .getDisplayName())) {
  259. displayName = userProfileOverall.getOcs().getData()
  260. .getDisplayName();
  261. } else if (!TextUtils.isEmpty(userProfileOverall.getOcs().getData()
  262. .getDisplayNameAlt())) {
  263. displayName = userProfileOverall.getOcs().getData()
  264. .getDisplayNameAlt();
  265. }
  266. if (!TextUtils.isEmpty(displayName)) {
  267. storeProfile(displayName, userProfileOverall.getOcs().getData().getUserId());
  268. } else {
  269. if (getActivity() != null) {
  270. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  271. getResources().getString(R.string.nc_display_name_not_fetched)));
  272. }
  273. abortVerification();
  274. }
  275. }
  276. @Override
  277. public void onError(Throwable e) {
  278. if (getActivity() != null) {
  279. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  280. getResources().getString(R.string.nc_display_name_not_fetched)));
  281. }
  282. abortVerification();
  283. }
  284. @Override
  285. public void onComplete() {
  286. }
  287. });
  288. }
  289. private void registerForPush() {
  290. OneTimeWorkRequest pushRegistrationWork = new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
  291. WorkManager.getInstance().enqueue(pushRegistrationWork);
  292. }
  293. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  294. public void onMessageEvent(EventStatus eventStatus) {
  295. if (eventStatus.getEventType().equals(EventStatus.EventType.PUSH_REGISTRATION)) {
  296. if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood() && getActivity() != null) {
  297. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  298. getResources().getString(R.string.nc_push_disabled)));
  299. }
  300. fetchAndStoreCapabilities();
  301. } else if (eventStatus.getEventType().equals(EventStatus.EventType.CAPABILITIES_FETCH)) {
  302. if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) {
  303. if (getActivity() != null) {
  304. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  305. getResources().getString(R.string.nc_capabilities_failed)));
  306. }
  307. abortVerification();
  308. } else if (internalAccountId == eventStatus.getUserId() && eventStatus.isAllGood()) {
  309. fetchAndStoreExternalSignalingSettings();
  310. }
  311. } else if (eventStatus.getEventType().equals(EventStatus.EventType.SIGNALING_SETTINGS)) {
  312. if (internalAccountId == eventStatus.getUserId() && !eventStatus.isAllGood()) {
  313. if (getActivity() != null) {
  314. getActivity().runOnUiThread(() -> progressText.setText(progressText.getText().toString() + "\n" +
  315. getResources().getString(R.string.nc_external_server_failed)));
  316. }
  317. }
  318. proceedWithLogin();
  319. }
  320. }
  321. private void fetchAndStoreCapabilities() {
  322. Data userData = new Data.Builder()
  323. .putLong(BundleKeys.KEY_INTERNAL_USER_ID, internalAccountId)
  324. .build();
  325. OneTimeWorkRequest pushNotificationWork = new OneTimeWorkRequest.Builder(CapabilitiesWorker.class)
  326. .setInputData(userData)
  327. .build();
  328. WorkManager.getInstance().enqueue(pushNotificationWork);
  329. }
  330. private void fetchAndStoreExternalSignalingSettings() {
  331. Data userData = new Data.Builder()
  332. .putLong(BundleKeys.KEY_INTERNAL_USER_ID, internalAccountId)
  333. .build();
  334. OneTimeWorkRequest signalingSettings = new OneTimeWorkRequest.Builder(SignalingSettingsJob.class)
  335. .setInputData(userData)
  336. .build();
  337. WorkManager.getInstance().enqueue(signalingSettings);
  338. }
  339. private void proceedWithLogin() {
  340. cookieManager.getCookieStore().removeAll();
  341. userUtils.disableAllUsersWithoutId(internalAccountId);
  342. if (getActivity() != null) {
  343. getActivity().runOnUiThread(() -> {
  344. if (userUtils.getUsers().size() == 1) {
  345. getRouter().setRoot(RouterTransaction.with(new
  346. ConversationsListController())
  347. .pushChangeHandler(new HorizontalChangeHandler())
  348. .popChangeHandler(new HorizontalChangeHandler()));
  349. } else {
  350. if (isAccountImport) {
  351. ApplicationWideMessageHolder.getInstance().setMessageType(
  352. ApplicationWideMessageHolder.MessageType.ACCOUNT_WAS_IMPORTED);
  353. }
  354. getRouter().popToRoot();
  355. }
  356. });
  357. }
  358. }
  359. private void dispose() {
  360. for (int i = 0; i < disposables.size(); i++) {
  361. if (!disposables.get(i).isDisposed()) {
  362. disposables.get(i).dispose();
  363. }
  364. }
  365. }
  366. @Override
  367. protected void onDestroyView(@NonNull View view) {
  368. super.onDestroyView(view);
  369. if (getActivity() != null) {
  370. getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
  371. }
  372. }
  373. @Override
  374. public void onDestroy() {
  375. dispose();
  376. super.onDestroy();
  377. }
  378. private void abortVerification() {
  379. if (!isAccountImport) {
  380. if (internalAccountId != -1) {
  381. userUtils.deleteUserWithId(internalAccountId).subscribe(new CompletableObserver() {
  382. @Override
  383. public void onSubscribe(Disposable d) {
  384. }
  385. @Override
  386. public void onComplete() {
  387. if (getActivity() != null) {
  388. getActivity().runOnUiThread(() -> {
  389. new Handler().postDelayed(() -> getRouter().popToRoot(), 7500);
  390. });
  391. }
  392. }
  393. @Override
  394. public void onError(Throwable e) {
  395. }
  396. });
  397. } else {
  398. if (getActivity() != null) {
  399. getActivity().runOnUiThread(() -> {
  400. new Handler().postDelayed(() -> getRouter().popToRoot(), 7500);
  401. });
  402. }
  403. }
  404. } else {
  405. ApplicationWideMessageHolder.getInstance().setMessageType(
  406. ApplicationWideMessageHolder.MessageType.FAILED_TO_IMPORT_ACCOUNT);
  407. if (getActivity() != null) {
  408. getActivity().runOnUiThread(() -> new Handler().postDelayed(() -> {
  409. if (getRouter().hasRootController()) {
  410. if (getActivity() != null) {
  411. getRouter().popToRoot();
  412. }
  413. } else {
  414. if (userUtils.anyUserExists()) {
  415. getRouter().setRoot(RouterTransaction.with(new ConversationsListController())
  416. .pushChangeHandler(new HorizontalChangeHandler())
  417. .popChangeHandler(new HorizontalChangeHandler()));
  418. } else {
  419. getRouter().setRoot(RouterTransaction.with(new ServerSelectionController())
  420. .pushChangeHandler(new HorizontalChangeHandler())
  421. .popChangeHandler(new HorizontalChangeHandler()));
  422. }
  423. }
  424. }, 7500));
  425. }
  426. }
  427. }
  428. }