ChatController.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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.Bitmap;
  26. import android.graphics.Color;
  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.support.annotation.NonNull;
  32. import android.support.annotation.Nullable;
  33. import android.support.v7.widget.LinearLayoutManager;
  34. import android.support.v7.widget.RecyclerView;
  35. import android.text.TextUtils;
  36. import android.util.Log;
  37. import android.view.LayoutInflater;
  38. import android.view.Menu;
  39. import android.view.MenuInflater;
  40. import android.view.MenuItem;
  41. import android.view.View;
  42. import android.view.ViewGroup;
  43. import android.view.inputmethod.EditorInfo;
  44. import android.widget.AbsListView;
  45. import android.widget.ImageView;
  46. import com.amulyakhare.textdrawable.TextDrawable;
  47. import com.bluelinelabs.conductor.RouterTransaction;
  48. import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
  49. import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler;
  50. import com.bumptech.glide.load.DataSource;
  51. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  52. import com.bumptech.glide.load.engine.GlideException;
  53. import com.bumptech.glide.load.resource.bitmap.CircleCrop;
  54. import com.bumptech.glide.request.RequestListener;
  55. import com.bumptech.glide.request.RequestOptions;
  56. import com.bumptech.glide.request.target.Target;
  57. import com.nextcloud.talk.R;
  58. import com.nextcloud.talk.activities.CallActivity;
  59. import com.nextcloud.talk.adapters.messages.MagicIncomingTextMessageViewHolder;
  60. import com.nextcloud.talk.adapters.messages.MagicOutcomingTextMessageViewHolder;
  61. import com.nextcloud.talk.api.NcApi;
  62. import com.nextcloud.talk.application.NextcloudTalkApplication;
  63. import com.nextcloud.talk.callbacks.MentionAutocompleteCallback;
  64. import com.nextcloud.talk.controllers.base.BaseController;
  65. import com.nextcloud.talk.models.database.UserEntity;
  66. import com.nextcloud.talk.models.json.call.Call;
  67. import com.nextcloud.talk.models.json.call.CallOverall;
  68. import com.nextcloud.talk.models.json.chat.ChatMessage;
  69. import com.nextcloud.talk.models.json.chat.ChatOverall;
  70. import com.nextcloud.talk.models.json.generic.GenericOverall;
  71. import com.nextcloud.talk.models.json.mention.Mention;
  72. import com.nextcloud.talk.models.json.rooms.Room;
  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.ApplicationWideCurrentRoomHolder;
  77. import com.nextcloud.talk.utils.KeyboardUtils;
  78. import com.nextcloud.talk.utils.bundle.BundleKeys;
  79. import com.nextcloud.talk.utils.database.user.UserUtils;
  80. import com.nextcloud.talk.utils.glide.GlideApp;
  81. import com.otaliastudios.autocomplete.Autocomplete;
  82. import com.otaliastudios.autocomplete.AutocompleteCallback;
  83. import com.otaliastudios.autocomplete.AutocompletePresenter;
  84. import com.otaliastudios.autocomplete.CharPolicy;
  85. import com.stfalcon.chatkit.commons.ImageLoader;
  86. import com.stfalcon.chatkit.commons.models.IMessage;
  87. import com.stfalcon.chatkit.messages.MessageInput;
  88. import com.stfalcon.chatkit.messages.MessagesList;
  89. import com.stfalcon.chatkit.messages.MessagesListAdapter;
  90. import com.stfalcon.chatkit.utils.DateFormatter;
  91. import com.webianks.library.PopupBubble;
  92. import org.parceler.Parcels;
  93. import java.io.IOException;
  94. import java.lang.reflect.Field;
  95. import java.util.ArrayList;
  96. import java.util.Date;
  97. import java.util.HashMap;
  98. import java.util.List;
  99. import java.util.Map;
  100. import java.util.concurrent.TimeUnit;
  101. import javax.inject.Inject;
  102. import autodagger.AutoInjector;
  103. import butterknife.BindView;
  104. import io.reactivex.Observer;
  105. import io.reactivex.android.schedulers.AndroidSchedulers;
  106. import io.reactivex.disposables.Disposable;
  107. import io.reactivex.schedulers.Schedulers;
  108. import okhttp3.Cache;
  109. import retrofit2.HttpException;
  110. import retrofit2.Response;
  111. @AutoInjector(NextcloudTalkApplication.class)
  112. public class ChatController extends BaseController implements MessagesListAdapter.OnLoadMoreListener,
  113. MessagesListAdapter.Formatter<Date>, MessagesListAdapter.OnMessageLongClickListener {
  114. private static final String TAG = "ChatController";
  115. @Inject
  116. NcApi ncApi;
  117. @Inject
  118. UserUtils userUtils;
  119. @Inject
  120. Cache cache;
  121. @BindView(R.id.messagesList)
  122. MessagesList messagesList;
  123. @BindView(R.id.nc_message_input)
  124. MessageInput messageInput;
  125. @BindView(R.id.nc_popup_bubble)
  126. PopupBubble popupBubble;
  127. private List<Disposable> disposableList = new ArrayList<>();
  128. private String conversationName;
  129. private String roomToken;
  130. private UserEntity conversationUser;
  131. private String roomPassword;
  132. private String credentials;
  133. private String baseUrl;
  134. private Call currentCall;
  135. private boolean inChat = false;
  136. private boolean historyRead = false;
  137. private int globalLastKnownFutureMessageId = -1;
  138. private int globalLastKnownPastMessageId = -1;
  139. private MessagesListAdapter<ChatMessage> adapter;
  140. private String myFirstMessage;
  141. private Autocomplete mentionAutocomplete;
  142. private LinearLayoutManager layoutManager;
  143. private boolean lookingIntoFuture = false;
  144. private int newMessagesCount = 0;
  145. private Boolean startCallFromNotification;
  146. private String roomId;
  147. public ChatController(Bundle args) {
  148. super(args);
  149. setHasOptionsMenu(true);
  150. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  151. UserEntity currentUser = userUtils.getCurrentUser();
  152. this.conversationName = args.getString(BundleKeys.KEY_CONVERSATION_NAME, "");
  153. if (args.containsKey(BundleKeys.KEY_USER_ENTITY)) {
  154. this.conversationUser = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_USER_ENTITY));
  155. } else {
  156. this.conversationUser = currentUser;
  157. }
  158. this.roomId = args.getString(BundleKeys.KEY_ROOM_ID, "");
  159. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomId(roomId);
  160. ApplicationWideCurrentRoomHolder.getInstance().setInCall(false);
  161. ApplicationWideCurrentRoomHolder.getInstance().setUserInRoom(conversationUser);
  162. this.roomToken = args.getString(BundleKeys.KEY_ROOM_TOKEN, "");
  163. if (args.containsKey(BundleKeys.KEY_ACTIVE_CONVERSATION)) {
  164. this.currentCall = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_ACTIVE_CONVERSATION));
  165. }
  166. this.baseUrl = args.getString(BundleKeys.KEY_MODIFIED_BASE_URL, "");
  167. if (!TextUtils.isEmpty(baseUrl)) {
  168. conversationUser.setBaseUrl(baseUrl);
  169. conversationUser.setUserId("-1");
  170. conversationUser.setDisplayName(currentUser.getDisplayName());
  171. } else {
  172. baseUrl = conversationUser.getBaseUrl();
  173. }
  174. this.roomPassword = args.getString(BundleKeys.KEY_CONVERSATION_PASSWORD, "");
  175. if (conversationUser.getUserId().equals("-1")) {
  176. credentials = null;
  177. } else {
  178. credentials = ApiUtils.getCredentials(conversationUser.getUserId(), conversationUser.getToken());
  179. }
  180. this.startCallFromNotification = args.getBoolean(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL);
  181. }
  182. private void handleFromNotification() {
  183. ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(baseUrl))
  184. .subscribeOn(Schedulers.newThread())
  185. .observeOn(AndroidSchedulers.mainThread())
  186. .subscribe(new Observer<RoomsOverall>() {
  187. @Override
  188. public void onSubscribe(Disposable d) {
  189. }
  190. @Override
  191. public void onNext(RoomsOverall roomsOverall) {
  192. for (Room room : roomsOverall.getOcs().getData()) {
  193. if (roomId.equals(room.getRoomId())) {
  194. roomToken = room.getToken();
  195. conversationName = room.getDisplayName();
  196. setTitle();
  197. break;
  198. }
  199. }
  200. setupMentionAutocomplete();
  201. joinRoomWithPassword();
  202. }
  203. @Override
  204. public void onError(Throwable e) {
  205. }
  206. @Override
  207. public void onComplete() {
  208. }
  209. });
  210. }
  211. @Override
  212. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  213. return inflater.inflate(R.layout.controller_chat, container, false);
  214. }
  215. @Override
  216. protected void onViewBound(@NonNull View view) {
  217. super.onViewBound(view);
  218. boolean adapterWasNull = false;
  219. if (adapter == null) {
  220. try {
  221. cache.evictAll();
  222. } catch (IOException e) {
  223. Log.e(TAG, "Failed to evict cache");
  224. }
  225. adapterWasNull = true;
  226. MessagesListAdapter.HoldersConfig holdersConfig = new MessagesListAdapter.HoldersConfig();
  227. holdersConfig.setIncoming(MagicIncomingTextMessageViewHolder.class,
  228. R.layout.item_custom_incoming_text_message);
  229. holdersConfig.setOutcoming(MagicOutcomingTextMessageViewHolder.class,
  230. R.layout.item_custom_outcoming_text_message);
  231. adapter = new MessagesListAdapter<>(conversationUser.getUserId(), holdersConfig, new ImageLoader() {
  232. @Override
  233. public void loadImage(ImageView imageView, String url) {
  234. GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
  235. .asBitmap()
  236. .diskCacheStrategy(DiskCacheStrategy.NONE)
  237. .load(url)
  238. .centerInside()
  239. .override(imageView.getMeasuredWidth(), imageView.getMeasuredHeight())
  240. .apply(RequestOptions.bitmapTransform(new CircleCrop()))
  241. .listener(new RequestListener<Bitmap>() {
  242. @Override
  243. public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
  244. TextDrawable drawable = TextDrawable.builder().beginConfig().bold()
  245. .width(imageView.getMeasuredWidth()).height(imageView.getMeasuredHeight())
  246. .endConfig().buildRound("?", getResources().getColor(R.color.nc_grey));
  247. imageView.setImageDrawable(drawable);
  248. return true;
  249. }
  250. @Override
  251. public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
  252. return false;
  253. }
  254. })
  255. .into(imageView);
  256. }
  257. });
  258. }
  259. messagesList.setAdapter(adapter);
  260. adapter.setLoadMoreListener(this);
  261. adapter.setDateHeadersFormatter(this::format);
  262. adapter.setOnMessageLongClickListener(this);
  263. layoutManager = (LinearLayoutManager) messagesList.getLayoutManager();
  264. popupBubble.setRecyclerView(messagesList);
  265. popupBubble.setPopupBubbleListener(context -> {
  266. if (newMessagesCount != 0) {
  267. int scrollPosition;
  268. if (newMessagesCount - 1 < 0) {
  269. scrollPosition = 0;
  270. } else {
  271. scrollPosition = newMessagesCount - 1;
  272. }
  273. new Handler().postDelayed(() -> messagesList.smoothScrollToPosition(scrollPosition), 200);
  274. }
  275. });
  276. messagesList.addOnScrollListener(new RecyclerView.OnScrollListener() {
  277. @Override
  278. public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
  279. super.onScrollStateChanged(recyclerView, newState);
  280. if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
  281. if (newMessagesCount != 0) {
  282. if (layoutManager.findFirstCompletelyVisibleItemPosition() < newMessagesCount) {
  283. newMessagesCount = 0;
  284. if (popupBubble != null && popupBubble.isShown()) {
  285. popupBubble.hide();
  286. }
  287. }
  288. }
  289. }
  290. }
  291. });
  292. messageInput.getInputEditText().setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
  293. messageInput.setInputListener(input -> {
  294. sendMessage(input.toString(), 1);
  295. return true;
  296. });
  297. if (adapterWasNull && startCallFromNotification == null) {
  298. setupMentionAutocomplete();
  299. joinRoomWithPassword();
  300. } else {
  301. handleFromNotification();
  302. }
  303. }
  304. private void setupMentionAutocomplete() {
  305. float elevation = 6f;
  306. Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
  307. AutocompletePresenter<Mention> presenter = new MentionAutocompletePresenter(getApplicationContext(), roomToken);
  308. AutocompleteCallback<Mention> callback = new MentionAutocompleteCallback();
  309. if (messageInput != null && messageInput.getInputEditText() != null) {
  310. mentionAutocomplete = Autocomplete.<Mention>on(messageInput.getInputEditText())
  311. .with(elevation)
  312. .with(backgroundDrawable)
  313. .with(new CharPolicy('@'))
  314. .with(presenter)
  315. .with(callback)
  316. .build();
  317. }
  318. }
  319. @Override
  320. protected void onAttach(@NonNull View view) {
  321. super.onAttach(view);
  322. if (getActionBar() != null) {
  323. getActionBar().setDisplayHomeAsUpEnabled(true);
  324. }
  325. if (mentionAutocomplete != null && mentionAutocomplete.isPopupShowing()) {
  326. mentionAutocomplete.dismissPopup();
  327. }
  328. if (getActivity() != null) {
  329. new KeyboardUtils(getActivity(), getView());
  330. }
  331. }
  332. @Override
  333. protected String getTitle() {
  334. return conversationName;
  335. }
  336. @Override
  337. public void onDestroy() {
  338. inChat = false;
  339. dispose();
  340. ApplicationWideCurrentRoomHolder.getInstance().clear();
  341. leaveRoom();
  342. }
  343. private void dispose() {
  344. Disposable disposable;
  345. for (int i = 0; i < disposableList.size(); i++) {
  346. if ((disposable = disposableList.get(i)).isDisposed()) {
  347. disposable.dispose();
  348. }
  349. }
  350. }
  351. private void startPing() {
  352. ncApi.pingCall(credentials, ApiUtils.getUrlForCallPing(baseUrl, roomToken))
  353. .subscribeOn(Schedulers.newThread())
  354. .observeOn(AndroidSchedulers.mainThread())
  355. .repeatWhen(observable -> observable.delay(5000, TimeUnit.MILLISECONDS))
  356. .takeWhile(observable -> inChat)
  357. .retry(3, observable -> inChat)
  358. .subscribe(new Observer<GenericOverall>() {
  359. @Override
  360. public void onSubscribe(Disposable d) {
  361. disposableList.add(d);
  362. }
  363. @Override
  364. public void onNext(GenericOverall genericOverall) {
  365. }
  366. @Override
  367. public void onError(Throwable e) {
  368. }
  369. @Override
  370. public void onComplete() {
  371. }
  372. });
  373. }
  374. private void joinRoomWithPassword() {
  375. if (currentCall == null) {
  376. ncApi.joinRoom(credentials, ApiUtils.getUrlForRoomParticipants(baseUrl, roomToken), roomPassword)
  377. .subscribeOn(Schedulers.newThread())
  378. .observeOn(AndroidSchedulers.mainThread())
  379. .retry(3)
  380. .subscribe(new Observer<CallOverall>() {
  381. @Override
  382. public void onSubscribe(Disposable d) {
  383. disposableList.add(d);
  384. }
  385. @Override
  386. public void onNext(CallOverall callOverall) {
  387. inChat = true;
  388. currentCall = callOverall.getOcs().getData();
  389. startPing();
  390. pullChatMessages(0);
  391. if (startCallFromNotification != null && startCallFromNotification) {
  392. startCallFromNotification = false;
  393. startACall(false);
  394. }
  395. }
  396. @Override
  397. public void onError(Throwable e) {
  398. }
  399. @Override
  400. public void onComplete() {
  401. }
  402. });
  403. } else {
  404. inChat = true;
  405. startPing();
  406. pullChatMessages(0);
  407. }
  408. }
  409. private void leaveRoom() {
  410. ncApi.leaveRoom(credentials, ApiUtils.getUrlForRoomParticipants(baseUrl, roomToken))
  411. .subscribeOn(Schedulers.newThread())
  412. .observeOn(AndroidSchedulers.mainThread())
  413. .subscribe(new Observer<GenericOverall>() {
  414. @Override
  415. public void onSubscribe(Disposable d) {
  416. }
  417. @Override
  418. public void onNext(GenericOverall genericOverall) {
  419. if (getRouter().hasRootController()) {
  420. getRouter().popToRoot(new VerticalChangeHandler());
  421. } else {
  422. getRouter().setRoot(RouterTransaction.with(new MagicBottomNavigationController())
  423. .pushChangeHandler(new HorizontalChangeHandler())
  424. .popChangeHandler(new HorizontalChangeHandler()));
  425. }
  426. }
  427. @Override
  428. public void onError(Throwable e) {
  429. }
  430. @Override
  431. public void onComplete() {
  432. }
  433. });
  434. }
  435. private void setSenderId() {
  436. try {
  437. final Field senderId = adapter.getClass().getDeclaredField("senderId");
  438. senderId.setAccessible(true);
  439. senderId.set(adapter, conversationUser.getUserId());
  440. } catch (NoSuchFieldException e) {
  441. Log.e(TAG, "Failed to set sender id");
  442. } catch (IllegalAccessException e) {
  443. Log.e(TAG, "Failed to access and set field");
  444. }
  445. }
  446. private void sendMessage(String message, int attempt) {
  447. if (attempt < 4) {
  448. Map<String, String> fieldMap = new HashMap<>();
  449. fieldMap.put("message", message);
  450. fieldMap.put("actorDisplayName", conversationUser.getDisplayName());
  451. ncApi.sendChatMessage(credentials, ApiUtils.getUrlForChat(baseUrl, roomToken), fieldMap)
  452. .subscribeOn(Schedulers.newThread())
  453. .observeOn(AndroidSchedulers.mainThread())
  454. .subscribe(new Observer<GenericOverall>() {
  455. @Override
  456. public void onSubscribe(Disposable d) {
  457. }
  458. @Override
  459. public void onNext(GenericOverall genericOverall) {
  460. if (conversationUser.getUserId().equals("-1") && TextUtils.isEmpty(myFirstMessage)) {
  461. myFirstMessage = message;
  462. }
  463. if (popupBubble != null && popupBubble.isShown()) {
  464. popupBubble.hide();
  465. }
  466. if (messagesList != null) {
  467. messagesList.smoothScrollToPosition(0);
  468. }
  469. }
  470. @Override
  471. public void onError(Throwable e) {
  472. if (e instanceof HttpException && ((HttpException) e).code() == 201) {
  473. if (conversationUser.getUserId().equals("-1") && TextUtils.isEmpty(myFirstMessage)) {
  474. myFirstMessage = message;
  475. }
  476. if (popupBubble != null && popupBubble.isShown()) {
  477. popupBubble.hide();
  478. }
  479. messagesList.smoothScrollToPosition(0);
  480. } else {
  481. sendMessage(message, attempt + 1);
  482. }
  483. }
  484. @Override
  485. public void onComplete() {
  486. }
  487. });
  488. }
  489. }
  490. private void pullChatMessages(int lookIntoFuture) {
  491. if (!lookingIntoFuture && lookIntoFuture == 1) {
  492. lookingIntoFuture = true;
  493. }
  494. Map<String, Integer> fieldMap = new HashMap<>();
  495. fieldMap.put("lookIntoFuture", lookIntoFuture);
  496. fieldMap.put("limit", 25);
  497. int lastKnown;
  498. if (lookIntoFuture == 1) {
  499. lastKnown = globalLastKnownFutureMessageId;
  500. } else {
  501. lastKnown = globalLastKnownPastMessageId;
  502. }
  503. if (lastKnown != -1) {
  504. fieldMap.put("lastKnownMessageId", lastKnown);
  505. }
  506. if (lookIntoFuture == 1) {
  507. ncApi.pullChatMessages(credentials, ApiUtils.getUrlForChat(baseUrl, roomToken), fieldMap)
  508. .subscribeOn(Schedulers.newThread())
  509. .observeOn(AndroidSchedulers.mainThread())
  510. .takeWhile(observable -> inChat)
  511. .retry(3, observable -> inChat)
  512. .subscribe(new Observer<Response>() {
  513. @Override
  514. public void onSubscribe(Disposable d) {
  515. disposableList.add(d);
  516. }
  517. @Override
  518. public void onNext(Response response) {
  519. processMessages(response, true);
  520. }
  521. @Override
  522. public void onError(Throwable e) {
  523. }
  524. @Override
  525. public void onComplete() {
  526. pullChatMessages(1);
  527. }
  528. });
  529. } else {
  530. ncApi.pullChatMessages(credentials,
  531. ApiUtils.getUrlForChat(baseUrl, roomToken), fieldMap)
  532. .subscribeOn(Schedulers.newThread())
  533. .observeOn(AndroidSchedulers.mainThread())
  534. .retry(3, observable -> inChat)
  535. .subscribe(new Observer<Response>() {
  536. @Override
  537. public void onSubscribe(Disposable d) {
  538. disposableList.add(d);
  539. }
  540. @Override
  541. public void onNext(Response response) {
  542. processMessages(response, false);
  543. }
  544. @Override
  545. public void onError(Throwable e) {
  546. }
  547. @Override
  548. public void onComplete() {
  549. }
  550. });
  551. }
  552. }
  553. private void processMessages(Response response, boolean isFromTheFuture) {
  554. if (response.code() == 200) {
  555. ChatOverall chatOverall = (ChatOverall) response.body();
  556. List<ChatMessage> chatMessageList = chatOverall.getOcs().getData();
  557. if (!isFromTheFuture) {
  558. for (int i = 0; i < chatMessageList.size(); i++) {
  559. chatMessageList.get(i).setBaseUrl(conversationUser.getBaseUrl());
  560. if (globalLastKnownPastMessageId == -1 || chatMessageList.get(i).getJsonMessageId() <
  561. globalLastKnownPastMessageId) {
  562. globalLastKnownPastMessageId = chatMessageList.get(i).getJsonMessageId();
  563. }
  564. if (globalLastKnownFutureMessageId == -1) {
  565. if (chatMessageList.get(i).getJsonMessageId() > globalLastKnownFutureMessageId) {
  566. globalLastKnownFutureMessageId = chatMessageList.get(i).getJsonMessageId();
  567. }
  568. }
  569. }
  570. adapter.addToEnd(chatMessageList, false);
  571. } else {
  572. for (int i = 0; i < chatMessageList.size(); i++) {
  573. chatMessageList.get(i).setBaseUrl(conversationUser.getBaseUrl());
  574. if (conversationUser.getUserId().equals("-1") && !TextUtils.isEmpty(myFirstMessage)) {
  575. ChatMessage chatMessage = chatMessageList.get(i);
  576. if (chatMessage.getActorType().equals("guests") &&
  577. chatMessage.getActorDisplayName().equals(conversationUser.getDisplayName())) {
  578. conversationUser.setUserId(chatMessage.getActorId());
  579. setSenderId();
  580. }
  581. }
  582. boolean shouldScroll = layoutManager.findFirstVisibleItemPosition() == 0 ||
  583. adapter.getItemCount() == 0;
  584. if (!shouldScroll && popupBubble != null) {
  585. if (!popupBubble.isShown()) {
  586. newMessagesCount = 1;
  587. popupBubble.show();
  588. } else if (popupBubble.isShown()) {
  589. newMessagesCount++;
  590. }
  591. } else {
  592. newMessagesCount = 0;
  593. }
  594. adapter.addToStart(chatMessageList.get(i), shouldScroll);
  595. }
  596. String xChatLastGivenHeader;
  597. if (response.headers().size() > 0 && !TextUtils.isEmpty((xChatLastGivenHeader = response.headers().get
  598. ("X-Chat-Last-Given")))) {
  599. globalLastKnownFutureMessageId = Integer.parseInt(xChatLastGivenHeader);
  600. }
  601. }
  602. if (!lookingIntoFuture) {
  603. pullChatMessages(1);
  604. }
  605. } else if (response.code() == 304 && !isFromTheFuture) {
  606. historyRead = true;
  607. if (!lookingIntoFuture) {
  608. pullChatMessages(1);
  609. }
  610. }
  611. }
  612. @Override
  613. public void onLoadMore(int page, int totalItemsCount) {
  614. if (!historyRead) {
  615. pullChatMessages(0);
  616. }
  617. }
  618. @Override
  619. public String format(Date date) {
  620. if (DateFormatter.isToday(date)) {
  621. return getResources().getString(R.string.nc_date_header_today);
  622. } else if (DateFormatter.isYesterday(date)) {
  623. return getResources().getString(R.string.nc_date_header_yesterday);
  624. } else {
  625. return DateFormatter.format(date, DateFormatter.Template.STRING_DAY_MONTH_YEAR);
  626. }
  627. }
  628. @Override
  629. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  630. super.onCreateOptionsMenu(menu, inflater);
  631. inflater.inflate(R.menu.menu_conversation, menu);
  632. }
  633. @Override
  634. public boolean onOptionsItemSelected(@NonNull MenuItem item) {
  635. switch (item.getItemId()) {
  636. case android.R.id.home:
  637. onDestroy();
  638. return true;
  639. case R.id.conversation_video_call:
  640. startACall(false);
  641. return true;
  642. case R.id.conversation_voice_call:
  643. startACall(true);
  644. return true;
  645. default:
  646. return super.onOptionsItemSelected(item);
  647. }
  648. }
  649. private void startACall(boolean isVoiceOnlyCall) {
  650. if (!isVoiceOnlyCall) {
  651. Intent videoCallIntent = getIntentForCall(false);
  652. if (videoCallIntent != null) {
  653. startActivity(videoCallIntent);
  654. }
  655. } else {
  656. Intent voiceCallIntent = getIntentForCall(true);
  657. if (voiceCallIntent != null) {
  658. startActivity(voiceCallIntent);
  659. }
  660. }
  661. }
  662. private Intent getIntentForCall(boolean isVoiceOnlyCall) {
  663. if (currentCall != null && !TextUtils.isEmpty(currentCall.getSessionId())) {
  664. Bundle bundle = new Bundle();
  665. bundle.putString(BundleKeys.KEY_ROOM_TOKEN, roomToken);
  666. bundle.putString(BundleKeys.KEY_ROOM_ID, roomId);
  667. bundle.putParcelable(BundleKeys.KEY_USER_ENTITY, Parcels.wrap(conversationUser));
  668. bundle.putString(BundleKeys.KEY_CONVERSATION_PASSWORD, roomPassword);
  669. bundle.putString(BundleKeys.KEY_CALL_SESSION, currentCall.getSessionId());
  670. bundle.putString(BundleKeys.KEY_MODIFIED_BASE_URL, baseUrl);
  671. if (isVoiceOnlyCall) {
  672. bundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, true);
  673. }
  674. Intent callIntent = new Intent(getActivity(), CallActivity.class);
  675. callIntent.putExtras(bundle);
  676. return callIntent;
  677. } else {
  678. return null;
  679. }
  680. }
  681. @Override
  682. public void onMessageLongClick(IMessage message) {
  683. if (getActivity() != null) {
  684. ClipboardManager clipboardManager = (android.content.ClipboardManager)
  685. getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
  686. ClipData clipData = android.content.ClipData.newPlainText(
  687. getResources().getString(R.string.nc_app_name), message.getText());
  688. if (clipboardManager != null) {
  689. clipboardManager.setPrimaryClip(clipData);
  690. }
  691. }
  692. }
  693. }