ChatController.java 57 KB

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