ChatController.java 50 KB

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