ChatController.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017-2018 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.ClipData;
  22. import android.content.ClipboardManager;
  23. import android.content.Context;
  24. import android.content.Intent;
  25. import android.graphics.Color;
  26. import android.graphics.drawable.ColorDrawable;
  27. import android.graphics.drawable.Drawable;
  28. import android.os.Bundle;
  29. import android.os.Handler;
  30. import android.support.annotation.NonNull;
  31. import android.support.v7.widget.LinearLayoutManager;
  32. import android.support.v7.widget.RecyclerView;
  33. import android.text.TextUtils;
  34. import android.util.Log;
  35. import android.view.LayoutInflater;
  36. import android.view.Menu;
  37. import android.view.MenuInflater;
  38. import android.view.MenuItem;
  39. import android.view.View;
  40. import android.view.ViewGroup;
  41. import android.view.inputmethod.EditorInfo;
  42. import android.widget.AbsListView;
  43. import android.widget.ImageView;
  44. import com.bluelinelabs.conductor.RouterTransaction;
  45. import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
  46. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  47. import com.bumptech.glide.load.resource.bitmap.CircleCrop;
  48. import com.bumptech.glide.request.RequestOptions;
  49. import com.nextcloud.talk.R;
  50. import com.nextcloud.talk.activities.CallActivity;
  51. import com.nextcloud.talk.adapters.messages.MagicIncomingTextMessageViewHolder;
  52. import com.nextcloud.talk.adapters.messages.MagicOutcomingTextMessageViewHolder;
  53. import com.nextcloud.talk.api.NcApi;
  54. import com.nextcloud.talk.application.NextcloudTalkApplication;
  55. import com.nextcloud.talk.callbacks.MentionAutocompleteCallback;
  56. import com.nextcloud.talk.controllers.base.BaseController;
  57. import com.nextcloud.talk.models.database.UserEntity;
  58. import com.nextcloud.talk.models.json.call.Call;
  59. import com.nextcloud.talk.models.json.call.CallOverall;
  60. import com.nextcloud.talk.models.json.chat.ChatMessage;
  61. import com.nextcloud.talk.models.json.chat.ChatOverall;
  62. import com.nextcloud.talk.models.json.generic.GenericOverall;
  63. import com.nextcloud.talk.models.json.mention.Mention;
  64. import com.nextcloud.talk.presenters.MentionAutocompletePresenter;
  65. import com.nextcloud.talk.utils.ApiUtils;
  66. import com.nextcloud.talk.utils.KeyboardUtils;
  67. import com.nextcloud.talk.utils.bundle.BundleKeys;
  68. import com.nextcloud.talk.utils.database.user.UserUtils;
  69. import com.nextcloud.talk.utils.glide.GlideApp;
  70. import com.otaliastudios.autocomplete.Autocomplete;
  71. import com.otaliastudios.autocomplete.AutocompleteCallback;
  72. import com.otaliastudios.autocomplete.AutocompletePresenter;
  73. import com.otaliastudios.autocomplete.CharPolicy;
  74. import com.stfalcon.chatkit.commons.ImageLoader;
  75. import com.stfalcon.chatkit.commons.models.IMessage;
  76. import com.stfalcon.chatkit.messages.MessageInput;
  77. import com.stfalcon.chatkit.messages.MessagesList;
  78. import com.stfalcon.chatkit.messages.MessagesListAdapter;
  79. import com.stfalcon.chatkit.utils.DateFormatter;
  80. import com.webianks.library.PopupBubble;
  81. import org.parceler.Parcels;
  82. import java.io.IOException;
  83. import java.util.ArrayList;
  84. import java.util.Date;
  85. import java.util.HashMap;
  86. import java.util.List;
  87. import java.util.Map;
  88. import java.util.Objects;
  89. import javax.inject.Inject;
  90. import autodagger.AutoInjector;
  91. import butterknife.BindView;
  92. import io.reactivex.Observer;
  93. import io.reactivex.android.schedulers.AndroidSchedulers;
  94. import io.reactivex.disposables.Disposable;
  95. import io.reactivex.schedulers.Schedulers;
  96. import okhttp3.Cache;
  97. import retrofit2.Response;
  98. @AutoInjector(NextcloudTalkApplication.class)
  99. public class ChatController extends BaseController implements MessagesListAdapter.OnLoadMoreListener,
  100. MessagesListAdapter.Formatter<Date>, MessagesListAdapter.OnMessageLongClickListener{
  101. private static final String TAG = "ChatController";
  102. @Inject
  103. NcApi ncApi;
  104. @Inject
  105. UserUtils userUtils;
  106. @Inject
  107. Cache cache;
  108. @BindView(R.id.input)
  109. MessageInput messageInput;
  110. @BindView(R.id.messagesList)
  111. MessagesList messagesList;
  112. @BindView(R.id.popupBubble)
  113. PopupBubble popupBubble;
  114. private List<Disposable> disposableList = new ArrayList<>();
  115. private String conversationName;
  116. private String roomToken;
  117. private UserEntity currentUser;
  118. private String roomPassword;
  119. private Call currentCall;
  120. private boolean inChat = false;
  121. private boolean historyRead = false;
  122. private int globalLastKnownFutureMessageId = -1;
  123. private int globalLastKnownPastMessageId = -1;
  124. private MessagesListAdapter<ChatMessage> adapter;
  125. private Menu globalMenu;
  126. private Autocomplete mentionAutocomplete;
  127. private LinearLayoutManager layoutManager;
  128. private boolean lookingIntoFuture = false;
  129. private int newMessagesCount = 0;
  130. /*
  131. TODO:
  132. - check push notifications
  133. */
  134. public ChatController(Bundle args) {
  135. super(args);
  136. setHasOptionsMenu(true);
  137. this.conversationName = args.getString(BundleKeys.KEY_CONVERSATION_NAME);
  138. this.currentUser = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_USER_ENTITY));
  139. this.roomToken = args.getString(BundleKeys.KEY_ROOM_TOKEN);
  140. this.roomPassword = args.getString(BundleKeys.KEY_ROOM_PASSWORD, "");
  141. }
  142. @Override
  143. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  144. return inflater.inflate(R.layout.controller_chat, container, false);
  145. }
  146. @Override
  147. protected void onViewBound(@NonNull View view) {
  148. super.onViewBound(view);
  149. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  150. boolean adapterWasNull = false;
  151. if (adapter == null) {
  152. try {
  153. cache.evictAll();
  154. } catch (IOException e) {
  155. Log.e(TAG, "Failed to evict cache");
  156. }
  157. adapterWasNull = true;
  158. MessagesListAdapter.HoldersConfig holdersConfig = new MessagesListAdapter.HoldersConfig();
  159. holdersConfig.setIncoming(MagicIncomingTextMessageViewHolder.class,
  160. R.layout.item_custom_incoming_text_message);
  161. holdersConfig.setOutcoming(MagicOutcomingTextMessageViewHolder.class,
  162. R.layout.item_custom_outcoming_text_message);
  163. adapter = new MessagesListAdapter<>(currentUser.getUserId(), holdersConfig, new ImageLoader() {
  164. @Override
  165. public void loadImage(ImageView imageView, String url) {
  166. GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
  167. .asBitmap()
  168. .diskCacheStrategy(DiskCacheStrategy.NONE)
  169. .load(url)
  170. .centerInside()
  171. .override(imageView.getMeasuredWidth(), imageView.getMeasuredHeight())
  172. .apply(RequestOptions.bitmapTransform(new CircleCrop()))
  173. .into(imageView);
  174. }
  175. });
  176. }
  177. messagesList.setAdapter(adapter);
  178. adapter.setLoadMoreListener(this);
  179. adapter.setDateHeadersFormatter(this::format);
  180. adapter.setOnMessageLongClickListener(this);
  181. layoutManager = (LinearLayoutManager) messagesList.getLayoutManager();
  182. popupBubble.setRecyclerView(messagesList);
  183. popupBubble.setPopupBubbleListener(context -> {
  184. if (newMessagesCount != 0) {
  185. new Handler().postDelayed(() -> messagesList.smoothScrollToPosition(newMessagesCount - 1), 200);
  186. }
  187. });
  188. messagesList.addOnScrollListener(new RecyclerView.OnScrollListener() {
  189. @Override
  190. public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
  191. super.onScrollStateChanged(recyclerView, newState);
  192. if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
  193. if (newMessagesCount != 0) {
  194. if (layoutManager.findFirstCompletelyVisibleItemPosition() < newMessagesCount) {
  195. newMessagesCount = 0;
  196. if (popupBubble.isShown()) {
  197. popupBubble.hide();
  198. }
  199. }
  200. }
  201. }
  202. }
  203. });
  204. setupMentionAutocomplete();
  205. messageInput.getInputEditText().setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
  206. messageInput.setInputListener(input -> {
  207. sendMessage(input.toString());
  208. return true;
  209. });
  210. if (adapterWasNull) {
  211. joinRoomWithPassword();
  212. }
  213. }
  214. private void setupMentionAutocomplete() {
  215. float elevation = 6f;
  216. Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
  217. AutocompletePresenter<Mention> presenter = new MentionAutocompletePresenter(getApplicationContext(), roomToken);
  218. AutocompleteCallback<Mention> callback = new MentionAutocompleteCallback();
  219. mentionAutocomplete = Autocomplete.<Mention>on(messageInput.getInputEditText())
  220. .with(elevation)
  221. .with(backgroundDrawable)
  222. .with(new CharPolicy('@'))
  223. .with(presenter)
  224. .with(callback)
  225. .build();
  226. }
  227. @Override
  228. protected void onAttach(@NonNull View view) {
  229. super.onAttach(view);
  230. if (getActionBar() != null) {
  231. getActionBar().setDisplayHomeAsUpEnabled(true);
  232. }
  233. if (mentionAutocomplete != null && mentionAutocomplete.isPopupShowing()) {
  234. mentionAutocomplete.dismissPopup();
  235. }
  236. if (getActivity() != null) {
  237. new KeyboardUtils(getActivity(), getView());
  238. }
  239. }
  240. @Override
  241. protected String getTitle() {
  242. return conversationName;
  243. }
  244. @Override
  245. public boolean handleBack() {
  246. if (getRouter().hasRootController()) {
  247. getRouter().popToRoot(new HorizontalChangeHandler());
  248. } else {
  249. getRouter().setRoot(RouterTransaction.with(new MagicBottomNavigationController())
  250. .pushChangeHandler(new HorizontalChangeHandler())
  251. .popChangeHandler(new HorizontalChangeHandler()));
  252. }
  253. return true;
  254. }
  255. @Override
  256. public void onDestroy() {
  257. inChat = false;
  258. dispose();
  259. super.onDestroy();
  260. }
  261. private void dispose() {
  262. Disposable disposable;
  263. for (int i = 0; i < disposableList.size(); i++) {
  264. if ((disposable = disposableList.get(i)).isDisposed()) {
  265. disposable.dispose();
  266. }
  267. }
  268. }
  269. private void joinRoomWithPassword() {
  270. String password = "";
  271. if (TextUtils.isEmpty(roomPassword)) {
  272. password = roomPassword;
  273. }
  274. ncApi.joinRoom(ApiUtils.getCredentials(currentUser.getUserId(), currentUser.getToken()), ApiUtils
  275. .getUrlForRoomParticipants(currentUser.getBaseUrl(), roomToken), password)
  276. .subscribeOn(Schedulers.newThread())
  277. .observeOn(AndroidSchedulers.mainThread())
  278. .retry(3)
  279. .subscribe(new Observer<CallOverall>() {
  280. @Override
  281. public void onSubscribe(Disposable d) {
  282. disposableList.add(d);
  283. }
  284. @Override
  285. public void onNext(CallOverall callOverall) {
  286. inChat = true;
  287. pullChatMessages(0);
  288. currentCall = callOverall.getOcs().getData();
  289. }
  290. @Override
  291. public void onError(Throwable e) {
  292. }
  293. @Override
  294. public void onComplete() {
  295. }
  296. });
  297. }
  298. private void sendMessage(String message) {
  299. Map<String, String> fieldMap = new HashMap<>();
  300. fieldMap.put("message", message);
  301. fieldMap.put("actorDisplayName", currentUser.getDisplayName());
  302. ncApi.sendChatMessage(ApiUtils.getCredentials(currentUser.getUserId(), currentUser.getToken()),
  303. ApiUtils.getUrlForChat(currentUser.getBaseUrl(), roomToken), fieldMap)
  304. .subscribeOn(Schedulers.newThread())
  305. .observeOn(AndroidSchedulers.mainThread())
  306. .retry(3, observable -> inChat)
  307. .subscribe(new Observer<GenericOverall>() {
  308. @Override
  309. public void onSubscribe(Disposable d) {
  310. }
  311. @Override
  312. public void onNext(GenericOverall genericOverall) {
  313. if (popupBubble.isShown()) {
  314. popupBubble.hide();
  315. }
  316. messagesList.smoothScrollToPosition(0);
  317. }
  318. @Override
  319. public void onError(Throwable e) {
  320. }
  321. @Override
  322. public void onComplete() {
  323. }
  324. });
  325. }
  326. private void pullChatMessages(int lookIntoFuture) {
  327. if (!lookingIntoFuture && lookIntoFuture == 1) {
  328. lookingIntoFuture = true;
  329. }
  330. Map<String, Integer> fieldMap = new HashMap<>();
  331. fieldMap.put("lookIntoFuture", lookIntoFuture);
  332. fieldMap.put("limit", 25);
  333. int lastKnown;
  334. if (lookIntoFuture == 1) {
  335. lastKnown = globalLastKnownFutureMessageId;
  336. } else {
  337. lastKnown = globalLastKnownPastMessageId;
  338. }
  339. if (lastKnown != -1) {
  340. fieldMap.put("lastKnownMessageId", lastKnown);
  341. }
  342. if (lookIntoFuture == 1) {
  343. ncApi.pullChatMessages(ApiUtils.getCredentials(currentUser.getUserId(), currentUser.getToken()),
  344. ApiUtils.getUrlForChat(currentUser.getBaseUrl(), roomToken), fieldMap)
  345. .subscribeOn(Schedulers.newThread())
  346. .observeOn(AndroidSchedulers.mainThread())
  347. .takeWhile(observable -> inChat)
  348. .retry(3, observable -> inChat)
  349. .subscribe(new Observer<Response>() {
  350. @Override
  351. public void onSubscribe(Disposable d) {
  352. disposableList.add(d);
  353. }
  354. @Override
  355. public void onNext(Response response) {
  356. processMessages(response, true);
  357. }
  358. @Override
  359. public void onError(Throwable e) {
  360. }
  361. @Override
  362. public void onComplete() {
  363. pullChatMessages(1);
  364. }
  365. });
  366. } else {
  367. ncApi.pullChatMessages(ApiUtils.getCredentials(currentUser.getUserId(), currentUser.getToken()),
  368. ApiUtils.getUrlForChat(currentUser.getBaseUrl(), roomToken), fieldMap)
  369. .subscribeOn(Schedulers.newThread())
  370. .observeOn(AndroidSchedulers.mainThread())
  371. .retry(3, observable -> inChat)
  372. .subscribe(new Observer<Response>() {
  373. @Override
  374. public void onSubscribe(Disposable d) {
  375. disposableList.add(d);
  376. }
  377. @Override
  378. public void onNext(Response response) {
  379. processMessages(response, false);
  380. }
  381. @Override
  382. public void onError(Throwable e) {
  383. }
  384. @Override
  385. public void onComplete() {
  386. }
  387. });
  388. }
  389. }
  390. private void processMessages(Response response, boolean isFromTheFuture) {
  391. if (response.code() == 200) {
  392. ChatOverall chatOverall = (ChatOverall) response.body();
  393. List<ChatMessage> chatMessageList = chatOverall.getOcs().getData();
  394. if (!isFromTheFuture) {
  395. for (int i = 0; i < chatMessageList.size(); i++) {
  396. chatMessageList.get(i).setBaseUrl(currentUser.getBaseUrl());
  397. if (globalLastKnownPastMessageId == -1 || chatMessageList.get(i).getJsonMessageId() <
  398. globalLastKnownPastMessageId) {
  399. globalLastKnownPastMessageId = chatMessageList.get(i).getJsonMessageId();
  400. }
  401. if (globalLastKnownFutureMessageId == -1) {
  402. if (chatMessageList.get(i).getJsonMessageId() > globalLastKnownFutureMessageId) {
  403. globalLastKnownFutureMessageId = chatMessageList.get(i).getJsonMessageId();
  404. }
  405. }
  406. }
  407. adapter.addToEnd(chatMessageList, false);
  408. } else {
  409. for (int i = 0; i < chatMessageList.size(); i++) {
  410. chatMessageList.get(i).setBaseUrl(currentUser.getBaseUrl());
  411. boolean shouldScroll = layoutManager.findFirstVisibleItemPosition() == 0 ||
  412. adapter.getItemCount() == 0;
  413. if (!shouldScroll) {
  414. if (!popupBubble.isShown()) {
  415. newMessagesCount = 1;
  416. popupBubble.show();
  417. } else if (popupBubble.isShown()) {
  418. newMessagesCount++;
  419. }
  420. } else {
  421. newMessagesCount = 0;
  422. }
  423. adapter.addToStart(chatMessageList.get(i), shouldScroll);
  424. }
  425. String xChatLastGivenHeader;
  426. if (response.headers().size() > 0 && !TextUtils.isEmpty((xChatLastGivenHeader = response.headers().get
  427. ("X-Chat-Last-Given")))) {
  428. globalLastKnownFutureMessageId = Integer.parseInt(xChatLastGivenHeader);
  429. }
  430. }
  431. if (!lookingIntoFuture) {
  432. pullChatMessages(1);
  433. }
  434. } else if (response.code() == 304 && !isFromTheFuture) {
  435. historyRead = true;
  436. if (!lookingIntoFuture) {
  437. pullChatMessages(1);
  438. }
  439. }
  440. }
  441. @Override
  442. public void onLoadMore(int page, int totalItemsCount) {
  443. if (!historyRead) {
  444. pullChatMessages(0);
  445. }
  446. }
  447. @Override
  448. public String format(Date date) {
  449. if (DateFormatter.isToday(date)) {
  450. return getResources().getString(R.string.nc_date_header_today);
  451. } else if (DateFormatter.isYesterday(date)) {
  452. return getResources().getString(R.string.nc_date_header_yesterday);
  453. } else {
  454. return DateFormatter.format(date, DateFormatter.Template.STRING_DAY_MONTH_YEAR);
  455. }
  456. }
  457. @Override
  458. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  459. super.onCreateOptionsMenu(menu, inflater);
  460. inflater.inflate(R.menu.menu_conversation, menu);
  461. globalMenu = menu;
  462. }
  463. @Override
  464. public boolean onOptionsItemSelected(@NonNull MenuItem item) {
  465. switch (item.getItemId()) {
  466. case android.R.id.home:
  467. inChat = false;
  468. if (getRouter().hasRootController()) {
  469. getRouter().popToRoot(new HorizontalChangeHandler());
  470. } else {
  471. getRouter().setRoot(RouterTransaction.with(new MagicBottomNavigationController())
  472. .pushChangeHandler(new HorizontalChangeHandler())
  473. .popChangeHandler(new HorizontalChangeHandler()));
  474. }
  475. return true;
  476. case R.id.conversation_video_call:
  477. startActivity(Objects.requireNonNull(getIntentForCall(false)));
  478. return true;
  479. case R.id.conversation_voice_call:
  480. startActivity(Objects.requireNonNull(getIntentForCall(true)));
  481. return true;
  482. default:
  483. return super.onOptionsItemSelected(item);
  484. }
  485. }
  486. private Intent getIntentForCall(boolean isVoiceOnlyCall) {
  487. if (currentCall != null && !TextUtils.isEmpty(currentCall.getSessionId())) {
  488. Bundle bundle = new Bundle();
  489. bundle.putString(BundleKeys.KEY_ROOM_TOKEN, roomToken);
  490. bundle.putParcelable(BundleKeys.KEY_USER_ENTITY, Parcels.wrap(currentUser));
  491. bundle.putString(BundleKeys.KEY_CALL_SESSION, currentCall.getSessionId());
  492. if (isVoiceOnlyCall) {
  493. bundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, true);
  494. }
  495. Intent callIntent = new Intent(getActivity(), CallActivity.class);
  496. callIntent.putExtras(bundle);
  497. return callIntent;
  498. } else {
  499. return null;
  500. }
  501. }
  502. @Override
  503. public void onMessageLongClick(IMessage message) {
  504. if (getActivity() != null) {
  505. ClipboardManager clipboardManager = (android.content.ClipboardManager)
  506. getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
  507. ClipData clipData = android.content.ClipData.newPlainText(
  508. getResources().getString(R.string.nc_app_name), message.getText());
  509. if (clipboardManager != null) {
  510. clipboardManager.setPrimaryClip(clipData);
  511. }
  512. }
  513. }
  514. }