ChatController.java 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017-2018 Mario Danic <mario@lovelyhq.com>
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.nextcloud.talk.controllers;
  21. import android.content.ClipData;
  22. import android.content.ClipboardManager;
  23. import android.content.Context;
  24. import android.content.Intent;
  25. import android.graphics.Color;
  26. import android.graphics.drawable.ColorDrawable;
  27. import android.graphics.drawable.Drawable;
  28. import android.net.Uri;
  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.ProgressBar;
  44. import android.widget.RelativeLayout;
  45. import android.widget.TextView;
  46. import com.bluelinelabs.conductor.RouterTransaction;
  47. import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
  48. import com.facebook.drawee.backends.pipeline.Fresco;
  49. import com.facebook.drawee.interfaces.DraweeController;
  50. import com.facebook.drawee.view.SimpleDraweeView;
  51. import com.facebook.imagepipeline.common.RotationOptions;
  52. import com.facebook.imagepipeline.request.ImageRequest;
  53. import com.facebook.imagepipeline.request.ImageRequestBuilder;
  54. import com.nextcloud.talk.R;
  55. import com.nextcloud.talk.activities.MagicCallActivity;
  56. import com.nextcloud.talk.adapters.messages.MagicIncomingTextMessageViewHolder;
  57. import com.nextcloud.talk.adapters.messages.MagicOutcomingTextMessageViewHolder;
  58. import com.nextcloud.talk.adapters.messages.MagicPreviewMessageViewHolder;
  59. import com.nextcloud.talk.adapters.messages.MagicSystemMessageViewHolder;
  60. import com.nextcloud.talk.api.NcApi;
  61. import com.nextcloud.talk.application.NextcloudTalkApplication;
  62. import com.nextcloud.talk.callbacks.MentionAutocompleteCallback;
  63. import com.nextcloud.talk.controllers.base.BaseController;
  64. import com.nextcloud.talk.models.database.UserEntity;
  65. import com.nextcloud.talk.models.json.call.Call;
  66. import com.nextcloud.talk.models.json.call.CallOverall;
  67. import com.nextcloud.talk.models.json.chat.ChatMessage;
  68. import com.nextcloud.talk.models.json.chat.ChatOverall;
  69. import com.nextcloud.talk.models.json.generic.GenericOverall;
  70. import com.nextcloud.talk.models.json.mention.Mention;
  71. import com.nextcloud.talk.models.json.rooms.Conversation;
  72. import com.nextcloud.talk.models.json.rooms.RoomOverall;
  73. import com.nextcloud.talk.models.json.rooms.RoomsOverall;
  74. import com.nextcloud.talk.presenters.MentionAutocompletePresenter;
  75. import com.nextcloud.talk.utils.ApiUtils;
  76. import com.nextcloud.talk.utils.DisplayUtils;
  77. import com.nextcloud.talk.utils.KeyboardUtils;
  78. import com.nextcloud.talk.utils.NotificationUtils;
  79. import com.nextcloud.talk.utils.bundle.BundleKeys;
  80. import com.nextcloud.talk.utils.database.user.UserUtils;
  81. import com.nextcloud.talk.utils.singletons.ApplicationWideCurrentRoomHolder;
  82. import com.otaliastudios.autocomplete.Autocomplete;
  83. import com.otaliastudios.autocomplete.AutocompleteCallback;
  84. import com.otaliastudios.autocomplete.AutocompletePresenter;
  85. import com.otaliastudios.autocomplete.CharPolicy;
  86. import com.stfalcon.chatkit.commons.ImageLoader;
  87. import com.stfalcon.chatkit.commons.models.IMessage;
  88. import com.stfalcon.chatkit.messages.MessageHolders;
  89. import com.stfalcon.chatkit.messages.MessageInput;
  90. import com.stfalcon.chatkit.messages.MessagesList;
  91. import com.stfalcon.chatkit.messages.MessagesListAdapter;
  92. import com.stfalcon.chatkit.utils.DateFormatter;
  93. import com.webianks.library.PopupBubble;
  94. import org.parceler.Parcels;
  95. import java.lang.reflect.Field;
  96. import java.util.ArrayList;
  97. import java.util.Date;
  98. import java.util.HashMap;
  99. import java.util.List;
  100. import java.util.Map;
  101. import java.util.concurrent.TimeUnit;
  102. import javax.inject.Inject;
  103. import androidx.annotation.NonNull;
  104. import androidx.recyclerview.widget.LinearLayoutManager;
  105. import androidx.recyclerview.widget.RecyclerView;
  106. import autodagger.AutoInjector;
  107. import butterknife.BindView;
  108. import butterknife.OnClick;
  109. import io.reactivex.Observer;
  110. import io.reactivex.android.schedulers.AndroidSchedulers;
  111. import io.reactivex.disposables.Disposable;
  112. import io.reactivex.schedulers.Schedulers;
  113. import retrofit2.HttpException;
  114. import retrofit2.Response;
  115. @AutoInjector(NextcloudTalkApplication.class)
  116. public class ChatController extends BaseController implements MessagesListAdapter.OnLoadMoreListener,
  117. MessagesListAdapter.Formatter<Date>, MessagesListAdapter.OnMessageLongClickListener, MessageHolders.ContentChecker {
  118. private static final String TAG = "ChatController";
  119. @Inject
  120. NcApi ncApi;
  121. @Inject
  122. UserUtils userUtils;
  123. @BindView(R.id.messagesListView)
  124. MessagesList messagesListView;
  125. @BindView(R.id.messageInputView)
  126. MessageInput messageInputView;
  127. @BindView(R.id.popupBubbleView)
  128. PopupBubble popupBubble;
  129. @BindView(R.id.emptyLayout)
  130. RelativeLayout emptyLayout;
  131. @BindView(R.id.sendHiTextView)
  132. TextView sendHiTextView;
  133. @BindView(R.id.progressBar)
  134. ProgressBar loadingProgressBar;
  135. private List<Disposable> disposableList = new ArrayList<>();
  136. private String conversationName;
  137. private String roomToken;
  138. private UserEntity conversationUser;
  139. private String roomPassword;
  140. private String credentials;
  141. private String baseUrl;
  142. private Call currentCall;
  143. private boolean inChat = false;
  144. private boolean historyRead = false;
  145. private int globalLastKnownFutureMessageId = -1;
  146. private int globalLastKnownPastMessageId = -1;
  147. private MessagesListAdapter<ChatMessage> adapter;
  148. private CharSequence myFirstMessage;
  149. private Autocomplete mentionAutocomplete;
  150. private LinearLayoutManager layoutManager;
  151. private boolean lookingIntoFuture = false;
  152. private int newMessagesCount = 0;
  153. private Boolean startCallFromNotification = null;
  154. private String roomId;
  155. private boolean voiceOnly;
  156. private boolean isFirstMessagesProcessing = true;
  157. private boolean isHelloClicked;
  158. private boolean isLeavingForConversation;
  159. private static final byte CONTENT_TYPE_SYSTEM_MESSAGE = 1;
  160. private boolean wasDetached;
  161. public ChatController(Bundle args) {
  162. super(args);
  163. setHasOptionsMenu(true);
  164. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  165. UserEntity currentUser = userUtils.getCurrentUser();
  166. this.conversationName = args.getString(BundleKeys.KEY_CONVERSATION_NAME, "");
  167. if (args.containsKey(BundleKeys.KEY_USER_ENTITY)) {
  168. this.conversationUser = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_USER_ENTITY));
  169. } else {
  170. this.conversationUser = currentUser;
  171. }
  172. this.roomId = args.getString(BundleKeys.KEY_ROOM_ID, "");
  173. this.roomToken = args.getString(BundleKeys.KEY_ROOM_TOKEN, "");
  174. if (args.containsKey(BundleKeys.KEY_ACTIVE_CONVERSATION)) {
  175. this.currentCall = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_ACTIVE_CONVERSATION));
  176. }
  177. this.baseUrl = args.getString(BundleKeys.KEY_MODIFIED_BASE_URL, "");
  178. if (!TextUtils.isEmpty(baseUrl)) {
  179. conversationUser.setBaseUrl(baseUrl);
  180. conversationUser.setUserId("?");
  181. conversationUser.setDisplayName(currentUser.getDisplayName());
  182. } else {
  183. baseUrl = conversationUser.getBaseUrl();
  184. }
  185. this.roomPassword = args.getString(BundleKeys.KEY_CONVERSATION_PASSWORD, "");
  186. if (conversationUser.getUserId().equals("?")) {
  187. credentials = null;
  188. } else {
  189. credentials = ApiUtils.getCredentials(conversationUser.getUsername(), conversationUser.getToken());
  190. }
  191. if (args.containsKey(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL)) {
  192. this.startCallFromNotification = args.getBoolean(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL);
  193. }
  194. this.voiceOnly = args.getBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, false);
  195. }
  196. private void getRoomInfo() {
  197. ncApi.getRoom(credentials, ApiUtils.getRoom(baseUrl, roomToken))
  198. .subscribeOn(Schedulers.newThread())
  199. .observeOn(AndroidSchedulers.mainThread())
  200. .subscribe(new Observer<RoomOverall>() {
  201. @Override
  202. public void onSubscribe(Disposable d) {
  203. disposableList.add(d);
  204. }
  205. @Override
  206. public void onNext(RoomOverall roomOverall) {
  207. conversationName = roomOverall.getOcs().getData().getDisplayName();
  208. setTitle();
  209. setupMentionAutocomplete();
  210. joinRoomWithPassword();
  211. }
  212. @Override
  213. public void onError(Throwable e) {
  214. }
  215. @Override
  216. public void onComplete() {
  217. }
  218. });
  219. }
  220. private void handleFromNotification() {
  221. ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(baseUrl))
  222. .subscribeOn(Schedulers.newThread())
  223. .observeOn(AndroidSchedulers.mainThread())
  224. .subscribe(new Observer<RoomsOverall>() {
  225. @Override
  226. public void onSubscribe(Disposable d) {
  227. disposableList.add(d);
  228. }
  229. @Override
  230. public void onNext(RoomsOverall roomsOverall) {
  231. for (Conversation conversation : roomsOverall.getOcs().getData()) {
  232. if (roomId.equals(conversation.getRoomId())) {
  233. roomToken = conversation.getToken();
  234. conversationName = conversation.getDisplayName();
  235. setTitle();
  236. break;
  237. }
  238. }
  239. if (!TextUtils.isEmpty(roomToken)) {
  240. setupMentionAutocomplete();
  241. joinRoomWithPassword();
  242. }
  243. }
  244. @Override
  245. public void onError(Throwable e) {
  246. }
  247. @Override
  248. public void onComplete() {
  249. }
  250. });
  251. }
  252. @Override
  253. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  254. return inflater.inflate(R.layout.controller_chat, container, false);
  255. }
  256. @Override
  257. protected void onViewBound(@NonNull View view) {
  258. super.onViewBound(view);
  259. getActionBar().show();
  260. boolean adapterWasNull = false;
  261. sendHiTextView.setText(String.format(getResources().getString(R.string.nc_chat_empty), getResources()
  262. .getString(R.string.nc_hello)));
  263. if (adapter == null) {
  264. loadingProgressBar.setVisibility(View.VISIBLE);
  265. adapterWasNull = true;
  266. MessageHolders messageHolders = new MessageHolders();
  267. messageHolders.setIncomingTextConfig(MagicIncomingTextMessageViewHolder.class, R.layout.item_custom_incoming_text_message);
  268. messageHolders.setOutcomingTextConfig(MagicOutcomingTextMessageViewHolder.class, R.layout.item_custom_outcoming_text_message);
  269. messageHolders.setIncomingImageConfig(MagicPreviewMessageViewHolder.class, R.layout.item_custom_incoming_preview_message);
  270. messageHolders.setOutcomingImageConfig(MagicPreviewMessageViewHolder.class, R.layout.item_custom_outcoming_preview_message);
  271. messageHolders.registerContentType(CONTENT_TYPE_SYSTEM_MESSAGE, MagicSystemMessageViewHolder.class,
  272. R.layout.item_system_message, MagicSystemMessageViewHolder.class, R.layout.item_system_message,
  273. this);
  274. adapter = new MessagesListAdapter<>(conversationUser.getUserId(), messageHolders, new ImageLoader() {
  275. @Override
  276. public void loadImage(SimpleDraweeView imageView, String url) {
  277. ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
  278. .setProgressiveRenderingEnabled(true)
  279. .setRotationOptions(RotationOptions.autoRotate())
  280. .disableDiskCache()
  281. .build();
  282. DraweeController draweeController = Fresco.newDraweeControllerBuilder()
  283. .setImageRequest(request)
  284. .setControllerListener(DisplayUtils.getImageControllerListener(imageView))
  285. .setOldController(imageView.getController())
  286. .setAutoPlayAnimations(true)
  287. .build();
  288. imageView.setController(draweeController);
  289. }
  290. });
  291. } else {
  292. if (adapter.getItemCount() == 0) {
  293. emptyLayout.setVisibility(View.VISIBLE);
  294. } else {
  295. messagesListView.setVisibility(View.VISIBLE);
  296. }
  297. }
  298. messagesListView.setAdapter(adapter);
  299. adapter.setLoadMoreListener(this);
  300. adapter.setDateHeadersFormatter(this::format);
  301. adapter.setOnMessageLongClickListener(this);
  302. layoutManager = (LinearLayoutManager) messagesListView.getLayoutManager();
  303. popupBubble.setRecyclerView(messagesListView);
  304. popupBubble.setPopupBubbleListener(context -> {
  305. if (newMessagesCount != 0) {
  306. int scrollPosition;
  307. if (newMessagesCount - 1 < 0) {
  308. scrollPosition = 0;
  309. } else {
  310. scrollPosition = newMessagesCount - 1;
  311. }
  312. new Handler().postDelayed(() -> messagesListView.smoothScrollToPosition(scrollPosition), 200);
  313. }
  314. });
  315. messagesListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
  316. @Override
  317. public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
  318. super.onScrollStateChanged(recyclerView, newState);
  319. if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
  320. if (newMessagesCount != 0) {
  321. if (layoutManager.findFirstCompletelyVisibleItemPosition() < newMessagesCount) {
  322. newMessagesCount = 0;
  323. if (popupBubble != null && popupBubble.isShown()) {
  324. popupBubble.hide();
  325. }
  326. }
  327. }
  328. }
  329. }
  330. });
  331. InputFilter[] filters = new InputFilter[1];
  332. filters[0] = new InputFilter.LengthFilter(1000);
  333. messageInputView.getInputEditText().setFilters(filters);
  334. messageInputView.getInputEditText().addTextChangedListener(new TextWatcher() {
  335. @Override
  336. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  337. }
  338. @Override
  339. public void onTextChanged(CharSequence s, int start, int before, int count) {
  340. if (s.length() == 1000) {
  341. messageInputView.getInputEditText().setError(getResources().getString(R.string.nc_limit_hit));
  342. } else {
  343. messageInputView.getInputEditText().setError(null);
  344. }
  345. }
  346. @Override
  347. public void afterTextChanged(Editable s) {
  348. }
  349. });
  350. messageInputView.setInputListener(input -> {
  351. sendMessage(input, 1);
  352. return true;
  353. });
  354. messageInputView.getButton().setContentDescription(getResources()
  355. .getString(R.string.nc_description_send_message_button));
  356. if (conversationUser.hasSpreedCapabilityWithName("mention-flag") && getActivity() != null) {
  357. getActivity().findViewById(R.id.toolbar).setOnClickListener(v -> showConversationInfoScreen());
  358. }
  359. if (adapterWasNull) {
  360. // we're starting
  361. if (TextUtils.isEmpty(roomToken)) {
  362. handleFromNotification();
  363. } else if (TextUtils.isEmpty(conversationName)) {
  364. getRoomInfo();
  365. } else {
  366. setupMentionAutocomplete();
  367. joinRoomWithPassword();
  368. }
  369. }
  370. }
  371. private void showConversationInfoScreen() {
  372. Bundle bundle = new Bundle();
  373. bundle.putParcelable(BundleKeys.KEY_USER_ENTITY, Parcels.wrap(conversationUser));
  374. bundle.putString(BundleKeys.KEY_BASE_URL, baseUrl);
  375. bundle.putString(BundleKeys.KEY_ROOM_TOKEN, roomToken);
  376. getRouter().pushController((RouterTransaction.with(new ConversationInfoController(bundle))
  377. .pushChangeHandler(new HorizontalChangeHandler())
  378. .popChangeHandler(new HorizontalChangeHandler())));
  379. }
  380. private void setupMentionAutocomplete() {
  381. float elevation = 6f;
  382. Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
  383. AutocompletePresenter<Mention> presenter = new MentionAutocompletePresenter(getApplicationContext(), roomToken);
  384. AutocompleteCallback<Mention> callback = new MentionAutocompleteCallback();
  385. if (messageInputView != null && messageInputView.getInputEditText() != null) {
  386. mentionAutocomplete = Autocomplete.<Mention>on(messageInputView.getInputEditText())
  387. .with(elevation)
  388. .with(backgroundDrawable)
  389. .with(new CharPolicy('@'))
  390. .with(presenter)
  391. .with(callback)
  392. .build();
  393. }
  394. }
  395. @Override
  396. protected void onAttach(@NonNull View view) {
  397. super.onAttach(view);
  398. isLeavingForConversation = false;
  399. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomId(roomId);
  400. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomToken(roomId);
  401. ApplicationWideCurrentRoomHolder.getInstance().setInCall(false);
  402. ApplicationWideCurrentRoomHolder.getInstance().setUserInRoom(conversationUser);
  403. if (mentionAutocomplete != null && mentionAutocomplete.isPopupShowing()) {
  404. mentionAutocomplete.dismissPopup();
  405. }
  406. if (getActivity() != null) {
  407. new KeyboardUtils(getActivity(), getView(), false);
  408. }
  409. NotificationUtils.cancelExistingNotifications(getApplicationContext(), conversationUser);
  410. if (inChat) {
  411. if (wasDetached & conversationUser.hasSpreedCapabilityWithName("no-ping")) {
  412. wasDetached = false;
  413. joinRoomWithPassword();
  414. }
  415. }
  416. }
  417. @Override
  418. protected void onDetach(@NonNull View view) {
  419. super.onDetach(view);
  420. if (conversationUser.hasSpreedCapabilityWithName("no-ping")
  421. && getActivity() != null && !getActivity().isChangingConfigurations() && !isLeavingForConversation) {
  422. wasDetached = true;
  423. leaveRoom();
  424. }
  425. }
  426. @Override
  427. protected String getTitle() {
  428. return conversationName;
  429. }
  430. @Override
  431. public void onDestroy() {
  432. super.onDestroy();
  433. if (getActivity() != null) {
  434. getActivity().findViewById(R.id.toolbar).setOnClickListener(null);
  435. }
  436. adapter = null;
  437. inChat = false;
  438. ApplicationWideCurrentRoomHolder.getInstance().clear();
  439. }
  440. private void dispose() {
  441. Disposable disposable;
  442. for (int i = 0; i < disposableList.size(); i++) {
  443. if (!(disposable = disposableList.get(i)).isDisposed()) {
  444. disposable.dispose();
  445. }
  446. }
  447. }
  448. private void startPing() {
  449. if (!conversationUser.hasSpreedCapabilityWithName("no-ping")) {
  450. ncApi.pingCall(credentials, ApiUtils.getUrlForCallPing(baseUrl, roomToken))
  451. .subscribeOn(Schedulers.newThread())
  452. .observeOn(AndroidSchedulers.mainThread())
  453. .repeatWhen(observable -> observable.delay(5000, TimeUnit.MILLISECONDS))
  454. .takeWhile(observable -> inChat)
  455. .retry(3, observable -> inChat)
  456. .subscribe(new Observer<GenericOverall>() {
  457. @Override
  458. public void onSubscribe(Disposable d) {
  459. disposableList.add(d);
  460. }
  461. @Override
  462. public void onNext(GenericOverall genericOverall) {
  463. }
  464. @Override
  465. public void onError(Throwable e) {
  466. }
  467. @Override
  468. public void onComplete() {
  469. }
  470. });
  471. }
  472. }
  473. @OnClick(R.id.emptyLayout)
  474. void sendHello() {
  475. if (!isHelloClicked) {
  476. isHelloClicked = true;
  477. sendMessage(getResources().getString(R.string.nc_hello) + " 👋", 1);
  478. }
  479. }
  480. private void joinRoomWithPassword() {
  481. if (currentCall == null) {
  482. ncApi.joinRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken), roomPassword)
  483. .subscribeOn(Schedulers.newThread())
  484. .observeOn(AndroidSchedulers.mainThread())
  485. .retry(3)
  486. .subscribe(new Observer<CallOverall>() {
  487. @Override
  488. public void onSubscribe(Disposable d) {
  489. disposableList.add(d);
  490. }
  491. @Override
  492. public void onNext(CallOverall callOverall) {
  493. inChat = true;
  494. currentCall = callOverall.getOcs().getData();
  495. ApplicationWideCurrentRoomHolder.getInstance().setSession(currentCall.getSessionId());
  496. startPing();
  497. if (isFirstMessagesProcessing) {
  498. pullChatMessages(0);
  499. } else {
  500. pullChatMessages(1);
  501. }
  502. if (startCallFromNotification != null && startCallFromNotification) {
  503. startCallFromNotification = false;
  504. startACall(voiceOnly);
  505. }
  506. }
  507. @Override
  508. public void onError(Throwable e) {
  509. }
  510. @Override
  511. public void onComplete() {
  512. }
  513. });
  514. } else {
  515. inChat = true;
  516. ApplicationWideCurrentRoomHolder.getInstance().setSession(currentCall.getSessionId());
  517. startPing();
  518. if (isFirstMessagesProcessing) {
  519. pullChatMessages(0);
  520. } else {
  521. pullChatMessages(1);
  522. }
  523. }
  524. }
  525. private void leaveRoom() {
  526. ncApi.leaveRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken))
  527. .subscribeOn(Schedulers.newThread())
  528. .observeOn(AndroidSchedulers.mainThread())
  529. .subscribe(new Observer<GenericOverall>() {
  530. @Override
  531. public void onSubscribe(Disposable d) {
  532. disposableList.add(d);
  533. }
  534. @Override
  535. public void onNext(GenericOverall genericOverall) {
  536. dispose();
  537. currentCall = null;
  538. if (!isDestroyed() && !isBeingDestroyed() && !wasDetached) {
  539. getRouter().popCurrentController();
  540. }
  541. }
  542. @Override
  543. public void onError(Throwable e) {
  544. }
  545. @Override
  546. public void onComplete() {
  547. dispose();
  548. }
  549. });
  550. }
  551. private void setSenderId() {
  552. try {
  553. final Field senderId = adapter.getClass().getDeclaredField("senderId");
  554. senderId.setAccessible(true);
  555. senderId.set(adapter, conversationUser.getUserId());
  556. } catch (NoSuchFieldException e) {
  557. Log.e(TAG, "Failed to set sender id");
  558. } catch (IllegalAccessException e) {
  559. Log.e(TAG, "Failed to access and set field");
  560. }
  561. }
  562. private void sendMessage(CharSequence message, int attempt) {
  563. if (attempt < 4) {
  564. ncApi.sendChatMessage(credentials, ApiUtils.getUrlForChat(baseUrl, roomToken), message, conversationUser
  565. .getDisplayName())
  566. .subscribeOn(Schedulers.newThread())
  567. .observeOn(AndroidSchedulers.mainThread())
  568. .subscribe(new Observer<GenericOverall>() {
  569. @Override
  570. public void onSubscribe(Disposable d) {
  571. }
  572. @Override
  573. public void onNext(GenericOverall genericOverall) {
  574. if (conversationUser.getUserId().equals("?") && TextUtils.isEmpty(myFirstMessage.toString())) {
  575. myFirstMessage = message;
  576. }
  577. if (popupBubble != null && popupBubble.isShown()) {
  578. popupBubble.hide();
  579. }
  580. if (messagesListView != null) {
  581. messagesListView.smoothScrollToPosition(0);
  582. }
  583. }
  584. @Override
  585. public void onError(Throwable e) {
  586. if (e instanceof HttpException) {
  587. int code = ((HttpException) e).code();
  588. if (Integer.toString(code).startsWith("2")) {
  589. if (conversationUser.getUserId().equals("?") && TextUtils.isEmpty(myFirstMessage.toString())) {
  590. myFirstMessage = message;
  591. }
  592. if (popupBubble != null && popupBubble.isShown()) {
  593. popupBubble.hide();
  594. }
  595. messagesListView.smoothScrollToPosition(0);
  596. } else {
  597. sendMessage(message, attempt + 1);
  598. }
  599. } else {
  600. sendMessage(message, attempt + 1);
  601. }
  602. }
  603. @Override
  604. public void onComplete() {
  605. }
  606. });
  607. }
  608. }
  609. private void pullChatMessages(int lookIntoFuture) {
  610. if (!inChat) {
  611. return;
  612. }
  613. if (!lookingIntoFuture && lookIntoFuture == 1) {
  614. lookingIntoFuture = true;
  615. }
  616. Map<String, Integer> fieldMap = new HashMap<>();
  617. fieldMap.put("lookIntoFuture", lookIntoFuture);
  618. fieldMap.put("limit", 25);
  619. int lastKnown;
  620. if (lookIntoFuture == 1) {
  621. lastKnown = globalLastKnownFutureMessageId;
  622. } else {
  623. lastKnown = globalLastKnownPastMessageId;
  624. }
  625. if (lastKnown != -1) {
  626. fieldMap.put("lastKnownMessageId", lastKnown);
  627. }
  628. if (!wasDetached) {
  629. if (lookIntoFuture == 1) {
  630. ncApi.pullChatMessages(credentials, ApiUtils.getUrlForChat(baseUrl, roomToken), fieldMap)
  631. .subscribeOn(Schedulers.newThread())
  632. .observeOn(AndroidSchedulers.mainThread())
  633. .takeWhile(observable -> inChat && !wasDetached)
  634. .retry(3, observable -> inChat && !wasDetached)
  635. .subscribe(new Observer<Response>() {
  636. @Override
  637. public void onSubscribe(Disposable d) {
  638. disposableList.add(d);
  639. }
  640. @Override
  641. public void onNext(Response response) {
  642. processMessages(response, true);
  643. }
  644. @Override
  645. public void onError(Throwable e) {
  646. }
  647. @Override
  648. public void onComplete() {
  649. pullChatMessages(1);
  650. }
  651. });
  652. } else {
  653. ncApi.pullChatMessages(credentials,
  654. ApiUtils.getUrlForChat(baseUrl, roomToken), fieldMap)
  655. .subscribeOn(Schedulers.newThread())
  656. .observeOn(AndroidSchedulers.mainThread())
  657. .retry(3, observable -> inChat && !wasDetached)
  658. .takeWhile(observable -> inChat && !wasDetached)
  659. .subscribe(new Observer<Response>() {
  660. @Override
  661. public void onSubscribe(Disposable d) {
  662. disposableList.add(d);
  663. }
  664. @Override
  665. public void onNext(Response response) {
  666. processMessages(response, false);
  667. }
  668. @Override
  669. public void onError(Throwable e) {
  670. }
  671. @Override
  672. public void onComplete() {
  673. }
  674. });
  675. }
  676. }
  677. }
  678. private void processMessages(Response response, boolean isFromTheFuture) {
  679. if (response.code() == 200) {
  680. ChatOverall chatOverall = (ChatOverall) response.body();
  681. List<ChatMessage> chatMessageList = chatOverall.getOcs().getData();
  682. if (isFirstMessagesProcessing) {
  683. NotificationUtils.cancelExistingNotifications(getApplicationContext(), conversationUser);
  684. isFirstMessagesProcessing = false;
  685. if (loadingProgressBar != null) {
  686. loadingProgressBar.setVisibility(View.GONE);
  687. }
  688. if (chatMessageList.size() == 0) {
  689. if (emptyLayout != null) {
  690. emptyLayout.setVisibility(View.VISIBLE);
  691. }
  692. if (messagesListView != null) {
  693. messagesListView.setVisibility(View.GONE);
  694. }
  695. } else {
  696. if (emptyLayout != null) {
  697. emptyLayout.setVisibility(View.GONE);
  698. }
  699. if (messagesListView != null) {
  700. messagesListView.setVisibility(View.VISIBLE);
  701. }
  702. }
  703. } else {
  704. if (emptyLayout != null) {
  705. emptyLayout.setVisibility(View.GONE);
  706. }
  707. if (messagesListView != null) {
  708. messagesListView.setVisibility(View.VISIBLE);
  709. }
  710. }
  711. int countGroupedMessages = 0;
  712. if (!isFromTheFuture) {
  713. for (int i = 0; i < chatMessageList.size(); i++) {
  714. if (chatMessageList.size() > i + 1) {
  715. if (TextUtils.isEmpty(chatMessageList.get(i).getSystemMessage()) &&
  716. TextUtils.isEmpty(chatMessageList.get(i + 1).getSystemMessage()) &&
  717. chatMessageList.get(i + 1).getActorId().equals(chatMessageList.get(i).getActorId()) &&
  718. countGroupedMessages < 4 && DateFormatter.isSameDay(chatMessageList.get(i).getCreatedAt(),
  719. chatMessageList.get(i + 1).getCreatedAt())) {
  720. chatMessageList.get(i).setGrouped(true);
  721. countGroupedMessages++;
  722. } else {
  723. countGroupedMessages = 0;
  724. }
  725. }
  726. chatMessageList.get(i).setBaseUrl(conversationUser.getBaseUrl());
  727. chatMessageList.get(i).setActiveUserId(conversationUser.getUserId());
  728. if (globalLastKnownPastMessageId == -1 || chatMessageList.get(i).getJsonMessageId() <
  729. globalLastKnownPastMessageId) {
  730. globalLastKnownPastMessageId = chatMessageList.get(i).getJsonMessageId();
  731. }
  732. if (globalLastKnownFutureMessageId == -1) {
  733. if (chatMessageList.get(i).getJsonMessageId() > globalLastKnownFutureMessageId) {
  734. globalLastKnownFutureMessageId = chatMessageList.get(i).getJsonMessageId();
  735. }
  736. }
  737. }
  738. adapter.addToEnd(chatMessageList, false);
  739. } else {
  740. ChatMessage chatMessage;
  741. for (int i = 0; i < chatMessageList.size(); i++) {
  742. chatMessage = chatMessageList.get(i);
  743. chatMessage.setBaseUrl(conversationUser.getBaseUrl());
  744. chatMessageList.get(i).setActiveUserId(conversationUser.getUserId());
  745. if (conversationUser.getUserId().equals("?") && myFirstMessage != null &&
  746. !TextUtils.isEmpty(myFirstMessage.toString())) {
  747. if (chatMessage.getActorType().equals("guests") &&
  748. chatMessage.getActorDisplayName().equals(conversationUser.getDisplayName())) {
  749. conversationUser.setUserId(chatMessage.getActorId());
  750. setSenderId();
  751. }
  752. }
  753. boolean shouldScroll = layoutManager.findFirstVisibleItemPosition() == 0 ||
  754. adapter.getItemCount() == 0;
  755. if (!shouldScroll && popupBubble != null) {
  756. if (!popupBubble.isShown()) {
  757. newMessagesCount = 1;
  758. popupBubble.show();
  759. } else if (popupBubble.isShown()) {
  760. newMessagesCount++;
  761. }
  762. } else {
  763. newMessagesCount = 0;
  764. }
  765. chatMessage.setGrouped(adapter.isPreviousSameAuthor(chatMessage.getActorId(), -1) && (adapter.getSameAuthorLastMessagesCount(chatMessage.getActorId()) % 5) > 0);
  766. adapter.addToStart(chatMessage, shouldScroll);
  767. }
  768. String xChatLastGivenHeader;
  769. if (response.headers().size() > 0 && !TextUtils.isEmpty((xChatLastGivenHeader = response.headers().get
  770. ("X-Chat-Last-Given")))) {
  771. globalLastKnownFutureMessageId = Integer.parseInt(xChatLastGivenHeader);
  772. }
  773. }
  774. if (!lookingIntoFuture && inChat) {
  775. pullChatMessages(1);
  776. }
  777. } else if (response.code() == 304 && !isFromTheFuture) {
  778. if (isFirstMessagesProcessing) {
  779. NotificationUtils.cancelExistingNotifications(getApplicationContext(), conversationUser);
  780. isFirstMessagesProcessing = false;
  781. if (loadingProgressBar != null) {
  782. loadingProgressBar.setVisibility(View.GONE);
  783. }
  784. if (emptyLayout != null && emptyLayout.getVisibility() != View.VISIBLE) {
  785. emptyLayout.setVisibility(View.VISIBLE);
  786. }
  787. }
  788. historyRead = true;
  789. if (!lookingIntoFuture && inChat) {
  790. pullChatMessages(1);
  791. }
  792. }
  793. }
  794. @Override
  795. public void onLoadMore(int page, int totalItemsCount) {
  796. if (!historyRead && inChat) {
  797. pullChatMessages(0);
  798. }
  799. }
  800. @Override
  801. public String format(Date date) {
  802. if (DateFormatter.isToday(date)) {
  803. return getResources().getString(R.string.nc_date_header_today);
  804. } else if (DateFormatter.isYesterday(date)) {
  805. return getResources().getString(R.string.nc_date_header_yesterday);
  806. } else {
  807. return DateFormatter.format(date, DateFormatter.Template.STRING_DAY_MONTH_YEAR);
  808. }
  809. }
  810. @Override
  811. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  812. super.onCreateOptionsMenu(menu, inflater);
  813. inflater.inflate(R.menu.menu_conversation, menu);
  814. }
  815. @Override
  816. public boolean onOptionsItemSelected(@NonNull MenuItem item) {
  817. switch (item.getItemId()) {
  818. case android.R.id.home:
  819. getRouter().popCurrentController();
  820. return true;
  821. case R.id.conversation_video_call:
  822. startACall(false);
  823. return true;
  824. case R.id.conversation_voice_call:
  825. startACall(true);
  826. return true;
  827. case R.id.conversation_info:
  828. showConversationInfoScreen();
  829. return true;
  830. default:
  831. return super.onOptionsItemSelected(item);
  832. }
  833. }
  834. private void startACall(boolean isVoiceOnlyCall) {
  835. isLeavingForConversation = true;
  836. if (!isVoiceOnlyCall) {
  837. Intent videoCallIntent = getIntentForCall(false);
  838. if (videoCallIntent != null) {
  839. startActivity(videoCallIntent);
  840. }
  841. } else {
  842. Intent voiceCallIntent = getIntentForCall(true);
  843. if (voiceCallIntent != null) {
  844. startActivity(voiceCallIntent);
  845. }
  846. }
  847. }
  848. private Intent getIntentForCall(boolean isVoiceOnlyCall) {
  849. if (currentCall != null) {
  850. Bundle bundle = new Bundle();
  851. bundle.putString(BundleKeys.KEY_ROOM_TOKEN, roomToken);
  852. bundle.putString(BundleKeys.KEY_ROOM_ID, roomId);
  853. bundle.putParcelable(BundleKeys.KEY_USER_ENTITY, Parcels.wrap(conversationUser));
  854. bundle.putString(BundleKeys.KEY_CONVERSATION_PASSWORD, roomPassword);
  855. bundle.putString(BundleKeys.KEY_MODIFIED_BASE_URL, baseUrl);
  856. if (isVoiceOnlyCall) {
  857. bundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, true);
  858. }
  859. if (getActivity() != null) {
  860. Intent callIntent = new Intent(getActivity(), MagicCallActivity.class);
  861. callIntent.putExtras(bundle);
  862. return callIntent;
  863. } else {
  864. return null;
  865. }
  866. } else {
  867. return null;
  868. }
  869. }
  870. @Override
  871. public void onMessageLongClick(IMessage message) {
  872. if (getActivity() != null) {
  873. ClipboardManager clipboardManager = (android.content.ClipboardManager)
  874. getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
  875. ClipData clipData = android.content.ClipData.newPlainText(
  876. getResources().getString(R.string.nc_app_name), message.getText());
  877. if (clipboardManager != null) {
  878. clipboardManager.setPrimaryClip(clipData);
  879. }
  880. }
  881. }
  882. @Override
  883. public boolean hasContentFor(IMessage message, byte type) {
  884. switch (type) {
  885. case CONTENT_TYPE_SYSTEM_MESSAGE:
  886. return !TextUtils.isEmpty(message.getSystemMessage());
  887. }
  888. return false;
  889. }
  890. }