AccountVerificationController.java 18 KB

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