ChatController.java 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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.PorterDuff;
  27. import android.graphics.drawable.ColorDrawable;
  28. import android.graphics.drawable.Drawable;
  29. import android.os.Bundle;
  30. import android.os.Handler;
  31. import android.text.Editable;
  32. import android.text.InputFilter;
  33. import android.text.TextUtils;
  34. import android.text.TextWatcher;
  35. import android.util.Log;
  36. import android.view.*;
  37. import android.widget.*;
  38. import androidx.annotation.NonNull;
  39. import androidx.recyclerview.widget.LinearLayoutManager;
  40. import androidx.recyclerview.widget.RecyclerView;
  41. import autodagger.AutoInjector;
  42. import butterknife.BindView;
  43. import butterknife.OnClick;
  44. import com.bluelinelabs.conductor.RouterTransaction;
  45. import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
  46. import com.facebook.drawee.backends.pipeline.Fresco;
  47. import com.facebook.drawee.interfaces.DraweeController;
  48. import com.facebook.drawee.view.SimpleDraweeView;
  49. import com.nextcloud.talk.R;
  50. import com.nextcloud.talk.activities.MagicCallActivity;
  51. import com.nextcloud.talk.adapters.messages.MagicIncomingTextMessageViewHolder;
  52. import com.nextcloud.talk.adapters.messages.MagicOutcomingTextMessageViewHolder;
  53. import com.nextcloud.talk.adapters.messages.MagicPreviewMessageViewHolder;
  54. import com.nextcloud.talk.adapters.messages.MagicSystemMessageViewHolder;
  55. import com.nextcloud.talk.api.NcApi;
  56. import com.nextcloud.talk.application.NextcloudTalkApplication;
  57. import com.nextcloud.talk.callbacks.MentionAutocompleteCallback;
  58. import com.nextcloud.talk.controllers.base.BaseController;
  59. import com.nextcloud.talk.models.database.UserEntity;
  60. import com.nextcloud.talk.models.json.call.Call;
  61. import com.nextcloud.talk.models.json.call.CallOverall;
  62. import com.nextcloud.talk.models.json.chat.ChatMessage;
  63. import com.nextcloud.talk.models.json.chat.ChatOverall;
  64. import com.nextcloud.talk.models.json.generic.GenericOverall;
  65. import com.nextcloud.talk.models.json.mention.Mention;
  66. import com.nextcloud.talk.models.json.rooms.Conversation;
  67. import com.nextcloud.talk.models.json.rooms.RoomOverall;
  68. import com.nextcloud.talk.models.json.rooms.RoomsOverall;
  69. import com.nextcloud.talk.presenters.MentionAutocompletePresenter;
  70. import com.nextcloud.talk.utils.*;
  71. import com.nextcloud.talk.utils.bundle.BundleKeys;
  72. import com.nextcloud.talk.utils.database.user.UserUtils;
  73. import com.nextcloud.talk.utils.preferences.AppPreferences;
  74. import com.nextcloud.talk.utils.singletons.ApplicationWideCurrentRoomHolder;
  75. import com.otaliastudios.autocomplete.Autocomplete;
  76. import com.otaliastudios.autocomplete.AutocompleteCallback;
  77. import com.otaliastudios.autocomplete.AutocompletePresenter;
  78. import com.stfalcon.chatkit.commons.ImageLoader;
  79. import com.stfalcon.chatkit.commons.models.IMessage;
  80. import com.stfalcon.chatkit.messages.MessageHolders;
  81. import com.stfalcon.chatkit.messages.MessageInput;
  82. import com.stfalcon.chatkit.messages.MessagesList;
  83. import com.stfalcon.chatkit.messages.MessagesListAdapter;
  84. import com.stfalcon.chatkit.utils.DateFormatter;
  85. import com.vanniktech.emoji.EmojiEditText;
  86. import com.vanniktech.emoji.EmojiImageView;
  87. import com.vanniktech.emoji.EmojiPopup;
  88. import com.vanniktech.emoji.emoji.Emoji;
  89. import com.vanniktech.emoji.listeners.OnEmojiClickListener;
  90. import com.vanniktech.emoji.listeners.OnEmojiPopupDismissListener;
  91. import com.vanniktech.emoji.listeners.OnEmojiPopupShownListener;
  92. import com.webianks.library.PopupBubble;
  93. import io.reactivex.Observer;
  94. import io.reactivex.android.schedulers.AndroidSchedulers;
  95. import io.reactivex.disposables.Disposable;
  96. import io.reactivex.schedulers.Schedulers;
  97. import org.parceler.Parcels;
  98. import retrofit2.HttpException;
  99. import retrofit2.Response;
  100. import javax.inject.Inject;
  101. import java.lang.reflect.Field;
  102. import java.util.*;
  103. import java.util.concurrent.TimeUnit;
  104. @AutoInjector(NextcloudTalkApplication.class)
  105. public class ChatController extends BaseController implements MessagesListAdapter.OnLoadMoreListener,
  106. MessagesListAdapter.Formatter<Date>, MessagesListAdapter.OnMessageLongClickListener, MessageHolders.ContentChecker {
  107. private static final String TAG = "ChatController";
  108. private static final byte CONTENT_TYPE_SYSTEM_MESSAGE = 1;
  109. @Inject
  110. NcApi ncApi;
  111. @Inject
  112. UserUtils userUtils;
  113. @Inject
  114. AppPreferences appPreferences;
  115. @BindView(R.id.messagesListView)
  116. MessagesList messagesListView;
  117. @BindView(R.id.messageInputView)
  118. MessageInput messageInputView;
  119. @BindView(R.id.messageInput)
  120. EmojiEditText messageInput;
  121. @BindView(R.id.popupBubbleView)
  122. PopupBubble popupBubble;
  123. @BindView(R.id.emptyLayout)
  124. RelativeLayout emptyLayout;
  125. @BindView(R.id.sendHiTextView)
  126. TextView sendHiTextView;
  127. @BindView(R.id.progressBar)
  128. ProgressBar loadingProgressBar;
  129. @BindView(R.id.smileyButton)
  130. ImageButton smileyButton;
  131. private List<Disposable> disposableList = new ArrayList<>();
  132. private String conversationName;
  133. private String roomToken;
  134. private UserEntity conversationUser;
  135. private String roomPassword;
  136. private String credentials;
  137. private Call currentCall;
  138. private boolean inChat = false;
  139. private boolean historyRead = false;
  140. private int globalLastKnownFutureMessageId = -1;
  141. private int globalLastKnownPastMessageId = -1;
  142. private MessagesListAdapter<ChatMessage> adapter;
  143. private Autocomplete mentionAutocomplete;
  144. private LinearLayoutManager layoutManager;
  145. private boolean lookingIntoFuture = false;
  146. private int newMessagesCount = 0;
  147. private Boolean startCallFromNotification = null;
  148. private String roomId;
  149. private boolean voiceOnly;
  150. private boolean isFirstMessagesProcessing = true;
  151. private boolean isHelloClicked;
  152. private boolean isLeavingForConversation;
  153. private boolean isLinkPreviewAllowed;
  154. private boolean wasDetached;
  155. private EmojiPopup emojiPopup;
  156. private CharSequence myFirstMessage;
  157. public ChatController(Bundle args) {
  158. super(args);
  159. setHasOptionsMenu(true);
  160. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  161. this.conversationName = args.getString(BundleKeys.KEY_CONVERSATION_NAME, "");
  162. this.conversationUser = args.getParcelable(BundleKeys.KEY_USER_ENTITY);
  163. this.roomId = args.getString(BundleKeys.KEY_ROOM_ID, "");
  164. this.roomToken = args.getString(BundleKeys.KEY_ROOM_TOKEN, "");
  165. if (args.containsKey(BundleKeys.KEY_ACTIVE_CONVERSATION)) {
  166. this.currentCall = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_ACTIVE_CONVERSATION));
  167. }
  168. this.roomPassword = args.getString(BundleKeys.KEY_CONVERSATION_PASSWORD, "");
  169. if (conversationUser.getUserId().equals("?")) {
  170. credentials = null;
  171. } else {
  172. credentials = ApiUtils.getCredentials(conversationUser.getUsername(), conversationUser.getToken());
  173. }
  174. if (args.containsKey(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL)) {
  175. this.startCallFromNotification = args.getBoolean(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL);
  176. }
  177. this.voiceOnly = args.getBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, false);
  178. }
  179. private void getRoomInfo() {
  180. ncApi.getRoom(credentials, ApiUtils.getRoom(conversationUser.getBaseUrl(), roomToken))
  181. .subscribeOn(Schedulers.newThread())
  182. .observeOn(AndroidSchedulers.mainThread())
  183. .subscribe(new Observer<RoomOverall>() {
  184. @Override
  185. public void onSubscribe(Disposable d) {
  186. disposableList.add(d);
  187. }
  188. @Override
  189. public void onNext(RoomOverall roomOverall) {
  190. conversationName = roomOverall.getOcs().getData().getDisplayName();
  191. setTitle();
  192. setupMentionAutocomplete();
  193. joinRoomWithPassword();
  194. }
  195. @Override
  196. public void onError(Throwable e) {
  197. }
  198. @Override
  199. public void onComplete() {
  200. }
  201. });
  202. }
  203. private void handleFromNotification() {
  204. ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(conversationUser.getBaseUrl()))
  205. .subscribeOn(Schedulers.newThread())
  206. .observeOn(AndroidSchedulers.mainThread())
  207. .subscribe(new Observer<RoomsOverall>() {
  208. @Override
  209. public void onSubscribe(Disposable d) {
  210. disposableList.add(d);
  211. }
  212. @Override
  213. public void onNext(RoomsOverall roomsOverall) {
  214. for (Conversation conversation : roomsOverall.getOcs().getData()) {
  215. if (roomId.equals(conversation.getRoomId())) {
  216. roomToken = conversation.getToken();
  217. conversationName = conversation.getDisplayName();
  218. setTitle();
  219. break;
  220. }
  221. }
  222. if (!TextUtils.isEmpty(roomToken)) {
  223. setupMentionAutocomplete();
  224. joinRoomWithPassword();
  225. }
  226. }
  227. @Override
  228. public void onError(Throwable e) {
  229. }
  230. @Override
  231. public void onComplete() {
  232. }
  233. });
  234. }
  235. @Override
  236. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  237. return inflater.inflate(R.layout.controller_chat, container, false);
  238. }
  239. @Override
  240. protected void onViewBound(@NonNull View view) {
  241. super.onViewBound(view);
  242. getActionBar().show();
  243. boolean adapterWasNull = false;
  244. sendHiTextView.setText(String.format(getResources().getString(R.string.nc_chat_empty), getResources()
  245. .getString(R.string.nc_hello)));
  246. if (adapter == null) {
  247. loadingProgressBar.setVisibility(View.VISIBLE);
  248. adapterWasNull = true;
  249. MessageHolders messageHolders = new MessageHolders();
  250. messageHolders.setIncomingTextConfig(MagicIncomingTextMessageViewHolder.class, R.layout.item_custom_incoming_text_message);
  251. messageHolders.setOutcomingTextConfig(MagicOutcomingTextMessageViewHolder.class, R.layout.item_custom_outcoming_text_message);
  252. messageHolders.setIncomingImageConfig(MagicPreviewMessageViewHolder.class, R.layout.item_custom_incoming_preview_message);
  253. messageHolders.setOutcomingImageConfig(MagicPreviewMessageViewHolder.class, R.layout.item_custom_outcoming_preview_message);
  254. messageHolders.registerContentType(CONTENT_TYPE_SYSTEM_MESSAGE, MagicSystemMessageViewHolder.class,
  255. R.layout.item_system_message, MagicSystemMessageViewHolder.class, R.layout.item_system_message,
  256. this);
  257. adapter = new MessagesListAdapter<>(conversationUser.getUserId(), messageHolders, new ImageLoader() {
  258. @Override
  259. public void loadImage(SimpleDraweeView imageView, String url) {
  260. DraweeController draweeController = Fresco.newDraweeControllerBuilder()
  261. .setImageRequest(DisplayUtils.getImageRequestForUrl(url))
  262. .setControllerListener(DisplayUtils.getImageControllerListener(imageView))
  263. .setOldController(imageView.getController())
  264. .setAutoPlayAnimations(true)
  265. .build();
  266. imageView.setController(draweeController);
  267. }
  268. });
  269. } else {
  270. if (adapter.getItemCount() == 0) {
  271. emptyLayout.setVisibility(View.VISIBLE);
  272. } else {
  273. messagesListView.setVisibility(View.VISIBLE);
  274. }
  275. }
  276. messagesListView.setAdapter(adapter);
  277. adapter.setLoadMoreListener(this);
  278. adapter.setDateHeadersFormatter(this::format);
  279. adapter.setOnMessageLongClickListener(this);
  280. layoutManager = (LinearLayoutManager) messagesListView.getLayoutManager();
  281. popupBubble.setRecyclerView(messagesListView);
  282. popupBubble.setPopupBubbleListener(context -> {
  283. if (newMessagesCount != 0) {
  284. int scrollPosition;
  285. if (newMessagesCount - 1 < 0) {
  286. scrollPosition = 0;
  287. } else {
  288. scrollPosition = newMessagesCount - 1;
  289. }
  290. new Handler().postDelayed(() -> messagesListView.smoothScrollToPosition(scrollPosition), 200);
  291. }
  292. });
  293. messagesListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
  294. @Override
  295. public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
  296. super.onScrollStateChanged(recyclerView, newState);
  297. if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
  298. if (newMessagesCount != 0) {
  299. if (layoutManager.findFirstCompletelyVisibleItemPosition() < newMessagesCount) {
  300. newMessagesCount = 0;
  301. if (popupBubble != null && popupBubble.isShown()) {
  302. popupBubble.hide();
  303. }
  304. }
  305. }
  306. }
  307. }
  308. });
  309. InputFilter[] filters = new InputFilter[1];
  310. filters[0] = new InputFilter.LengthFilter(1000);
  311. messageInput.setFilters(filters);
  312. messageInput.addTextChangedListener(new TextWatcher() {
  313. @Override
  314. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  315. }
  316. @Override
  317. public void onTextChanged(CharSequence s, int start, int before, int count) {
  318. if (s.length() == 1000) {
  319. messageInput.setError(getResources().getString(R.string.nc_limit_hit));
  320. } else {
  321. messageInput.setError(null);
  322. }
  323. }
  324. @Override
  325. public void afterTextChanged(Editable s) {
  326. }
  327. });
  328. messageInputView.setInputListener(input -> {
  329. sendMessage(input);
  330. return true;
  331. });
  332. messageInputView.getButton().setContentDescription(getResources()
  333. .getString(R.string.nc_description_send_message_button));
  334. if (!conversationUser.getUserId().equals("?") && conversationUser.hasSpreedCapabilityWithName("mention-flag") && getActivity() != null) {
  335. getActivity().findViewById(R.id.toolbar).setOnClickListener(v -> showConversationInfoScreen());
  336. }
  337. if (adapterWasNull) {
  338. // we're starting
  339. if (TextUtils.isEmpty(roomToken)) {
  340. handleFromNotification();
  341. } else if (TextUtils.isEmpty(conversationName)) {
  342. getRoomInfo();
  343. } else {
  344. setupMentionAutocomplete();
  345. joinRoomWithPassword();
  346. }
  347. }
  348. }
  349. private void showConversationInfoScreen() {
  350. Bundle bundle = new Bundle();
  351. bundle.putParcelable(BundleKeys.KEY_USER_ENTITY, conversationUser);
  352. bundle.putString(BundleKeys.KEY_BASE_URL, conversationUser.getBaseUrl());
  353. bundle.putString(BundleKeys.KEY_ROOM_TOKEN, roomToken);
  354. getRouter().pushController((RouterTransaction.with(new ConversationInfoController(bundle))
  355. .pushChangeHandler(new HorizontalChangeHandler())
  356. .popChangeHandler(new HorizontalChangeHandler())));
  357. }
  358. private void setupMentionAutocomplete() {
  359. float elevation = 6f;
  360. Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
  361. AutocompletePresenter<Mention> presenter = new MentionAutocompletePresenter(getApplicationContext(), roomToken);
  362. AutocompleteCallback<Mention> callback = new MentionAutocompleteCallback();
  363. if (mentionAutocomplete == null && messageInput != null) {
  364. mentionAutocomplete = Autocomplete.<Mention>on(messageInput)
  365. .with(elevation)
  366. .with(backgroundDrawable)
  367. .with(new MagicCharPolicy('@'))
  368. .with(presenter)
  369. .with(callback)
  370. .build();
  371. }
  372. }
  373. @Override
  374. protected void onAttach(@NonNull View view) {
  375. super.onAttach(view);
  376. isLeavingForConversation = false;
  377. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomId(roomId);
  378. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomToken(roomId);
  379. ApplicationWideCurrentRoomHolder.getInstance().setInCall(false);
  380. ApplicationWideCurrentRoomHolder.getInstance().setUserInRoom(conversationUser);
  381. isLinkPreviewAllowed = appPreferences.getAreLinkPreviewsAllowed();
  382. emojiPopup = EmojiPopup.Builder.fromRootView(view).setOnEmojiPopupShownListener(new OnEmojiPopupShownListener() {
  383. @Override
  384. public void onEmojiPopupShown() {
  385. if (getResources() != null) {
  386. smileyButton.setColorFilter(getResources().getColor(R.color.colorPrimary),
  387. PorterDuff.Mode.SRC_IN);
  388. }
  389. }
  390. }).setOnEmojiPopupDismissListener(new OnEmojiPopupDismissListener() {
  391. @Override
  392. public void onEmojiPopupDismiss() {
  393. if (smileyButton != null) {
  394. smileyButton.clearColorFilter();
  395. }
  396. }
  397. }).setOnEmojiClickListener(new OnEmojiClickListener() {
  398. @Override
  399. public void onEmojiClick(@NonNull EmojiImageView emoji, @NonNull Emoji imageView) {
  400. messageInput.getEditableText().append(" ");
  401. }
  402. }).build(messageInput);
  403. if (mentionAutocomplete != null && mentionAutocomplete.isPopupShowing()) {
  404. mentionAutocomplete.dismissPopup();
  405. }
  406. if (getActivity() != null) {
  407. new KeyboardUtils(getActivity(), getView(), false);
  408. }
  409. NotificationUtils.cancelExistingNotifications(getApplicationContext(), conversationUser);
  410. if (inChat) {
  411. if (wasDetached & conversationUser.hasSpreedCapabilityWithName("no-ping")) {
  412. wasDetached = false;
  413. joinRoomWithPassword();
  414. }
  415. }
  416. }
  417. @Override
  418. protected void onDetach(@NonNull View view) {
  419. super.onDetach(view);
  420. ApplicationWideCurrentRoomHolder.getInstance().clear();
  421. if (conversationUser.hasSpreedCapabilityWithName("no-ping")
  422. && getActivity() != null && !getActivity().isChangingConfigurations() && !isLeavingForConversation) {
  423. wasDetached = true;
  424. leaveRoom();
  425. }
  426. }
  427. @Override
  428. protected String getTitle() {
  429. return conversationName;
  430. }
  431. @Override
  432. public void onDestroy() {
  433. super.onDestroy();
  434. if (getActivity() != null) {
  435. getActivity().findViewById(R.id.toolbar).setOnClickListener(null);
  436. }
  437. adapter = null;
  438. inChat = false;
  439. }
  440. private void dispose() {
  441. Disposable disposable;
  442. for (int i = 0; i < disposableList.size(); i++) {
  443. if (!(disposable = disposableList.get(i)).isDisposed()) {
  444. disposable.dispose();
  445. }
  446. }
  447. }
  448. private void startPing() {
  449. if (!conversationUser.hasSpreedCapabilityWithName("no-ping")) {
  450. ncApi.pingCall(credentials, ApiUtils.getUrlForCallPing(conversationUser.getBaseUrl(), roomToken))
  451. .subscribeOn(Schedulers.newThread())
  452. .observeOn(AndroidSchedulers.mainThread())
  453. .repeatWhen(observable -> observable.delay(5000, TimeUnit.MILLISECONDS))
  454. .takeWhile(observable -> inChat)
  455. .retry(3, observable -> inChat)
  456. .subscribe(new Observer<GenericOverall>() {
  457. @Override
  458. public void onSubscribe(Disposable d) {
  459. disposableList.add(d);
  460. }
  461. @Override
  462. public void onNext(GenericOverall genericOverall) {
  463. }
  464. @Override
  465. public void onError(Throwable e) {
  466. }
  467. @Override
  468. public void onComplete() {
  469. }
  470. });
  471. }
  472. }
  473. @OnClick(R.id.smileyButton)
  474. void onSmileyClick() {
  475. emojiPopup.toggle();
  476. }
  477. @OnClick(R.id.emptyLayout)
  478. void sendHello() {
  479. if (!isHelloClicked) {
  480. isHelloClicked = true;
  481. sendMessage(getResources().getString(R.string.nc_hello) + " 👋");
  482. }
  483. }
  484. private void joinRoomWithPassword() {
  485. if (currentCall == null) {
  486. ncApi.joinRoom(credentials,
  487. ApiUtils.getUrlForSettingMyselfAsActiveParticipant(conversationUser.getBaseUrl(), roomToken), roomPassword)
  488. .subscribeOn(Schedulers.newThread())
  489. .observeOn(AndroidSchedulers.mainThread())
  490. .retry(3)
  491. .subscribe(new Observer<CallOverall>() {
  492. @Override
  493. public void onSubscribe(Disposable d) {
  494. disposableList.add(d);
  495. }
  496. @Override
  497. public void onNext(CallOverall callOverall) {
  498. inChat = true;
  499. currentCall = callOverall.getOcs().getData();
  500. ApplicationWideCurrentRoomHolder.getInstance().setSession(currentCall.getSessionId());
  501. startPing();
  502. if (isFirstMessagesProcessing) {
  503. pullChatMessages(0);
  504. } else {
  505. pullChatMessages(1);
  506. }
  507. if (startCallFromNotification != null && startCallFromNotification) {
  508. startCallFromNotification = false;
  509. startACall(voiceOnly);
  510. }
  511. }
  512. @Override
  513. public void onError(Throwable e) {
  514. }
  515. @Override
  516. public void onComplete() {
  517. }
  518. });
  519. } else {
  520. inChat = true;
  521. ApplicationWideCurrentRoomHolder.getInstance().setSession(currentCall.getSessionId());
  522. startPing();
  523. if (isFirstMessagesProcessing) {
  524. pullChatMessages(0);
  525. } else {
  526. pullChatMessages(1);
  527. }
  528. }
  529. }
  530. private void leaveRoom() {
  531. ncApi.leaveRoom(credentials,
  532. ApiUtils.getUrlForSettingMyselfAsActiveParticipant(conversationUser.getBaseUrl(),
  533. roomToken))
  534. .subscribeOn(Schedulers.newThread())
  535. .observeOn(AndroidSchedulers.mainThread())
  536. .subscribe(new Observer<GenericOverall>() {
  537. @Override
  538. public void onSubscribe(Disposable d) {
  539. disposableList.add(d);
  540. }
  541. @Override
  542. public void onNext(GenericOverall genericOverall) {
  543. dispose();
  544. currentCall = null;
  545. if (!isDestroyed() && !isBeingDestroyed() && !wasDetached) {
  546. getRouter().popCurrentController();
  547. }
  548. }
  549. @Override
  550. public void onError(Throwable e) {
  551. }
  552. @Override
  553. public void onComplete() {
  554. dispose();
  555. }
  556. });
  557. }
  558. private void setSenderId() {
  559. try {
  560. final Field senderId = adapter.getClass().getDeclaredField("senderId");
  561. senderId.setAccessible(true);
  562. senderId.set(adapter, conversationUser.getUserId());
  563. } catch (NoSuchFieldException e) {
  564. Log.w(TAG, "Failed to set sender id");
  565. } catch (IllegalAccessException e) {
  566. Log.w(TAG, "Failed to access and set field");
  567. }
  568. }
  569. private void sendMessage(CharSequence message) {
  570. ncApi.sendChatMessage(credentials, ApiUtils.getUrlForChat(conversationUser.getBaseUrl(), roomToken),
  571. message, conversationUser
  572. .getDisplayName())
  573. .subscribeOn(Schedulers.newThread())
  574. .observeOn(AndroidSchedulers.mainThread())
  575. .subscribe(new Observer<GenericOverall>() {
  576. @Override
  577. public void onSubscribe(Disposable d) {
  578. }
  579. @Override
  580. public void onNext(GenericOverall genericOverall) {
  581. myFirstMessage = message;
  582. if (popupBubble != null && popupBubble.isShown()) {
  583. popupBubble.hide();
  584. }
  585. if (messagesListView != null) {
  586. messagesListView.smoothScrollToPosition(0);
  587. }
  588. }
  589. @Override
  590. public void onError(Throwable e) {
  591. if (e instanceof HttpException) {
  592. int code = ((HttpException) e).code();
  593. if (Integer.toString(code).startsWith("2")) {
  594. myFirstMessage = message;
  595. if (popupBubble != null && popupBubble.isShown()) {
  596. popupBubble.hide();
  597. }
  598. messagesListView.smoothScrollToPosition(0);
  599. }
  600. }
  601. }
  602. @Override
  603. public void onComplete() {
  604. }
  605. });
  606. }
  607. private void pullChatMessages(int lookIntoFuture) {
  608. if (!inChat) {
  609. return;
  610. }
  611. if (!lookingIntoFuture && lookIntoFuture == 1) {
  612. lookingIntoFuture = true;
  613. }
  614. Map<String, Integer> fieldMap = new HashMap<>();
  615. fieldMap.put("lookIntoFuture", lookIntoFuture);
  616. fieldMap.put("limit", 25);
  617. int lastKnown;
  618. if (lookIntoFuture == 1) {
  619. lastKnown = globalLastKnownFutureMessageId;
  620. } else {
  621. lastKnown = globalLastKnownPastMessageId;
  622. }
  623. if (lastKnown != -1) {
  624. fieldMap.put("lastKnownMessageId", lastKnown);
  625. }
  626. if (!wasDetached) {
  627. if (lookIntoFuture == 1) {
  628. ncApi.pullChatMessages(credentials, ApiUtils.getUrlForChat(conversationUser.getBaseUrl(),
  629. roomToken),
  630. fieldMap)
  631. .subscribeOn(Schedulers.newThread())
  632. .observeOn(AndroidSchedulers.mainThread())
  633. .takeWhile(observable -> inChat && !wasDetached)
  634. .retry(3, observable -> inChat && !wasDetached)
  635. .subscribe(new Observer<Response>() {
  636. @Override
  637. public void onSubscribe(Disposable d) {
  638. disposableList.add(d);
  639. }
  640. @Override
  641. public void onNext(Response response) {
  642. processMessages(response, true);
  643. }
  644. @Override
  645. public void onError(Throwable e) {
  646. }
  647. @Override
  648. public void onComplete() {
  649. pullChatMessages(1);
  650. }
  651. });
  652. } else {
  653. ncApi.pullChatMessages(credentials,
  654. ApiUtils.getUrlForChat(conversationUser.getBaseUrl(), roomToken), fieldMap)
  655. .subscribeOn(Schedulers.newThread())
  656. .observeOn(AndroidSchedulers.mainThread())
  657. .retry(3, observable -> inChat && !wasDetached)
  658. .takeWhile(observable -> inChat && !wasDetached)
  659. .subscribe(new Observer<Response>() {
  660. @Override
  661. public void onSubscribe(Disposable d) {
  662. disposableList.add(d);
  663. }
  664. @Override
  665. public void onNext(Response response) {
  666. processMessages(response, false);
  667. }
  668. @Override
  669. public void onError(Throwable e) {
  670. }
  671. @Override
  672. public void onComplete() {
  673. }
  674. });
  675. }
  676. }
  677. }
  678. private void processMessages(Response response, boolean isFromTheFuture) {
  679. if (response.code() == 200) {
  680. ChatOverall chatOverall = (ChatOverall) response.body();
  681. List<ChatMessage> chatMessageList = chatOverall.getOcs().getData();
  682. if (isFirstMessagesProcessing) {
  683. NotificationUtils.cancelExistingNotifications(getApplicationContext(), conversationUser);
  684. isFirstMessagesProcessing = false;
  685. if (loadingProgressBar != null) {
  686. loadingProgressBar.setVisibility(View.GONE);
  687. }
  688. if (chatMessageList.size() == 0) {
  689. if (emptyLayout != null) {
  690. emptyLayout.setVisibility(View.VISIBLE);
  691. }
  692. if (messagesListView != null) {
  693. messagesListView.setVisibility(View.GONE);
  694. }
  695. } else {
  696. if (emptyLayout != null) {
  697. emptyLayout.setVisibility(View.GONE);
  698. }
  699. if (messagesListView != null) {
  700. messagesListView.setVisibility(View.VISIBLE);
  701. }
  702. }
  703. } else {
  704. if (emptyLayout != null) {
  705. emptyLayout.setVisibility(View.GONE);
  706. }
  707. if (messagesListView != null) {
  708. messagesListView.setVisibility(View.VISIBLE);
  709. }
  710. }
  711. int countGroupedMessages = 0;
  712. if (!isFromTheFuture) {
  713. for (int i = 0; i < chatMessageList.size(); i++) {
  714. if (chatMessageList.size() > i + 1) {
  715. if (TextUtils.isEmpty(chatMessageList.get(i).getSystemMessage()) &&
  716. TextUtils.isEmpty(chatMessageList.get(i + 1).getSystemMessage()) &&
  717. chatMessageList.get(i + 1).getActorId().equals(chatMessageList.get(i).getActorId()) &&
  718. countGroupedMessages < 4 && DateFormatter.isSameDay(chatMessageList.get(i).getCreatedAt(),
  719. chatMessageList.get(i + 1).getCreatedAt())) {
  720. chatMessageList.get(i).setGrouped(true);
  721. countGroupedMessages++;
  722. } else {
  723. countGroupedMessages = 0;
  724. }
  725. }
  726. ChatMessage chatMessage = chatMessageList.get(i);
  727. chatMessage.setLinkPreviewAllowed(isLinkPreviewAllowed);
  728. chatMessage.setBaseUrl(conversationUser.getBaseUrl());
  729. chatMessage.setActiveUserId(conversationUser.getUserId());
  730. if (globalLastKnownPastMessageId == -1 || chatMessageList.get(i).getJsonMessageId() <
  731. globalLastKnownPastMessageId) {
  732. globalLastKnownPastMessageId = chatMessageList.get(i).getJsonMessageId();
  733. }
  734. if (globalLastKnownFutureMessageId == -1) {
  735. if (chatMessageList.get(i).getJsonMessageId() > globalLastKnownFutureMessageId) {
  736. globalLastKnownFutureMessageId = chatMessageList.get(i).getJsonMessageId();
  737. }
  738. }
  739. }
  740. if (adapter != null) {
  741. adapter.addToEnd(chatMessageList, false);
  742. }
  743. } else {
  744. ChatMessage chatMessage;
  745. for (int i = 0; i < chatMessageList.size(); i++) {
  746. chatMessage = chatMessageList.get(i);
  747. chatMessage.setBaseUrl(conversationUser.getBaseUrl());
  748. chatMessage.setActiveUserId(conversationUser.getUserId());
  749. chatMessage.setLinkPreviewAllowed(isLinkPreviewAllowed);
  750. // if credentials are empty, we're acting as a guest
  751. if (TextUtils.isEmpty(credentials) && myFirstMessage != null && !TextUtils.isEmpty(myFirstMessage.toString())) {
  752. if (chatMessage.getActorType().equals("guests")) {
  753. conversationUser.setUserId(chatMessage.getActorId());
  754. setSenderId();
  755. }
  756. }
  757. boolean shouldScroll = layoutManager.findFirstVisibleItemPosition() == 0 ||
  758. (adapter != null && adapter.getItemCount() == 0);
  759. if (!shouldScroll && popupBubble != null) {
  760. if (!popupBubble.isShown()) {
  761. newMessagesCount = 1;
  762. popupBubble.show();
  763. } else if (popupBubble.isShown()) {
  764. newMessagesCount++;
  765. }
  766. } else {
  767. newMessagesCount = 0;
  768. }
  769. chatMessage.setGrouped(adapter.isPreviousSameAuthor(chatMessage.getActorId(), -1) && (adapter.getSameAuthorLastMessagesCount(chatMessage.getActorId()) % 5) > 0);
  770. adapter.addToStart(chatMessage, shouldScroll);
  771. }
  772. String xChatLastGivenHeader;
  773. if (response.headers().size() > 0 && !TextUtils.isEmpty((xChatLastGivenHeader = response.headers().get
  774. ("X-Chat-Last-Given")))) {
  775. globalLastKnownFutureMessageId = Integer.parseInt(xChatLastGivenHeader);
  776. }
  777. }
  778. if (!lookingIntoFuture && inChat) {
  779. pullChatMessages(1);
  780. }
  781. } else if (response.code() == 304 && !isFromTheFuture) {
  782. if (isFirstMessagesProcessing) {
  783. NotificationUtils.cancelExistingNotifications(getApplicationContext(), conversationUser);
  784. isFirstMessagesProcessing = false;
  785. if (loadingProgressBar != null) {
  786. loadingProgressBar.setVisibility(View.GONE);
  787. }
  788. if (emptyLayout != null && emptyLayout.getVisibility() != View.VISIBLE) {
  789. emptyLayout.setVisibility(View.VISIBLE);
  790. }
  791. }
  792. historyRead = true;
  793. if (!lookingIntoFuture && inChat) {
  794. pullChatMessages(1);
  795. }
  796. }
  797. }
  798. @Override
  799. public void onLoadMore(int page, int totalItemsCount) {
  800. if (!historyRead && inChat) {
  801. pullChatMessages(0);
  802. }
  803. }
  804. @Override
  805. public String format(Date date) {
  806. if (DateFormatter.isToday(date)) {
  807. return getResources().getString(R.string.nc_date_header_today);
  808. } else if (DateFormatter.isYesterday(date)) {
  809. return getResources().getString(R.string.nc_date_header_yesterday);
  810. } else {
  811. return DateFormatter.format(date, DateFormatter.Template.STRING_DAY_MONTH_YEAR);
  812. }
  813. }
  814. @Override
  815. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  816. super.onCreateOptionsMenu(menu, inflater);
  817. inflater.inflate(R.menu.menu_conversation, menu);
  818. if (conversationUser.getUserId().equals("?")) {
  819. menu.removeItem(R.id.conversation_info);
  820. }
  821. }
  822. @Override
  823. public boolean onOptionsItemSelected(@NonNull MenuItem item) {
  824. switch (item.getItemId()) {
  825. case android.R.id.home:
  826. getRouter().popCurrentController();
  827. return true;
  828. case R.id.conversation_video_call:
  829. startACall(false);
  830. return true;
  831. case R.id.conversation_voice_call:
  832. startACall(true);
  833. return true;
  834. case R.id.conversation_info:
  835. showConversationInfoScreen();
  836. return true;
  837. default:
  838. return super.onOptionsItemSelected(item);
  839. }
  840. }
  841. private void startACall(boolean isVoiceOnlyCall) {
  842. isLeavingForConversation = true;
  843. if (!isVoiceOnlyCall) {
  844. Intent videoCallIntent = getIntentForCall(false);
  845. if (videoCallIntent != null) {
  846. startActivity(videoCallIntent);
  847. }
  848. } else {
  849. Intent voiceCallIntent = getIntentForCall(true);
  850. if (voiceCallIntent != null) {
  851. startActivity(voiceCallIntent);
  852. }
  853. }
  854. }
  855. private Intent getIntentForCall(boolean isVoiceOnlyCall) {
  856. if (currentCall != null) {
  857. Bundle bundle = new Bundle();
  858. bundle.putString(BundleKeys.KEY_ROOM_TOKEN, roomToken);
  859. bundle.putString(BundleKeys.KEY_ROOM_ID, roomId);
  860. bundle.putParcelable(BundleKeys.KEY_USER_ENTITY, conversationUser);
  861. bundle.putString(BundleKeys.KEY_CONVERSATION_PASSWORD, roomPassword);
  862. bundle.putString(BundleKeys.KEY_MODIFIED_BASE_URL, conversationUser.getBaseUrl());
  863. if (isVoiceOnlyCall) {
  864. bundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, true);
  865. }
  866. if (getActivity() != null) {
  867. Intent callIntent = new Intent(getActivity(), MagicCallActivity.class);
  868. callIntent.putExtras(bundle);
  869. return callIntent;
  870. } else {
  871. return null;
  872. }
  873. } else {
  874. return null;
  875. }
  876. }
  877. @Override
  878. public void onMessageLongClick(IMessage message) {
  879. if (getActivity() != null) {
  880. ClipboardManager clipboardManager = (android.content.ClipboardManager)
  881. getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
  882. ClipData clipData = android.content.ClipData.newPlainText(
  883. getResources().getString(R.string.nc_app_name), message.getText());
  884. if (clipboardManager != null) {
  885. clipboardManager.setPrimaryClip(clipData);
  886. }
  887. }
  888. }
  889. @Override
  890. public boolean hasContentFor(IMessage message, byte type) {
  891. switch (type) {
  892. case CONTENT_TYPE_SYSTEM_MESSAGE:
  893. return !TextUtils.isEmpty(message.getSystemMessage());
  894. }
  895. return false;
  896. }
  897. }