AccountVerificationController.java 19 KB

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