ChatController.java 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  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 (!conversationUser.getUserId().equals("?") && conversationUser.hasSpreedFeatureCapability("mention-flag") && getActivity() != null) {
  449. getActivity().findViewById(R.id.toolbar).setOnClickListener(v -> showConversationInfoScreen());
  450. }
  451. if (currentConversation != null) {
  452. loadAvatarForStatusBar();
  453. checkLobbyState();
  454. }
  455. if (adapterWasNull) {
  456. // we're starting
  457. if (TextUtils.isEmpty(roomToken)) {
  458. handleFromNotification();
  459. } else if (TextUtils.isEmpty(conversationName)) {
  460. getRoomInfo();
  461. } else {
  462. setupMentionAutocomplete();
  463. joinRoomWithPassword();
  464. }
  465. }
  466. }
  467. private void checkReadOnlyState() {
  468. if (currentConversation != null) {
  469. if (currentConversation.shouldShowLobby(conversationUser) || (currentConversation.getConversationReadOnlyState() != null && currentConversation.getConversationReadOnlyState().equals(Conversation.ConversationReadOnlyState.CONVERSATION_READ_ONLY))) {
  470. conversationVoiceCallMenuItem.getIcon().setAlpha(99);
  471. conversationVideoMenuItem.getIcon().setAlpha(99);
  472. if (messageInputView != null) {
  473. messageInputView.setVisibility(View.GONE);
  474. }
  475. } else {
  476. if (conversationVoiceCallMenuItem != null) {
  477. conversationVoiceCallMenuItem.getIcon().setAlpha(255);
  478. }
  479. if (conversationVideoMenuItem != null) {
  480. conversationVideoMenuItem.getIcon().setAlpha(255);
  481. }
  482. if (messageInputView != null) {
  483. if (currentConversation.shouldShowLobby(conversationUser)) {
  484. messageInputView.setVisibility(View.GONE);
  485. } else {
  486. messageInputView.setVisibility(View.VISIBLE);
  487. }
  488. }
  489. }
  490. }
  491. }
  492. private void checkLobbyState() {
  493. if (currentConversation != null && currentConversation.isLobbyViewApplicable(conversationUser)) {
  494. if (!checkingLobbyStatus) {
  495. getRoomInfo();
  496. }
  497. if (currentConversation.shouldShowLobby(conversationUser)) {
  498. lobbyView.setVisibility(View.VISIBLE);
  499. messagesListView.setVisibility(View.GONE);
  500. messageInputView.setVisibility(View.GONE);
  501. loadingProgressBar.setVisibility(View.GONE);
  502. if (currentConversation.getLobbyTimer() != null && currentConversation.getLobbyTimer() != 0L) {
  503. conversationLobbyText.setText(String.format(getResources().getString(R.string.nc_lobby_waiting_with_date), DateUtils.INSTANCE.getLocalDateStringFromTimestampForLobby(currentConversation.getLobbyTimer())));
  504. } else {
  505. conversationLobbyText.setText(R.string.nc_lobby_waiting);
  506. }
  507. } else {
  508. lobbyView.setVisibility(View.GONE);
  509. messagesListView.setVisibility(View.VISIBLE);
  510. messageInput.setVisibility(View.VISIBLE);
  511. if (isFirstMessagesProcessing) {
  512. pullChatMessages(0);
  513. } else {
  514. pullChatMessages(1);
  515. }
  516. }
  517. } else {
  518. lobbyView.setVisibility(View.GONE);
  519. messagesListView.setVisibility(View.VISIBLE);
  520. messageInput.setVisibility(View.VISIBLE);
  521. }
  522. }
  523. private void showBrowserScreen(BrowserController.BrowserType browserType) {
  524. Bundle bundle = new Bundle();
  525. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_BROWSER_TYPE(), Parcels.wrap(browserType));
  526. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), Parcels.wrap(conversationUser));
  527. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), roomToken);
  528. getRouter().pushController((RouterTransaction.with(new BrowserController(bundle))
  529. .pushChangeHandler(new VerticalChangeHandler())
  530. .popChangeHandler(new VerticalChangeHandler())));
  531. }
  532. private void showConversationInfoScreen() {
  533. Bundle bundle = new Bundle();
  534. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), conversationUser);
  535. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), roomToken);
  536. getRouter().pushController((RouterTransaction.with(new ConversationInfoController(bundle))
  537. .pushChangeHandler(new HorizontalChangeHandler())
  538. .popChangeHandler(new HorizontalChangeHandler())));
  539. }
  540. private void setupMentionAutocomplete() {
  541. float elevation = 6f;
  542. Drawable backgroundDrawable = new ColorDrawable(getResources().getColor(R.color.bg_default));
  543. AutocompletePresenter<Mention> presenter = new MentionAutocompletePresenter(getApplicationContext(), roomToken);
  544. AutocompleteCallback<Mention> callback = new MentionAutocompleteCallback(getActivity(),
  545. conversationUser, messageInput);
  546. if (mentionAutocomplete == null && messageInput != null) {
  547. mentionAutocomplete = Autocomplete.<Mention>on(messageInput)
  548. .with(elevation)
  549. .with(backgroundDrawable)
  550. .with(new MagicCharPolicy('@'))
  551. .with(presenter)
  552. .with(callback)
  553. .build();
  554. }
  555. }
  556. @Override
  557. protected void onAttach(@NonNull View view) {
  558. super.onAttach(view);
  559. eventBus.register(this);
  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 (conversationUser.hasSpreedFeatureCapability("no-ping")
  613. && getActivity() != null && !getActivity().isChangingConfigurations() && !isLeavingForConversation) {
  614. wasDetached = true;
  615. leaveRoom();
  616. }
  617. if (mentionAutocomplete != null && mentionAutocomplete.isPopupShowing()) {
  618. mentionAutocomplete.dismissPopup();
  619. }
  620. }
  621. @Override
  622. protected String getTitle() {
  623. return String.valueOf(EmojiCompat.get().process(conversationName));
  624. }
  625. @Override
  626. public void onDestroy() {
  627. super.onDestroy();
  628. if (getActivity() != null) {
  629. getActivity().findViewById(R.id.toolbar).setOnClickListener(null);
  630. }
  631. if (getActionBar() != null) {
  632. getActionBar().setIcon(null);
  633. }
  634. adapter = null;
  635. inChat = false;
  636. }
  637. private void dispose() {
  638. Disposable disposable;
  639. for (int i = 0; i < disposableList.size(); i++) {
  640. if (!(disposable = disposableList.get(i)).isDisposed()) {
  641. disposable.dispose();
  642. }
  643. }
  644. }
  645. private void startPing() {
  646. if (!conversationUser.hasSpreedFeatureCapability("no-ping")) {
  647. ncApi.pingCall(credentials, ApiUtils.getUrlForCallPing(conversationUser.getBaseUrl(), roomToken))
  648. .subscribeOn(Schedulers.io())
  649. .observeOn(AndroidSchedulers.mainThread())
  650. .repeatWhen(observable -> observable.delay(5000, TimeUnit.MILLISECONDS))
  651. .takeWhile(observable -> inChat)
  652. .retry(3, observable -> inChat)
  653. .subscribe(new Observer<GenericOverall>() {
  654. @Override
  655. public void onSubscribe(Disposable d) {
  656. disposableList.add(d);
  657. }
  658. @Override
  659. public void onNext(GenericOverall genericOverall) {
  660. }
  661. @Override
  662. public void onError(Throwable e) {
  663. }
  664. @Override
  665. public void onComplete() {
  666. }
  667. });
  668. }
  669. }
  670. @OnClick(R.id.smileyButton)
  671. void onSmileyClick() {
  672. emojiPopup.toggle();
  673. }
  674. private void joinRoomWithPassword() {
  675. if (currentCall == null) {
  676. ncApi.joinRoom(credentials,
  677. ApiUtils.getUrlForSettingMyselfAsActiveParticipant(conversationUser.getBaseUrl(), roomToken), roomPassword)
  678. .subscribeOn(Schedulers.io())
  679. .observeOn(AndroidSchedulers.mainThread())
  680. .retry(3)
  681. .subscribe(new Observer<CallOverall>() {
  682. @Override
  683. public void onSubscribe(Disposable d) {
  684. disposableList.add(d);
  685. }
  686. @Override
  687. public void onNext(CallOverall callOverall) {
  688. inChat = true;
  689. currentCall = callOverall.getOcs().getData();
  690. ApplicationWideCurrentRoomHolder.getInstance().setSession(currentCall.getSessionId());
  691. startPing();
  692. checkLobbyState();
  693. setupWebsocket();
  694. if (isFirstMessagesProcessing) {
  695. pullChatMessages(0);
  696. } else {
  697. pullChatMessages(1);
  698. }
  699. if (magicWebSocketInstance != null) {
  700. magicWebSocketInstance.joinRoomWithRoomTokenAndSession(roomToken,
  701. currentCall.getSessionId());
  702. }
  703. if (startCallFromNotification != null && startCallFromNotification) {
  704. startCallFromNotification = false;
  705. startACall(voiceOnly);
  706. }
  707. }
  708. @Override
  709. public void onError(Throwable e) {
  710. }
  711. @Override
  712. public void onComplete() {
  713. }
  714. });
  715. } else {
  716. inChat = true;
  717. ApplicationWideCurrentRoomHolder.getInstance().setSession(currentCall.getSessionId());
  718. if (magicWebSocketInstance != null) {
  719. magicWebSocketInstance.joinRoomWithRoomTokenAndSession(roomToken,
  720. currentCall.getSessionId());
  721. }
  722. startPing();
  723. if (isFirstMessagesProcessing) {
  724. pullChatMessages(0);
  725. } else {
  726. pullChatMessages(1);
  727. }
  728. }
  729. }
  730. private void leaveRoom() {
  731. ncApi.leaveRoom(credentials,
  732. ApiUtils.getUrlForSettingMyselfAsActiveParticipant(conversationUser.getBaseUrl(),
  733. roomToken))
  734. .subscribeOn(Schedulers.io())
  735. .observeOn(AndroidSchedulers.mainThread())
  736. .subscribe(new Observer<GenericOverall>() {
  737. @Override
  738. public void onSubscribe(Disposable d) {
  739. disposableList.add(d);
  740. }
  741. @Override
  742. public void onNext(GenericOverall genericOverall) {
  743. dispose();
  744. checkingLobbyStatus = false;
  745. if (lobbyTimerHandler != null) {
  746. lobbyTimerHandler.removeCallbacksAndMessages(null);
  747. }
  748. if (magicWebSocketInstance != null && currentCall != null) {
  749. magicWebSocketInstance.joinRoomWithRoomTokenAndSession("", currentCall.getSessionId());
  750. }
  751. if (!isDestroyed() && !isBeingDestroyed() && !wasDetached) {
  752. getRouter().popCurrentController();
  753. }
  754. }
  755. @Override
  756. public void onError(Throwable e) {
  757. }
  758. @Override
  759. public void onComplete() {
  760. dispose();
  761. }
  762. });
  763. }
  764. private void setSenderId() {
  765. try {
  766. final Field senderId = adapter.getClass().getDeclaredField("senderId");
  767. senderId.setAccessible(true);
  768. senderId.set(adapter, conversationUser.getUserId());
  769. } catch (NoSuchFieldException e) {
  770. Log.w(TAG, "Failed to set sender id");
  771. } catch (IllegalAccessException e) {
  772. Log.w(TAG, "Failed to access and set field");
  773. }
  774. }
  775. private void submitMessage() {
  776. final Editable editable = messageInput.getEditableText();
  777. Spans.MentionChipSpan mentionSpans[] = editable.getSpans(0, editable.length(),
  778. Spans.MentionChipSpan.class);
  779. Spans.MentionChipSpan mentionSpan;
  780. for (int i = 0; i < mentionSpans.length; i++) {
  781. mentionSpan = mentionSpans[i];
  782. String mentionId = mentionSpan.getId();
  783. if (mentionId.contains(" ") || mentionId.startsWith("guest/")) {
  784. mentionId = "\"" + mentionId + "\"";
  785. }
  786. editable.replace(editable.getSpanStart(mentionSpan), editable.getSpanEnd(mentionSpan), "@" + mentionId);
  787. }
  788. messageInput.setText("");
  789. sendMessage(editable);
  790. }
  791. private void sendMessage(CharSequence message) {
  792. ncApi.sendChatMessage(credentials, ApiUtils.getUrlForChat(conversationUser.getBaseUrl(), roomToken),
  793. message, conversationUser.getDisplayName())
  794. .subscribeOn(Schedulers.io())
  795. .observeOn(AndroidSchedulers.mainThread())
  796. .subscribe(new Observer<GenericOverall>() {
  797. @Override
  798. public void onSubscribe(Disposable d) {
  799. }
  800. @Override
  801. public void onNext(GenericOverall genericOverall) {
  802. myFirstMessage = message;
  803. if (popupBubble != null && popupBubble.isShown()) {
  804. popupBubble.hide();
  805. }
  806. if (messagesListView != null) {
  807. messagesListView.smoothScrollToPosition(0);
  808. }
  809. }
  810. @Override
  811. public void onError(Throwable e) {
  812. if (e instanceof HttpException) {
  813. int code = ((HttpException) e).code();
  814. if (Integer.toString(code).startsWith("2")) {
  815. myFirstMessage = message;
  816. if (popupBubble != null && popupBubble.isShown()) {
  817. popupBubble.hide();
  818. }
  819. messagesListView.smoothScrollToPosition(0);
  820. }
  821. }
  822. }
  823. @Override
  824. public void onComplete() {
  825. }
  826. });
  827. }
  828. private void setupWebsocket() {
  829. if (WebSocketConnectionHelper.getMagicWebSocketInstanceForUserId(conversationUser.getId()) != null) {
  830. magicWebSocketInstance = WebSocketConnectionHelper.getMagicWebSocketInstanceForUserId(conversationUser.getId());
  831. } else {
  832. magicWebSocketInstance = null;
  833. }
  834. }
  835. private void pullChatMessages(int lookIntoFuture) {
  836. if (!inChat) {
  837. return;
  838. }
  839. if (currentConversation.shouldShowLobby(conversationUser)) {
  840. return;
  841. }
  842. Map<String, Integer> fieldMap = new HashMap<>();
  843. fieldMap.put("includeLastKnown", 0);
  844. if (lookIntoFuture > 0) {
  845. lookingIntoFuture = true;
  846. } else if (isFirstMessagesProcessing) {
  847. globalLastKnownFutureMessageId = currentConversation.getLastReadMessage();
  848. globalLastKnownPastMessageId = currentConversation.getLastReadMessage();
  849. fieldMap.put("includeLastKnown", 1);
  850. }
  851. fieldMap.put("lookIntoFuture", lookIntoFuture);
  852. fieldMap.put("limit", 10);
  853. fieldMap.put("setReadMarker", 1);
  854. int lastKnown;
  855. if (lookIntoFuture > 0) {
  856. lastKnown = globalLastKnownFutureMessageId;
  857. } else {
  858. lastKnown = globalLastKnownPastMessageId;
  859. }
  860. fieldMap.put("lastKnownMessageId", lastKnown);
  861. if (!wasDetached) {
  862. if (lookIntoFuture > 0) {
  863. ncApi.pullChatMessages(credentials, ApiUtils.getUrlForChat(conversationUser.getBaseUrl(),
  864. roomToken),
  865. fieldMap)
  866. .subscribeOn(Schedulers.io())
  867. .observeOn(AndroidSchedulers.mainThread())
  868. .takeWhile(observable -> inChat && !wasDetached)
  869. .subscribe(new Observer<Response>() {
  870. @Override
  871. public void onSubscribe(Disposable d) {
  872. disposableList.add(d);
  873. }
  874. @Override
  875. public void onNext(Response response) {
  876. processMessages(response, true);
  877. }
  878. @Override
  879. public void onError(Throwable e) {
  880. }
  881. @Override
  882. public void onComplete() {
  883. if (!currentConversation.shouldShowLobby(conversationUser)) {
  884. pullChatMessages(1);
  885. }
  886. }
  887. });
  888. } else {
  889. ncApi.pullChatMessages(credentials,
  890. ApiUtils.getUrlForChat(conversationUser.getBaseUrl(), roomToken), fieldMap)
  891. .subscribeOn(Schedulers.io())
  892. .observeOn(AndroidSchedulers.mainThread())
  893. .retry(3, observable -> inChat && !wasDetached)
  894. .takeWhile(observable -> inChat && !wasDetached)
  895. .subscribe(new Observer<Response>() {
  896. @Override
  897. public void onSubscribe(Disposable d) {
  898. disposableList.add(d);
  899. }
  900. @Override
  901. public void onNext(Response response) {
  902. processMessages(response, false);
  903. }
  904. @Override
  905. public void onError(Throwable e) {
  906. }
  907. @Override
  908. public void onComplete() {
  909. }
  910. });
  911. }
  912. }
  913. }
  914. private void processMessages(Response response, boolean isFromTheFuture) {
  915. if (response.code() == 200) {
  916. ChatOverall chatOverall = (ChatOverall) response.body();
  917. List<ChatMessage> chatMessageList = chatOverall.getOcs().getData();
  918. if (isFirstMessagesProcessing) {
  919. cancelNotificationsForCurrentConversation();
  920. isFirstMessagesProcessing = false;
  921. if (loadingProgressBar != null) {
  922. loadingProgressBar.setVisibility(View.GONE);
  923. }
  924. if (messagesListView != null) {
  925. messagesListView.setVisibility(View.VISIBLE);
  926. }
  927. }
  928. int countGroupedMessages = 0;
  929. if (!isFromTheFuture) {
  930. for (int i = 0; i < chatMessageList.size(); i++) {
  931. if (chatMessageList.size() > i + 1) {
  932. if (TextUtils.isEmpty(chatMessageList.get(i).getSystemMessage()) &&
  933. TextUtils.isEmpty(chatMessageList.get(i + 1).getSystemMessage()) &&
  934. chatMessageList.get(i + 1).getActorId().equals(chatMessageList.get(i).getActorId()) &&
  935. countGroupedMessages < 4 && DateFormatter.isSameDay(chatMessageList.get(i).getCreatedAt(),
  936. chatMessageList.get(i + 1).getCreatedAt())) {
  937. chatMessageList.get(i).setGrouped(true);
  938. countGroupedMessages++;
  939. } else {
  940. countGroupedMessages = 0;
  941. }
  942. }
  943. ChatMessage chatMessage = chatMessageList.get(i);
  944. chatMessage.setOneToOneConversation(currentConversation.getType().equals(Conversation.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL));
  945. chatMessage.setLinkPreviewAllowed(isLinkPreviewAllowed);
  946. chatMessage.setActiveUser(conversationUser);
  947. if (globalLastKnownPastMessageId == -1 || chatMessageList.get(i).getJsonMessageId() <
  948. globalLastKnownPastMessageId) {
  949. globalLastKnownPastMessageId = chatMessageList.get(i).getJsonMessageId();
  950. }
  951. if (globalLastKnownFutureMessageId == -1) {
  952. if (chatMessageList.get(i).getJsonMessageId() > globalLastKnownFutureMessageId) {
  953. globalLastKnownFutureMessageId = chatMessageList.get(i).getJsonMessageId();
  954. }
  955. }
  956. }
  957. if (adapter != null) {
  958. adapter.addToEnd(chatMessageList, false);
  959. }
  960. } else {
  961. ChatMessage chatMessage;
  962. for (int i = 0; i < chatMessageList.size(); i++) {
  963. chatMessage = chatMessageList.get(i);
  964. chatMessage.setActiveUser(conversationUser);
  965. chatMessage.setLinkPreviewAllowed(isLinkPreviewAllowed);
  966. // if credentials are empty, we're acting as a guest
  967. if (TextUtils.isEmpty(credentials) && myFirstMessage != null && !TextUtils.isEmpty(myFirstMessage.toString())) {
  968. if (chatMessage.getActorType().equals("guests")) {
  969. conversationUser.setUserId(chatMessage.getActorId());
  970. setSenderId();
  971. }
  972. }
  973. boolean shouldScroll = layoutManager.findFirstVisibleItemPosition() == 0 ||
  974. (adapter != null && adapter.getItemCount() == 0);
  975. if (!shouldScroll && popupBubble != null) {
  976. if (!popupBubble.isShown()) {
  977. newMessagesCount = 1;
  978. popupBubble.show();
  979. } else if (popupBubble.isShown()) {
  980. newMessagesCount++;
  981. }
  982. } else {
  983. newMessagesCount = 0;
  984. }
  985. if (adapter != null) {
  986. chatMessage.setGrouped(adapter.isPreviousSameAuthor(chatMessage.getActorId(), -1) && (adapter.getSameAuthorLastMessagesCount(chatMessage.getActorId()) % 5) > 0);
  987. chatMessage.setOneToOneConversation(currentConversation.getType().equals(Conversation.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL));
  988. adapter.addToStart(chatMessage, shouldScroll);
  989. }
  990. }
  991. String xChatLastGivenHeader;
  992. if (response.headers().size() > 0 && !TextUtils.isEmpty((xChatLastGivenHeader = response.headers().get
  993. ("X-Chat-Last-Given")))) {
  994. if (xChatLastGivenHeader != null) {
  995. globalLastKnownFutureMessageId = Integer.parseInt(xChatLastGivenHeader);
  996. }
  997. }
  998. }
  999. if (!lookingIntoFuture && inChat) {
  1000. pullChatMessages(1);
  1001. }
  1002. } else if (response.code() == 304 && !isFromTheFuture) {
  1003. if (isFirstMessagesProcessing) {
  1004. cancelNotificationsForCurrentConversation();
  1005. isFirstMessagesProcessing = false;
  1006. if (loadingProgressBar != null) {
  1007. loadingProgressBar.setVisibility(View.GONE);
  1008. }
  1009. }
  1010. historyRead = true;
  1011. if (!lookingIntoFuture && inChat) {
  1012. pullChatMessages(1);
  1013. }
  1014. }
  1015. }
  1016. @Override
  1017. public void onLoadMore(int page, int totalItemsCount) {
  1018. if (!historyRead && inChat) {
  1019. pullChatMessages(0);
  1020. }
  1021. }
  1022. @Override
  1023. public String format(Date date) {
  1024. if (DateFormatter.isToday(date)) {
  1025. return getResources().getString(R.string.nc_date_header_today);
  1026. } else if (DateFormatter.isYesterday(date)) {
  1027. return getResources().getString(R.string.nc_date_header_yesterday);
  1028. } else {
  1029. return DateFormatter.format(date, DateFormatter.Template.STRING_DAY_MONTH_YEAR);
  1030. }
  1031. }
  1032. @Override
  1033. public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
  1034. super.onCreateOptionsMenu(menu, inflater);
  1035. inflater.inflate(R.menu.menu_conversation, menu);
  1036. if (conversationUser.getUserId().equals("?")) {
  1037. menu.removeItem(R.id.conversation_info);
  1038. } else {
  1039. conversationInfoMenuItem = menu.findItem(R.id.conversation_info);
  1040. conversationVoiceCallMenuItem = menu.findItem(R.id.conversation_voice_call);
  1041. conversationVideoMenuItem = menu.findItem(R.id.conversation_video_call);
  1042. loadAvatarForStatusBar();
  1043. }
  1044. }
  1045. @Override
  1046. public void onPrepareOptionsMenu(@NonNull Menu menu) {
  1047. super.onPrepareOptionsMenu(menu);
  1048. if (conversationUser.hasSpreedFeatureCapability("read-only-rooms")) {
  1049. checkReadOnlyState();
  1050. }
  1051. }
  1052. @Override
  1053. public boolean onOptionsItemSelected(@NonNull MenuItem item) {
  1054. switch (item.getItemId()) {
  1055. case android.R.id.home:
  1056. getRouter().popCurrentController();
  1057. return true;
  1058. case R.id.conversation_video_call:
  1059. if (conversationVideoMenuItem.getIcon().getAlpha() == 255) {
  1060. startACall(false);
  1061. return true;
  1062. }
  1063. return false;
  1064. case R.id.conversation_voice_call:
  1065. if (conversationVoiceCallMenuItem.getIcon().getAlpha() == 255) {
  1066. startACall(true);
  1067. return true;
  1068. }
  1069. return false;
  1070. case R.id.conversation_info:
  1071. showConversationInfoScreen();
  1072. return true;
  1073. default:
  1074. return super.onOptionsItemSelected(item);
  1075. }
  1076. }
  1077. private void startACall(boolean isVoiceOnlyCall) {
  1078. isLeavingForConversation = true;
  1079. if (!isVoiceOnlyCall) {
  1080. Intent videoCallIntent = getIntentForCall(false);
  1081. if (videoCallIntent != null) {
  1082. startActivity(videoCallIntent);
  1083. }
  1084. } else {
  1085. Intent voiceCallIntent = getIntentForCall(true);
  1086. if (voiceCallIntent != null) {
  1087. startActivity(voiceCallIntent);
  1088. }
  1089. }
  1090. }
  1091. private Intent getIntentForCall(boolean isVoiceOnlyCall) {
  1092. if (currentConversation != null) {
  1093. Bundle bundle = new Bundle();
  1094. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), roomToken);
  1095. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), roomId);
  1096. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), conversationUser);
  1097. bundle.putString(BundleKeys.INSTANCE.getKEY_CONVERSATION_PASSWORD(), roomPassword);
  1098. bundle.putString(BundleKeys.INSTANCE.getKEY_MODIFIED_BASE_URL(), conversationUser.getBaseUrl());
  1099. if (isVoiceOnlyCall) {
  1100. bundle.putBoolean(BundleKeys.INSTANCE.getKEY_CALL_VOICE_ONLY(), true);
  1101. }
  1102. if (getActivity() != null) {
  1103. Intent callIntent = new Intent(getActivity(), MagicCallActivity.class);
  1104. callIntent.putExtras(bundle);
  1105. return callIntent;
  1106. } else {
  1107. return null;
  1108. }
  1109. } else {
  1110. return null;
  1111. }
  1112. }
  1113. @Override
  1114. public void onMessageLongClick(IMessage message) {
  1115. if (getActivity() != null) {
  1116. ClipboardManager clipboardManager = (android.content.ClipboardManager)
  1117. getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
  1118. ClipData clipData = android.content.ClipData.newPlainText(
  1119. getResources().getString(R.string.nc_app_name), message.getText());
  1120. if (clipboardManager != null) {
  1121. clipboardManager.setPrimaryClip(clipData);
  1122. }
  1123. }
  1124. }
  1125. @Override
  1126. public boolean hasContentFor(IMessage message, byte type) {
  1127. switch (type) {
  1128. case CONTENT_TYPE_SYSTEM_MESSAGE:
  1129. return !TextUtils.isEmpty(message.getSystemMessage());
  1130. }
  1131. return false;
  1132. }
  1133. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  1134. public void onMessageEvent(WebSocketCommunicationEvent webSocketCommunicationEvent) {
  1135. /*
  1136. switch (webSocketCommunicationEvent.getType()) {
  1137. case "refreshChat":
  1138. if (webSocketCommunicationEvent.getHashMap().get(BundleKeys.KEY_INTERNAL_USER_ID).equals(Long.toString(conversationUser.getId()))) {
  1139. if (roomToken.equals(webSocketCommunicationEvent.getHashMap().get(BundleKeys.KEY_ROOM_TOKEN))) {
  1140. pullChatMessages(2);
  1141. }
  1142. }
  1143. break;
  1144. default:
  1145. }*/
  1146. }
  1147. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  1148. public void onMessageEvent(UserMentionClickEvent userMentionClickEvent) {
  1149. if ((!currentConversation.getType().equals(Conversation.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL) || !currentConversation.getName().equals(userMentionClickEvent.getUserId()))) {
  1150. RetrofitBucket retrofitBucket =
  1151. ApiUtils.getRetrofitBucketForCreateRoom(conversationUser.getBaseUrl(), "1",
  1152. userMentionClickEvent.getUserId(), null);
  1153. ncApi.createRoom(credentials,
  1154. retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
  1155. .subscribeOn(Schedulers.io())
  1156. .observeOn(AndroidSchedulers.mainThread())
  1157. .subscribe(new Observer<RoomOverall>() {
  1158. @Override
  1159. public void onSubscribe(Disposable d) {
  1160. }
  1161. @Override
  1162. public void onNext(RoomOverall roomOverall) {
  1163. Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class);
  1164. Bundle bundle = new Bundle();
  1165. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), conversationUser);
  1166. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), roomOverall.getOcs().getData().getToken());
  1167. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), roomOverall.getOcs().getData().getRoomId());
  1168. if (conversationUser.hasSpreedFeatureCapability("chat-v2")) {
  1169. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
  1170. Parcels.wrap(roomOverall.getOcs().getData()));
  1171. conversationIntent.putExtras(bundle);
  1172. ConductorRemapping.INSTANCE.remapChatController(getRouter(), conversationUser.getId(),
  1173. roomOverall.getOcs().getData().getToken(), bundle, false);
  1174. } else {
  1175. conversationIntent.putExtras(bundle);
  1176. startActivity(conversationIntent);
  1177. new Handler().postDelayed(new Runnable() {
  1178. @Override
  1179. public void run() {
  1180. if (!isDestroyed() && !isBeingDestroyed()) {
  1181. getRouter().popCurrentController();
  1182. }
  1183. }
  1184. }, 100);
  1185. }
  1186. }
  1187. @Override
  1188. public void onError(Throwable e) {
  1189. }
  1190. @Override
  1191. public void onComplete() {
  1192. }
  1193. });
  1194. }
  1195. }
  1196. }