ChatController.java 59 KB

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