ChatController.java 37 KB

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