ChatController.java 57 KB

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