AccountVerificationController.java 17 KB

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