ChatController.java 21 KB

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