ChatController.java 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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 android.widget.ProgressBar;
  47. import android.widget.RelativeLayout;
  48. import android.widget.TextView;
  49. import com.amulyakhare.textdrawable.TextDrawable;
  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.MagicCallActivity;
  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.RoomOverall;
  74. import com.nextcloud.talk.models.json.rooms.RoomsOverall;
  75. import com.nextcloud.talk.presenters.MentionAutocompletePresenter;
  76. import com.nextcloud.talk.utils.ApiUtils;
  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.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.io.IOException;
  96. import java.lang.reflect.Field;
  97. import java.util.ArrayList;
  98. import java.util.Date;
  99. import java.util.HashMap;
  100. import java.util.List;
  101. import java.util.Map;
  102. import java.util.concurrent.TimeUnit;
  103. import javax.inject.Inject;
  104. import autodagger.AutoInjector;
  105. import butterknife.BindView;
  106. import butterknife.OnClick;
  107. import io.reactivex.Observer;
  108. import io.reactivex.android.schedulers.AndroidSchedulers;
  109. import io.reactivex.disposables.Disposable;
  110. import io.reactivex.schedulers.Schedulers;
  111. import okhttp3.Cache;
  112. import retrofit2.HttpException;
  113. import retrofit2.Response;
  114. @AutoInjector(NextcloudTalkApplication.class)
  115. public class ChatController extends BaseController implements MessagesListAdapter.OnLoadMoreListener,
  116. MessagesListAdapter.Formatter<Date>, MessagesListAdapter.OnMessageLongClickListener {
  117. private static final String TAG = "ChatController";
  118. @Inject
  119. NcApi ncApi;
  120. @Inject
  121. UserUtils userUtils;
  122. @Inject
  123. Cache cache;
  124. @BindView(R.id.messagesListView)
  125. MessagesList messagesListView;
  126. @BindView(R.id.messageInputView)
  127. MessageInput messageInputView;
  128. @BindView(R.id.popupBubbleView)
  129. PopupBubble popupBubble;
  130. @BindView(R.id.emptyLayout)
  131. RelativeLayout emptyLayout;
  132. @BindView(R.id.sendHiTextView)
  133. TextView sendHiTextView;
  134. @BindView(R.id.progressBar)
  135. ProgressBar loadingProgressBar;
  136. private List<Disposable> disposableList = new ArrayList<>();
  137. private String conversationName;
  138. private String roomToken;
  139. private UserEntity conversationUser;
  140. private String roomPassword;
  141. private String credentials;
  142. private String baseUrl;
  143. private Call currentCall;
  144. private boolean inChat = false;
  145. private boolean historyRead = false;
  146. private int globalLastKnownFutureMessageId = -1;
  147. private int globalLastKnownPastMessageId = -1;
  148. private MessagesListAdapter<ChatMessage> adapter;
  149. private CharSequence myFirstMessage;
  150. private Autocomplete mentionAutocomplete;
  151. private LinearLayoutManager layoutManager;
  152. private boolean lookingIntoFuture = false;
  153. private int newMessagesCount = 0;
  154. private Boolean startCallFromNotification = null;
  155. private String roomId;
  156. private boolean voiceOnly;
  157. private boolean isFirstMessagesProcessing = true;
  158. private boolean isHelloClicked;
  159. private final short VIEW_TYPE_DATE_HEADER = 130;
  160. public ChatController(Bundle args) {
  161. super(args);
  162. setHasOptionsMenu(true);
  163. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  164. UserEntity currentUser = userUtils.getCurrentUser();
  165. this.conversationName = args.getString(BundleKeys.KEY_CONVERSATION_NAME, "");
  166. if (args.containsKey(BundleKeys.KEY_USER_ENTITY)) {
  167. this.conversationUser = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_USER_ENTITY));
  168. } else {
  169. this.conversationUser = currentUser;
  170. }
  171. this.roomId = args.getString(BundleKeys.KEY_ROOM_ID, "");
  172. this.roomToken = args.getString(BundleKeys.KEY_ROOM_TOKEN, "");
  173. if (args.containsKey(BundleKeys.KEY_ACTIVE_CONVERSATION)) {
  174. this.currentCall = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_ACTIVE_CONVERSATION));
  175. }
  176. this.baseUrl = args.getString(BundleKeys.KEY_MODIFIED_BASE_URL, "");
  177. if (!TextUtils.isEmpty(baseUrl)) {
  178. conversationUser.setBaseUrl(baseUrl);
  179. conversationUser.setUserId("?");
  180. conversationUser.setDisplayName(currentUser.getDisplayName());
  181. } else {
  182. baseUrl = conversationUser.getBaseUrl();
  183. }
  184. this.roomPassword = args.getString(BundleKeys.KEY_CONVERSATION_PASSWORD, "");
  185. if (conversationUser.getUserId().equals("?")) {
  186. credentials = null;
  187. } else {
  188. credentials = ApiUtils.getCredentials(conversationUser.getUserId(), conversationUser.getToken());
  189. }
  190. if (args.containsKey(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL)) {
  191. this.startCallFromNotification = args.getBoolean(BundleKeys.KEY_FROM_NOTIFICATION_START_CALL);
  192. }
  193. this.voiceOnly = args.getBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, false);
  194. }
  195. private void getRoomInfo() {
  196. ncApi.getRoom(credentials, ApiUtils.getRoom(baseUrl, roomToken))
  197. .subscribeOn(Schedulers.newThread())
  198. .observeOn(AndroidSchedulers.mainThread())
  199. .subscribe(new Observer<RoomOverall>() {
  200. @Override
  201. public void onSubscribe(Disposable d) {
  202. }
  203. @Override
  204. public void onNext(RoomOverall roomOverall) {
  205. conversationName = roomOverall.getOcs().getData().getDisplayName();
  206. Log.d("MARIO", getTitle());
  207. setTitle();
  208. setupMentionAutocomplete();
  209. joinRoomWithPassword();
  210. }
  211. @Override
  212. public void onError(Throwable e) {
  213. }
  214. @Override
  215. public void onComplete() {
  216. }
  217. });
  218. }
  219. private void handleFromNotification() {
  220. ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(baseUrl))
  221. .subscribeOn(Schedulers.newThread())
  222. .observeOn(AndroidSchedulers.mainThread())
  223. .subscribe(new Observer<RoomsOverall>() {
  224. @Override
  225. public void onSubscribe(Disposable d) {
  226. }
  227. @Override
  228. public void onNext(RoomsOverall roomsOverall) {
  229. for (Room room : roomsOverall.getOcs().getData()) {
  230. if (roomId.equals(room.getRoomId())) {
  231. roomToken = room.getToken();
  232. conversationName = room.getDisplayName();
  233. Log.d("MARIO", getTitle());
  234. setTitle();
  235. break;
  236. }
  237. }
  238. if (!TextUtils.isEmpty(roomToken)) {
  239. setupMentionAutocomplete();
  240. joinRoomWithPassword();
  241. }
  242. }
  243. @Override
  244. public void onError(Throwable e) {
  245. }
  246. @Override
  247. public void onComplete() {
  248. }
  249. });
  250. }
  251. @Override
  252. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  253. return inflater.inflate(R.layout.controller_chat, container, false);
  254. }
  255. @Override
  256. protected void onViewBound(@NonNull View view) {
  257. super.onViewBound(view);
  258. getActionBar().show();
  259. boolean adapterWasNull = false;
  260. sendHiTextView.setText(String.format(getResources().getString(R.string.nc_chat_empty), getResources()
  261. .getString(R.string.nc_hello)));
  262. if (adapter == null) {
  263. loadingProgressBar.setVisibility(View.VISIBLE);
  264. try {
  265. cache.evictAll();
  266. } catch (IOException e) {
  267. Log.e(TAG, "Failed to evict cache");
  268. }
  269. adapterWasNull = true;
  270. MessageHolders messageHolders = new MessageHolders();
  271. messageHolders.setIncomingTextConfig(MagicIncomingTextMessageViewHolder.class, R.layout.item_custom_incoming_text_message);
  272. messageHolders.setOutcomingTextConfig(MagicOutcomingTextMessageViewHolder.class, R.layout.item_custom_outcoming_text_message);
  273. adapter = new MessagesListAdapter<>(conversationUser.getUserId(), messageHolders, new ImageLoader() {
  274. @Override
  275. public void loadImage(ImageView imageView, String url) {
  276. GlideApp.with(NextcloudTalkApplication.getSharedApplication().getApplicationContext())
  277. .asBitmap()
  278. .diskCacheStrategy(DiskCacheStrategy.NONE)
  279. .load(url)
  280. .centerInside()
  281. .override(imageView.getMeasuredWidth(), imageView.getMeasuredHeight())
  282. .apply(RequestOptions.bitmapTransform(new CircleCrop()))
  283. .listener(new RequestListener<Bitmap>() {
  284. @Override
  285. public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
  286. TextDrawable drawable = TextDrawable.builder().beginConfig().bold()
  287. .endConfig().buildRound("?", getResources().getColor(R.color.nc_grey));
  288. imageView.setImageDrawable(drawable);
  289. return true;
  290. }
  291. @Override
  292. public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
  293. return false;
  294. }
  295. })
  296. .into(imageView);
  297. }
  298. });
  299. } else {
  300. if (adapter.getItemCount() == 0) {
  301. emptyLayout.setVisibility(View.VISIBLE);
  302. } else {
  303. messagesListView.setVisibility(View.VISIBLE);
  304. }
  305. }
  306. messagesListView.setAdapter(adapter);
  307. adapter.setLoadMoreListener(this);
  308. adapter.setDateHeadersFormatter(this::format);
  309. adapter.setOnMessageLongClickListener(this);
  310. layoutManager = (LinearLayoutManager) messagesListView.getLayoutManager();
  311. popupBubble.setRecyclerView(messagesListView);
  312. popupBubble.setPopupBubbleListener(context -> {
  313. if (newMessagesCount != 0) {
  314. int scrollPosition;
  315. if (newMessagesCount - 1 < 0) {
  316. scrollPosition = 0;
  317. } else {
  318. scrollPosition = newMessagesCount - 1;
  319. }
  320. new Handler().postDelayed(() -> messagesListView.smoothScrollToPosition(scrollPosition), 200);
  321. }
  322. });
  323. messagesListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
  324. @Override
  325. public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
  326. super.onScrollStateChanged(recyclerView, newState);
  327. if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
  328. if (newMessagesCount != 0) {
  329. if (layoutManager.findFirstCompletelyVisibleItemPosition() < newMessagesCount) {
  330. newMessagesCount = 0;
  331. if (popupBubble != null && popupBubble.isShown()) {
  332. popupBubble.hide();
  333. }
  334. }
  335. }
  336. }
  337. }
  338. });
  339. messageInputView.getInputEditText().setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
  340. messageInputView.setInputListener(input -> {
  341. sendMessage(input, 1);
  342. return true;
  343. });
  344. messageInputView.getButton().setContentDescription(getResources()
  345. .getString(R.string.nc_description_send_message_button));
  346. if (adapterWasNull) {
  347. // we're starting
  348. if (TextUtils.isEmpty(roomToken)) {
  349. handleFromNotification();
  350. } else if (TextUtils.isEmpty(conversationName)){
  351. getRoomInfo();
  352. } else {
  353. setupMentionAutocomplete();
  354. joinRoomWithPassword();
  355. }
  356. }
  357. }
  358. private void setupMentionAutocomplete() {
  359. float elevation = 6f;
  360. Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
  361. AutocompletePresenter<Mention> presenter = new MentionAutocompletePresenter(getApplicationContext(), roomToken);
  362. AutocompleteCallback<Mention> callback = new MentionAutocompleteCallback();
  363. if (messageInputView != null && messageInputView.getInputEditText() != null) {
  364. mentionAutocomplete = Autocomplete.<Mention>on(messageInputView.getInputEditText())
  365. .with(elevation)
  366. .with(backgroundDrawable)
  367. .with(new CharPolicy('@'))
  368. .with(presenter)
  369. .with(callback)
  370. .build();
  371. }
  372. }
  373. @Override
  374. protected void onAttach(@NonNull View view) {
  375. super.onAttach(view);
  376. if (getActionBar() != null) {
  377. getActionBar().setDisplayHomeAsUpEnabled(true);
  378. }
  379. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomId(roomId);
  380. ApplicationWideCurrentRoomHolder.getInstance().setInCall(false);
  381. ApplicationWideCurrentRoomHolder.getInstance().setUserInRoom(conversationUser);
  382. if (mentionAutocomplete != null && mentionAutocomplete.isPopupShowing()) {
  383. mentionAutocomplete.dismissPopup();
  384. }
  385. if (getActivity() != null) {
  386. new KeyboardUtils(getActivity(), getView(), false);
  387. }
  388. }
  389. @Override
  390. protected String getTitle() {
  391. return conversationName;
  392. }
  393. @Override
  394. public void onDestroy() {
  395. inChat = false;
  396. dispose();
  397. ApplicationWideCurrentRoomHolder.getInstance().clear();
  398. leaveRoom();
  399. }
  400. private void dispose() {
  401. Disposable disposable;
  402. for (int i = 0; i < disposableList.size(); i++) {
  403. if ((disposable = disposableList.get(i)).isDisposed()) {
  404. disposable.dispose();
  405. }
  406. }
  407. }
  408. private void startPing() {
  409. if (!conversationUser.hasSpreedCapabilityWithName("no-ping")) {
  410. ncApi.pingCall(credentials, ApiUtils.getUrlForCallPing(baseUrl, roomToken))
  411. .subscribeOn(Schedulers.newThread())
  412. .observeOn(AndroidSchedulers.mainThread())
  413. .repeatWhen(observable -> observable.delay(5000, TimeUnit.MILLISECONDS))
  414. .takeWhile(observable -> inChat)
  415. .retry(3, observable -> inChat)
  416. .subscribe(new Observer<GenericOverall>() {
  417. @Override
  418. public void onSubscribe(Disposable d) {
  419. disposableList.add(d);
  420. }
  421. @Override
  422. public void onNext(GenericOverall genericOverall) {
  423. }
  424. @Override
  425. public void onError(Throwable e) {
  426. }
  427. @Override
  428. public void onComplete() {
  429. }
  430. });
  431. }
  432. }
  433. @OnClick(R.id.emptyLayout)
  434. public void sendHello() {
  435. if (!isHelloClicked) {
  436. isHelloClicked = true;
  437. sendMessage(getResources().getString(R.string.nc_hello) + " 👋", 1);
  438. }
  439. }
  440. private void joinRoomWithPassword() {
  441. if (currentCall == null) {
  442. ncApi.joinRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken), roomPassword)
  443. .subscribeOn(Schedulers.newThread())
  444. .observeOn(AndroidSchedulers.mainThread())
  445. .retry(3)
  446. .subscribe(new Observer<CallOverall>() {
  447. @Override
  448. public void onSubscribe(Disposable d) {
  449. disposableList.add(d);
  450. }
  451. @Override
  452. public void onNext(CallOverall callOverall) {
  453. inChat = true;
  454. currentCall = callOverall.getOcs().getData();
  455. startPing();
  456. pullChatMessages(0);
  457. if (startCallFromNotification != null && startCallFromNotification) {
  458. startCallFromNotification = false;
  459. startACall(voiceOnly);
  460. }
  461. }
  462. @Override
  463. public void onError(Throwable e) {
  464. }
  465. @Override
  466. public void onComplete() {
  467. }
  468. });
  469. } else {
  470. inChat = true;
  471. startPing();
  472. pullChatMessages(0);
  473. }
  474. }
  475. private void leaveRoom() {
  476. ncApi.leaveRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken))
  477. .subscribeOn(Schedulers.newThread())
  478. .observeOn(AndroidSchedulers.mainThread())
  479. .subscribe(new Observer<GenericOverall>() {
  480. @Override
  481. public void onSubscribe(Disposable d) {
  482. }
  483. @Override
  484. public void onNext(GenericOverall genericOverall) {
  485. getRouter().popToRoot();
  486. }
  487. @Override
  488. public void onError(Throwable e) {
  489. }
  490. @Override
  491. public void onComplete() {
  492. }
  493. });
  494. }
  495. private void setSenderId() {
  496. try {
  497. final Field senderId = adapter.getClass().getDeclaredField("senderId");
  498. senderId.setAccessible(true);
  499. senderId.set(adapter, conversationUser.getUserId());
  500. } catch (NoSuchFieldException e) {
  501. Log.e(TAG, "Failed to set sender id");
  502. } catch (IllegalAccessException e) {
  503. Log.e(TAG, "Failed to access and set field");
  504. }
  505. }
  506. private void sendMessage(CharSequence message, int attempt) {
  507. if (attempt < 4) {
  508. ncApi.sendChatMessage(credentials, ApiUtils.getUrlForChat(baseUrl, roomToken), message, conversationUser
  509. .getDisplayName())
  510. .subscribeOn(Schedulers.newThread())
  511. .observeOn(AndroidSchedulers.mainThread())
  512. .subscribe(new Observer<GenericOverall>() {
  513. @Override
  514. public void onSubscribe(Disposable d) {
  515. }
  516. @Override
  517. public void onNext(GenericOverall genericOverall) {
  518. if (conversationUser.getUserId().equals("?") && TextUtils.isEmpty(myFirstMessage.toString())) {
  519. myFirstMessage = message;
  520. }
  521. if (popupBubble != null && popupBubble.isShown()) {
  522. popupBubble.hide();
  523. }
  524. if (messagesListView != null) {
  525. messagesListView.smoothScrollToPosition(0);
  526. }
  527. }
  528. @Override
  529. public void onError(Throwable e) {
  530. if (e instanceof HttpException && ((HttpException) e).code() == 201) {
  531. if (conversationUser.getUserId().equals("?") && TextUtils.isEmpty(myFirstMessage.toString())) {
  532. myFirstMessage = message;
  533. }
  534. if (popupBubble != null && popupBubble.isShown()) {
  535. popupBubble.hide();
  536. }
  537. messagesListView.smoothScrollToPosition(0);
  538. } else {
  539. sendMessage(message, attempt + 1);
  540. }
  541. }
  542. @Override
  543. public void onComplete() {
  544. }
  545. });
  546. }
  547. }
  548. private void pullChatMessages(int lookIntoFuture) {
  549. if (!lookingIntoFuture && lookIntoFuture == 1) {
  550. lookingIntoFuture = true;
  551. }
  552. Map<String, Integer> fieldMap = new HashMap<>();
  553. fieldMap.put("lookIntoFuture", lookIntoFuture);
  554. fieldMap.put("limit", 25);
  555. int lastKnown;
  556. if (lookIntoFuture == 1) {
  557. lastKnown = globalLastKnownFutureMessageId;
  558. } else {
  559. lastKnown = globalLastKnownPastMessageId;
  560. }
  561. if (lastKnown != -1) {
  562. fieldMap.put("lastKnownMessageId", lastKnown);
  563. }
  564. if (lookIntoFuture == 1) {
  565. ncApi.pullChatMessages(credentials, ApiUtils.getUrlForChat(baseUrl, roomToken), fieldMap)
  566. .subscribeOn(Schedulers.newThread())
  567. .observeOn(AndroidSchedulers.mainThread())
  568. .takeWhile(observable -> inChat)
  569. .retry(3, observable -> inChat)
  570. .subscribe(new Observer<Response>() {
  571. @Override
  572. public void onSubscribe(Disposable d) {
  573. disposableList.add(d);
  574. }
  575. @Override
  576. public void onNext(Response response) {
  577. processMessages(response, true);
  578. }
  579. @Override
  580. public void onError(Throwable e) {
  581. }
  582. @Override
  583. public void onComplete() {
  584. pullChatMessages(1);
  585. }
  586. });
  587. } else {
  588. ncApi.pullChatMessages(credentials,
  589. ApiUtils.getUrlForChat(baseUrl, roomToken), fieldMap)
  590. .subscribeOn(Schedulers.newThread())
  591. .observeOn(AndroidSchedulers.mainThread())
  592. .retry(3, observable -> inChat)
  593. .subscribe(new Observer<Response>() {
  594. @Override
  595. public void onSubscribe(Disposable d) {
  596. disposableList.add(d);
  597. }
  598. @Override
  599. public void onNext(Response response) {
  600. processMessages(response, false);
  601. }
  602. @Override
  603. public void onError(Throwable e) {
  604. }
  605. @Override
  606. public void onComplete() {
  607. }
  608. });
  609. }
  610. }
  611. private void processMessages(Response response, boolean isFromTheFuture) {
  612. if (response.code() == 200) {
  613. ChatOverall chatOverall = (ChatOverall) response.body();
  614. List<ChatMessage> chatMessageList = chatOverall.getOcs().getData();
  615. if (isFirstMessagesProcessing) {
  616. isFirstMessagesProcessing = false;
  617. if (loadingProgressBar != null) {
  618. loadingProgressBar.setVisibility(View.GONE);
  619. }
  620. if (chatMessageList.size() == 0) {
  621. emptyLayout.setVisibility(View.VISIBLE);
  622. } else {
  623. messagesListView.setVisibility(View.VISIBLE);
  624. }
  625. } else {
  626. if (emptyLayout.getVisibility() != View.GONE) {
  627. emptyLayout.setVisibility(View.GONE);
  628. }
  629. if (messagesListView.getVisibility() != View.VISIBLE) {
  630. messagesListView.setVisibility(View.VISIBLE);
  631. }
  632. }
  633. int countGroupedMessages = 0;
  634. if (!isFromTheFuture) {
  635. for (int i = 0; i < chatMessageList.size(); i++) {
  636. if (chatMessageList.size() > i + 1) {
  637. if (chatMessageList.get(i + 1).getActorId().equals(chatMessageList.get(i).getActorId()) &&
  638. countGroupedMessages < 4 && DateFormatter.isSameDay(chatMessageList.get(i).getCreatedAt(),
  639. chatMessageList.get(i + 1).getCreatedAt())) {
  640. chatMessageList.get(i).setGrouped(true);
  641. countGroupedMessages++;
  642. } else {
  643. countGroupedMessages = 0;
  644. }
  645. }
  646. chatMessageList.get(i).setBaseUrl(conversationUser.getBaseUrl());
  647. if (globalLastKnownPastMessageId == -1 || chatMessageList.get(i).getJsonMessageId() <
  648. globalLastKnownPastMessageId) {
  649. globalLastKnownPastMessageId = chatMessageList.get(i).getJsonMessageId();
  650. }
  651. if (globalLastKnownFutureMessageId == -1) {
  652. if (chatMessageList.get(i).getJsonMessageId() > globalLastKnownFutureMessageId) {
  653. globalLastKnownFutureMessageId = chatMessageList.get(i).getJsonMessageId();
  654. }
  655. }
  656. }
  657. adapter.addToEnd(chatMessageList, false);
  658. } else {
  659. ChatMessage chatMessage;
  660. for (int i = 0; i < chatMessageList.size(); i++) {
  661. chatMessage = chatMessageList.get(i);
  662. chatMessage.setBaseUrl(conversationUser.getBaseUrl());
  663. if (conversationUser.getUserId().equals("?") && !TextUtils.isEmpty(myFirstMessage.toString())) {
  664. if (chatMessage.getActorType().equals("guests") &&
  665. chatMessage.getActorDisplayName().equals(conversationUser.getDisplayName())) {
  666. conversationUser.setUserId(chatMessage.getActorId());
  667. setSenderId();
  668. }
  669. }
  670. boolean shouldScroll = layoutManager.findFirstVisibleItemPosition() == 0 ||
  671. adapter.getItemCount() == 0;
  672. if (!shouldScroll && popupBubble != null) {
  673. if (!popupBubble.isShown()) {
  674. newMessagesCount = 1;
  675. popupBubble.show();
  676. } else if (popupBubble.isShown()) {
  677. newMessagesCount++;
  678. }
  679. } else {
  680. newMessagesCount = 0;
  681. }
  682. chatMessage.setGrouped(adapter.isPreviousSameAuthor(chatMessage.getActorId(), -1) && (adapter.getSameAuthorLastMessagesCount(chatMessage.getActorId()) % 5) > 0);
  683. adapter.addToStart(chatMessage, shouldScroll);
  684. }
  685. String xChatLastGivenHeader;
  686. if (response.headers().size() > 0 && !TextUtils.isEmpty((xChatLastGivenHeader = response.headers().get
  687. ("X-Chat-Last-Given")))) {
  688. globalLastKnownFutureMessageId = Integer.parseInt(xChatLastGivenHeader);
  689. }
  690. }
  691. if (!lookingIntoFuture) {
  692. pullChatMessages(1);
  693. }
  694. } else if (response.code() == 304 && !isFromTheFuture) {
  695. if (isFirstMessagesProcessing) {
  696. isFirstMessagesProcessing = false;
  697. loadingProgressBar.setVisibility(View.GONE);
  698. if (emptyLayout.getVisibility() != View.VISIBLE) {
  699. emptyLayout.setVisibility(View.VISIBLE);
  700. }
  701. }
  702. historyRead = true;
  703. if (!lookingIntoFuture) {
  704. pullChatMessages(1);
  705. }
  706. }
  707. }
  708. @Override
  709. public void onLoadMore(int page, int totalItemsCount) {
  710. if (!historyRead) {
  711. pullChatMessages(0);
  712. }
  713. }
  714. @Override
  715. public String format(Date date) {
  716. if (DateFormatter.isToday(date)) {
  717. return getResources().getString(R.string.nc_date_header_today);
  718. } else if (DateFormatter.isYesterday(date)) {
  719. return getResources().getString(R.string.nc_date_header_yesterday);
  720. } else {
  721. return DateFormatter.format(date, DateFormatter.Template.STRING_DAY_MONTH_YEAR);
  722. }
  723. }
  724. @Override
  725. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  726. super.onCreateOptionsMenu(menu, inflater);
  727. inflater.inflate(R.menu.menu_conversation, menu);
  728. }
  729. @Override
  730. public boolean onOptionsItemSelected(@NonNull MenuItem item) {
  731. switch (item.getItemId()) {
  732. case android.R.id.home:
  733. onDestroy();
  734. return true;
  735. case R.id.conversation_video_call:
  736. startACall(false);
  737. return true;
  738. case R.id.conversation_voice_call:
  739. startACall(true);
  740. return true;
  741. default:
  742. return super.onOptionsItemSelected(item);
  743. }
  744. }
  745. private void startACall(boolean isVoiceOnlyCall) {
  746. if (!isVoiceOnlyCall) {
  747. Intent videoCallIntent = getIntentForCall(false);
  748. if (videoCallIntent != null) {
  749. startActivity(videoCallIntent);
  750. }
  751. } else {
  752. Intent voiceCallIntent = getIntentForCall(true);
  753. if (voiceCallIntent != null) {
  754. startActivity(voiceCallIntent);
  755. }
  756. }
  757. }
  758. private Intent getIntentForCall(boolean isVoiceOnlyCall) {
  759. if (currentCall != null && !TextUtils.isEmpty(currentCall.getSessionId())) {
  760. Bundle bundle = new Bundle();
  761. bundle.putString(BundleKeys.KEY_ROOM_TOKEN, roomToken);
  762. bundle.putString(BundleKeys.KEY_ROOM_ID, roomId);
  763. bundle.putParcelable(BundleKeys.KEY_USER_ENTITY, Parcels.wrap(conversationUser));
  764. bundle.putString(BundleKeys.KEY_CONVERSATION_PASSWORD, roomPassword);
  765. bundle.putString(BundleKeys.KEY_CALL_SESSION, currentCall.getSessionId());
  766. bundle.putString(BundleKeys.KEY_MODIFIED_BASE_URL, baseUrl);
  767. if (isVoiceOnlyCall) {
  768. bundle.putBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, true);
  769. }
  770. if (getActivity() != null) {
  771. Intent callIntent = new Intent(getActivity(), MagicCallActivity.class);
  772. callIntent.putExtras(bundle);
  773. return callIntent;
  774. } else {
  775. return null;
  776. }
  777. } else {
  778. return null;
  779. }
  780. }
  781. @Override
  782. public void onMessageLongClick(IMessage message) {
  783. if (getActivity() != null) {
  784. ClipboardManager clipboardManager = (android.content.ClipboardManager)
  785. getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
  786. ClipData clipData = android.content.ClipData.newPlainText(
  787. getResources().getString(R.string.nc_app_name), message.getText());
  788. if (clipboardManager != null) {
  789. clipboardManager.setPrimaryClip(clipData);
  790. }
  791. }
  792. }
  793. }