ContactsController.java 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017 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.app.SearchManager;
  22. import android.content.Context;
  23. import android.content.Intent;
  24. import android.graphics.PorterDuff;
  25. import android.os.Build;
  26. import android.os.Bundle;
  27. import android.os.Handler;
  28. import android.text.InputType;
  29. import android.util.Log;
  30. import android.view.LayoutInflater;
  31. import android.view.Menu;
  32. import android.view.MenuInflater;
  33. import android.view.MenuItem;
  34. import android.view.View;
  35. import android.view.ViewGroup;
  36. import android.view.inputmethod.EditorInfo;
  37. import android.widget.ImageView;
  38. import android.widget.LinearLayout;
  39. import android.widget.RelativeLayout;
  40. import com.bluelinelabs.conductor.RouterTransaction;
  41. import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler;
  42. import com.bluelinelabs.logansquare.LoganSquare;
  43. import com.kennyc.bottomsheet.BottomSheet;
  44. import com.nextcloud.talk.R;
  45. import com.nextcloud.talk.activities.MagicCallActivity;
  46. import com.nextcloud.talk.adapters.items.GenericTextHeaderItem;
  47. import com.nextcloud.talk.adapters.items.UserItem;
  48. import com.nextcloud.talk.api.NcApi;
  49. import com.nextcloud.talk.application.NextcloudTalkApplication;
  50. import com.nextcloud.talk.controllers.base.BaseController;
  51. import com.nextcloud.talk.controllers.bottomsheet.EntryMenuController;
  52. import com.nextcloud.talk.controllers.bottomsheet.OperationsMenuController;
  53. import com.nextcloud.talk.events.BottomSheetLockEvent;
  54. import com.nextcloud.talk.jobs.AddParticipantsToConversation;
  55. import com.nextcloud.talk.models.RetrofitBucket;
  56. import com.nextcloud.talk.models.database.UserEntity;
  57. import com.nextcloud.talk.models.json.autocomplete.AutocompleteOverall;
  58. import com.nextcloud.talk.models.json.autocomplete.AutocompleteUser;
  59. import com.nextcloud.talk.models.json.conversations.Conversation;
  60. import com.nextcloud.talk.models.json.conversations.RoomOverall;
  61. import com.nextcloud.talk.models.json.converters.EnumActorTypeConverter;
  62. import com.nextcloud.talk.models.json.participants.Participant;
  63. import com.nextcloud.talk.utils.ApiUtils;
  64. import com.nextcloud.talk.utils.ConductorRemapping;
  65. import com.nextcloud.talk.utils.KeyboardUtils;
  66. import com.nextcloud.talk.utils.bundle.BundleKeys;
  67. import com.nextcloud.talk.utils.database.user.UserUtils;
  68. import com.nextcloud.talk.utils.preferences.AppPreferences;
  69. import org.greenrobot.eventbus.EventBus;
  70. import org.greenrobot.eventbus.Subscribe;
  71. import org.greenrobot.eventbus.ThreadMode;
  72. import org.parceler.Parcels;
  73. import java.util.ArrayList;
  74. import java.util.Collections;
  75. import java.util.HashMap;
  76. import java.util.HashSet;
  77. import java.util.List;
  78. import java.util.Map;
  79. import java.util.Set;
  80. import javax.inject.Inject;
  81. import androidx.annotation.NonNull;
  82. import androidx.annotation.Nullable;
  83. import androidx.appcompat.widget.SearchView;
  84. import androidx.coordinatorlayout.widget.CoordinatorLayout;
  85. import androidx.core.content.res.ResourcesCompat;
  86. import androidx.core.view.MenuItemCompat;
  87. import androidx.recyclerview.widget.RecyclerView;
  88. import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
  89. import androidx.work.Data;
  90. import androidx.work.OneTimeWorkRequest;
  91. import androidx.work.WorkManager;
  92. import autodagger.AutoInjector;
  93. import butterknife.BindView;
  94. import butterknife.OnClick;
  95. import butterknife.Optional;
  96. import eu.davidea.fastscroller.FastScroller;
  97. import eu.davidea.flexibleadapter.FlexibleAdapter;
  98. import eu.davidea.flexibleadapter.SelectableAdapter;
  99. import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager;
  100. import eu.davidea.flexibleadapter.items.AbstractFlexibleItem;
  101. import eu.davidea.flexibleadapter.items.IFlexible;
  102. import io.reactivex.Observer;
  103. import io.reactivex.android.schedulers.AndroidSchedulers;
  104. import io.reactivex.disposables.Disposable;
  105. import io.reactivex.schedulers.Schedulers;
  106. import okhttp3.ResponseBody;
  107. @AutoInjector(NextcloudTalkApplication.class)
  108. public class ContactsController extends BaseController implements SearchView.OnQueryTextListener,
  109. FlexibleAdapter.OnItemClickListener, FastScroller.OnScrollStateChangeListener {
  110. public static final String TAG = "ContactsController";
  111. @Nullable
  112. @BindView(R.id.initial_relative_layout)
  113. RelativeLayout initialRelativeLayout;
  114. @Nullable
  115. @BindView(R.id.secondary_relative_layout)
  116. RelativeLayout secondaryRelativeLayout;
  117. @BindView(R.id.loading_content)
  118. LinearLayout loadingContent;
  119. @BindView(R.id.recycler_view)
  120. RecyclerView recyclerView;
  121. @BindView(R.id.swipe_refresh_layout)
  122. SwipeRefreshLayout swipeRefreshLayout;
  123. @BindView(R.id.fast_scroller)
  124. FastScroller fastScroller;
  125. @BindView(R.id.call_header_layout)
  126. RelativeLayout conversationPrivacyToogleLayout;
  127. @BindView(R.id.joinConversationViaLinkRelativeLayout)
  128. RelativeLayout joinConversationViaLinkLayout;
  129. @BindView(R.id.joinConversationViaLinkImageView)
  130. ImageView joinConversationViaLinkImageView;
  131. @BindView(R.id.public_call_link)
  132. ImageView publicCallLinkImageView;
  133. @BindView(R.id.generic_rv_layout)
  134. CoordinatorLayout genericRvLayout;
  135. @Inject
  136. UserUtils userUtils;
  137. @Inject
  138. EventBus eventBus;
  139. @Inject
  140. AppPreferences appPreferences;
  141. @Inject
  142. NcApi ncApi;
  143. private String credentials;
  144. private UserEntity currentUser;
  145. private Disposable contactsQueryDisposable;
  146. private Disposable cacheQueryDisposable;
  147. private FlexibleAdapter adapter;
  148. private List<AbstractFlexibleItem> contactItems;
  149. private BottomSheet bottomSheet;
  150. private View view;
  151. private SmoothScrollLinearLayoutManager layoutManager;
  152. private MenuItem searchItem;
  153. private SearchView searchView;
  154. private boolean isNewConversationView;
  155. private boolean isPublicCall;
  156. private HashMap<String, GenericTextHeaderItem> userHeaderItems = new HashMap<>();
  157. private boolean alreadyFetching = false;
  158. private MenuItem doneMenuItem;
  159. private Set<String> selectedUserIds;
  160. private Set<String> selectedGroupIds;
  161. private Set<String> selectedEmails;
  162. private List<String> existingParticipants;
  163. private boolean isAddingParticipantsView;
  164. private String conversationToken;
  165. public ContactsController() {
  166. super();
  167. setHasOptionsMenu(true);
  168. }
  169. public ContactsController(Bundle args) {
  170. super(args);
  171. setHasOptionsMenu(true);
  172. if (args.containsKey(BundleKeys.INSTANCE.getKEY_NEW_CONVERSATION())) {
  173. isNewConversationView = true;
  174. existingParticipants = new ArrayList<>();
  175. } else if (args.containsKey(BundleKeys.INSTANCE.getKEY_ADD_PARTICIPANTS())) {
  176. isAddingParticipantsView = true;
  177. conversationToken = args.getString(BundleKeys.INSTANCE.getKEY_TOKEN());
  178. existingParticipants = new ArrayList<>();
  179. if (args.containsKey(BundleKeys.INSTANCE.getKEY_EXISTING_PARTICIPANTS())) {
  180. existingParticipants = args.getStringArrayList(BundleKeys.INSTANCE.getKEY_EXISTING_PARTICIPANTS());
  181. }
  182. }
  183. selectedEmails = new HashSet<>();
  184. selectedGroupIds = new HashSet<>();
  185. selectedUserIds = new HashSet<>();
  186. }
  187. @Override
  188. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  189. return inflater.inflate(R.layout.controller_contacts_rv, container, false);
  190. }
  191. @Override
  192. protected void onAttach(@NonNull View view) {
  193. super.onAttach(view);
  194. eventBus.register(this);
  195. if (isNewConversationView) {
  196. toggleNewCallHeaderVisibility(!isPublicCall);
  197. }
  198. if (isAddingParticipantsView) {
  199. joinConversationViaLinkLayout.setVisibility(View.GONE);
  200. conversationPrivacyToogleLayout.setVisibility(View.GONE);
  201. }
  202. }
  203. @Override
  204. protected void onViewBound(@NonNull View view) {
  205. super.onViewBound(view);
  206. NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
  207. currentUser = userUtils.getCurrentUser();
  208. if (currentUser != null) {
  209. credentials = ApiUtils.getCredentials(currentUser.getUsername(), currentUser.getToken());
  210. }
  211. if (adapter == null) {
  212. contactItems = new ArrayList<>();
  213. adapter = new FlexibleAdapter<>(contactItems, getActivity(), false);
  214. if (currentUser != null) {
  215. fetchData(true);
  216. }
  217. }
  218. setupAdapter();
  219. prepareViews();
  220. }
  221. private void setupAdapter() {
  222. adapter.setNotifyChangeOfUnfilteredItems(true)
  223. .setMode(SelectableAdapter.Mode.MULTI);
  224. adapter.setStickyHeaderElevation(5)
  225. .setUnlinkAllItemsOnRemoveHeaders(true)
  226. .setDisplayHeadersAtStartUp(true)
  227. .setStickyHeaders(true);
  228. adapter.addListener(this);
  229. }
  230. private void selectionDone() {
  231. if (!isAddingParticipantsView) {
  232. if (!isPublicCall && (selectedGroupIds.size() + selectedUserIds.size() == 1)) {
  233. String userId;
  234. String roomType = "1";
  235. if (selectedGroupIds.size() == 1) {
  236. roomType = "2";
  237. userId = selectedGroupIds.iterator().next();
  238. } else {
  239. userId = selectedUserIds.iterator().next();
  240. }
  241. int apiVersion = ApiUtils.getConversationApiVersion(currentUser, new int[] {ApiUtils.APIv4, 1});
  242. RetrofitBucket retrofitBucket = ApiUtils.getRetrofitBucketForCreateRoom(apiVersion,
  243. currentUser.getBaseUrl(),
  244. roomType,
  245. userId,
  246. null);
  247. ncApi.createRoom(credentials,
  248. retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
  249. .subscribeOn(Schedulers.io())
  250. .observeOn(AndroidSchedulers.mainThread())
  251. .subscribe(new Observer<RoomOverall>() {
  252. @Override
  253. public void onSubscribe(Disposable d) {
  254. }
  255. @Override
  256. public void onNext(RoomOverall roomOverall) {
  257. Bundle bundle = new Bundle();
  258. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), currentUser);
  259. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), roomOverall.getOcs().getData().getToken());
  260. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), roomOverall.getOcs().getData().getRoomId());
  261. // FIXME once APIv2 or later is used only, the createRoom already returns all the data
  262. ncApi.getRoom(credentials,
  263. ApiUtils.getUrlForRoom(apiVersion, currentUser.getBaseUrl(),
  264. roomOverall.getOcs().getData().getToken()))
  265. .subscribeOn(Schedulers.io())
  266. .observeOn(AndroidSchedulers.mainThread())
  267. .subscribe(new Observer<RoomOverall>() {
  268. @Override
  269. public void onSubscribe(Disposable d) {
  270. }
  271. @Override
  272. public void onNext(RoomOverall roomOverall) {
  273. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
  274. Parcels.wrap(roomOverall.getOcs().getData()));
  275. ConductorRemapping.INSTANCE.remapChatController(getRouter(), currentUser.getId(),
  276. roomOverall.getOcs().getData().getToken(), bundle, true);
  277. }
  278. @Override
  279. public void onError(Throwable e) {
  280. }
  281. @Override
  282. public void onComplete() {
  283. }
  284. });
  285. }
  286. @Override
  287. public void onError(Throwable e) {
  288. }
  289. @Override
  290. public void onComplete() {
  291. }
  292. });
  293. } else {
  294. Bundle bundle = new Bundle();
  295. Conversation.ConversationType roomType;
  296. if (isPublicCall) {
  297. roomType = Conversation.ConversationType.ROOM_PUBLIC_CALL;
  298. } else {
  299. roomType = Conversation.ConversationType.ROOM_GROUP_CALL;
  300. }
  301. ArrayList<String> userIdsArray = new ArrayList<>(selectedUserIds);
  302. ArrayList<String> emailsArray = new ArrayList<>(selectedEmails);
  303. ArrayList<String> groupIdsArray = new ArrayList<>(selectedGroupIds);
  304. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_CONVERSATION_TYPE(), Parcels.wrap(roomType));
  305. bundle.putStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_PARTICIPANTS(), userIdsArray);
  306. bundle.putStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_GROUP(), groupIdsArray);
  307. bundle.putStringArrayList(BundleKeys.INSTANCE.getKEY_INVITED_EMAIL(), emailsArray);
  308. bundle.putInt(BundleKeys.INSTANCE.getKEY_OPERATION_CODE(), 11);
  309. prepareAndShowBottomSheetWithBundle(bundle, true);
  310. }
  311. } else {
  312. String[] userIdsArray = selectedUserIds.toArray(new String[selectedUserIds.size()]);
  313. String[] groupIdsArray = selectedGroupIds.toArray(new String[selectedGroupIds.size()]);
  314. String[] emailsArray = selectedEmails.toArray(new String[selectedEmails.size()]);
  315. Data.Builder data = new Data.Builder();
  316. data.putLong(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), currentUser.getId());
  317. data.putString(BundleKeys.INSTANCE.getKEY_TOKEN(), conversationToken);
  318. data.putStringArray(BundleKeys.INSTANCE.getKEY_SELECTED_USERS(), userIdsArray);
  319. data.putStringArray(BundleKeys.INSTANCE.getKEY_SELECTED_GROUPS(), groupIdsArray);
  320. data.putStringArray(BundleKeys.INSTANCE.getKEY_SELECTED_EMAILS(), emailsArray);
  321. OneTimeWorkRequest addParticipantsToConversationWorker =
  322. new OneTimeWorkRequest.Builder(AddParticipantsToConversation.class).setInputData(data.build()).build();
  323. WorkManager.getInstance().enqueue(addParticipantsToConversationWorker);
  324. getRouter().popCurrentController();
  325. }
  326. }
  327. private void initSearchView() {
  328. if (getActivity() != null) {
  329. SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
  330. if (searchItem != null) {
  331. searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
  332. searchView.setMaxWidth(Integer.MAX_VALUE);
  333. searchView.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER);
  334. int imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_FULLSCREEN;
  335. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && appPreferences.getIsKeyboardIncognito()) {
  336. imeOptions |= EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING;
  337. }
  338. searchView.setImeOptions(imeOptions);
  339. searchView.setQueryHint(getResources().getString(R.string.nc_search));
  340. if (searchManager != null) {
  341. searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
  342. }
  343. searchView.setOnQueryTextListener(this);
  344. }
  345. }
  346. }
  347. @Override
  348. public boolean onOptionsItemSelected(@NonNull MenuItem item) {
  349. switch (item.getItemId()) {
  350. case android.R.id.home:
  351. getRouter().popCurrentController();
  352. return true;
  353. case R.id.contacts_selection_done:
  354. selectionDone();
  355. return true;
  356. default:
  357. return super.onOptionsItemSelected(item);
  358. }
  359. }
  360. @Override
  361. public void onCreateOptionsMenu(Menu menu, @NonNull MenuInflater inflater) {
  362. super.onCreateOptionsMenu(menu, inflater);
  363. inflater.inflate(R.menu.menu_contacts, menu);
  364. searchItem = menu.findItem(R.id.action_search);
  365. doneMenuItem = menu.findItem(R.id.contacts_selection_done);
  366. initSearchView();
  367. }
  368. @Override
  369. public void onPrepareOptionsMenu(@NonNull Menu menu) {
  370. super.onPrepareOptionsMenu(menu);
  371. checkAndHandleDoneMenuItem();
  372. if (adapter.hasFilter()) {
  373. searchItem.expandActionView();
  374. searchView.setQuery((CharSequence) adapter.getFilter(String.class), false);
  375. }
  376. }
  377. private void fetchData(boolean startFromScratch) {
  378. dispose(null);
  379. alreadyFetching = true;
  380. Set<AutocompleteUser> autocompleteUsersHashSet = new HashSet<>();
  381. userHeaderItems = new HashMap<>();
  382. String query = (String) adapter.getFilter(String.class);
  383. RetrofitBucket retrofitBucket = ApiUtils.getRetrofitBucketForContactsSearchFor14(currentUser.getBaseUrl(), query);
  384. Map<String, Object> modifiedQueryMap = new HashMap<String, Object>(retrofitBucket.getQueryMap());
  385. modifiedQueryMap.put("limit", 50);
  386. if (isAddingParticipantsView) {
  387. modifiedQueryMap.put("itemId", conversationToken);
  388. }
  389. List<String> shareTypesList;
  390. shareTypesList = new ArrayList<>();
  391. // users
  392. shareTypesList.add("0");
  393. if (!isAddingParticipantsView) {
  394. // groups
  395. shareTypesList.add("1");
  396. } else if (currentUser.hasSpreedFeatureCapability("invite-groups-and-mails")) {
  397. // groups
  398. shareTypesList.add("1");
  399. // emails
  400. shareTypesList.add("4");
  401. }
  402. modifiedQueryMap.put("shareTypes[]", shareTypesList);
  403. ncApi.getContactsWithSearchParam(
  404. credentials,
  405. retrofitBucket.getUrl(), shareTypesList, modifiedQueryMap)
  406. .subscribeOn(Schedulers.io())
  407. .observeOn(AndroidSchedulers.mainThread())
  408. .retry(3)
  409. .subscribe(new Observer<ResponseBody>() {
  410. @Override
  411. public void onSubscribe(Disposable d) {
  412. contactsQueryDisposable = d;
  413. }
  414. @Override
  415. public void onNext(ResponseBody responseBody) {
  416. if (responseBody != null) {
  417. Participant participant;
  418. List<AbstractFlexibleItem> newUserItemList = new ArrayList<>();
  419. EnumActorTypeConverter actorTypeConverter = new EnumActorTypeConverter();
  420. try {
  421. AutocompleteOverall autocompleteOverall = LoganSquare.parse(responseBody.string(), AutocompleteOverall.class);
  422. autocompleteUsersHashSet.addAll(autocompleteOverall.getOcs().getData());
  423. for (AutocompleteUser autocompleteUser : autocompleteUsersHashSet) {
  424. if (!autocompleteUser.getId().equals(currentUser.getUserId()) && !existingParticipants.contains(autocompleteUser.getId())) {
  425. participant = new Participant();
  426. participant.setActorId(autocompleteUser.getId());
  427. participant.setActorType(actorTypeConverter.getFromString(autocompleteUser.getSource()));
  428. participant.setDisplayName(autocompleteUser.getLabel());
  429. participant.setSource(autocompleteUser.getSource());
  430. String headerTitle;
  431. if (participant.getActorType() != Participant.ActorType.GROUPS) {
  432. headerTitle = participant.getDisplayName().substring(0, 1).toUpperCase();
  433. } else {
  434. headerTitle = getResources().getString(R.string.nc_groups);
  435. }
  436. GenericTextHeaderItem genericTextHeaderItem;
  437. if (!userHeaderItems.containsKey(headerTitle)) {
  438. genericTextHeaderItem = new GenericTextHeaderItem(headerTitle);
  439. userHeaderItems.put(headerTitle, genericTextHeaderItem);
  440. }
  441. UserItem newContactItem = new UserItem(participant, currentUser,
  442. userHeaderItems.get(headerTitle));
  443. if (!contactItems.contains(newContactItem)) {
  444. newUserItemList.add(newContactItem);
  445. }
  446. }
  447. }
  448. } catch (Exception exception) {
  449. Log.e(TAG, "Parsing response body failed while getting contacts");
  450. }
  451. userHeaderItems = new HashMap<>();
  452. contactItems.addAll(newUserItemList);
  453. Collections.sort(newUserItemList, (o1, o2) -> {
  454. String firstName;
  455. String secondName;
  456. if (o1 instanceof UserItem) {
  457. firstName = ((UserItem) o1).getModel().getDisplayName();
  458. } else {
  459. firstName = ((GenericTextHeaderItem) o1).getModel();
  460. }
  461. if (o2 instanceof UserItem) {
  462. secondName = ((UserItem) o2).getModel().getDisplayName();
  463. } else {
  464. secondName = ((GenericTextHeaderItem) o2).getModel();
  465. }
  466. if (o1 instanceof UserItem && o2 instanceof UserItem) {
  467. if ("groups".equals(((UserItem) o1).getModel().getSource()) && "groups".equals(((UserItem) o2).getModel().getSource())) {
  468. return firstName.compareToIgnoreCase(secondName);
  469. } else if ("groups".equals(((UserItem) o1).getModel().getSource())) {
  470. return -1;
  471. } else if ("groups".equals(((UserItem) o2).getModel().getSource())) {
  472. return 1;
  473. }
  474. }
  475. return firstName.compareToIgnoreCase(secondName);
  476. });
  477. Collections.sort(contactItems, (o1, o2) -> {
  478. String firstName;
  479. String secondName;
  480. if (o1 instanceof UserItem) {
  481. firstName = ((UserItem) o1).getModel().getDisplayName();
  482. } else {
  483. firstName = ((GenericTextHeaderItem) o1).getModel();
  484. }
  485. if (o2 instanceof UserItem) {
  486. secondName = ((UserItem) o2).getModel().getDisplayName();
  487. } else {
  488. secondName = ((GenericTextHeaderItem) o2).getModel();
  489. }
  490. if (o1 instanceof UserItem && o2 instanceof UserItem) {
  491. if ("groups".equals(((UserItem) o1).getModel().getSource()) && "groups".equals(((UserItem) o2).getModel().getSource())) {
  492. return firstName.compareToIgnoreCase(secondName);
  493. } else if ("groups".equals(((UserItem) o1).getModel().getSource())) {
  494. return -1;
  495. } else if ("groups".equals(((UserItem) o2).getModel().getSource())) {
  496. return 1;
  497. }
  498. }
  499. return firstName.compareToIgnoreCase(secondName);
  500. });
  501. if (newUserItemList.size() > 0) {
  502. adapter.updateDataSet(newUserItemList);
  503. } else {
  504. adapter.filterItems();
  505. }
  506. if (swipeRefreshLayout != null) {
  507. swipeRefreshLayout.setRefreshing(false);
  508. }
  509. }
  510. }
  511. @Override
  512. public void onError(Throwable e) {
  513. if (swipeRefreshLayout != null) {
  514. swipeRefreshLayout.setRefreshing(false);
  515. }
  516. dispose(contactsQueryDisposable);
  517. }
  518. @Override
  519. public void onComplete() {
  520. if (swipeRefreshLayout != null) {
  521. swipeRefreshLayout.setRefreshing(false);
  522. }
  523. dispose(contactsQueryDisposable);
  524. alreadyFetching = false;
  525. disengageProgressBar();
  526. }
  527. });
  528. }
  529. private void prepareViews() {
  530. layoutManager = new SmoothScrollLinearLayoutManager(getActivity());
  531. recyclerView.setLayoutManager(layoutManager);
  532. recyclerView.setHasFixedSize(true);
  533. recyclerView.setAdapter(adapter);
  534. swipeRefreshLayout.setOnRefreshListener(() -> fetchData(true));
  535. swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
  536. swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.refresh_spinner_background);
  537. fastScroller.addOnScrollStateChangeListener(this);
  538. adapter.setFastScroller(fastScroller);
  539. fastScroller.setBubbleTextCreator(position -> {
  540. IFlexible abstractFlexibleItem = adapter.getItem(position);
  541. if (abstractFlexibleItem instanceof UserItem) {
  542. return ((UserItem) adapter.getItem(position)).getHeader().getModel();
  543. } else if (abstractFlexibleItem instanceof GenericTextHeaderItem) {
  544. return ((GenericTextHeaderItem) adapter.getItem(position)).getModel();
  545. } else {
  546. return "";
  547. }
  548. });
  549. joinConversationViaLinkImageView
  550. .getBackground()
  551. .setColorFilter(ResourcesCompat.getColor(getResources(), R.color.colorBackgroundDarker, null),
  552. PorterDuff.Mode.SRC_IN);
  553. publicCallLinkImageView
  554. .getBackground()
  555. .setColorFilter(ResourcesCompat.getColor(getResources(), R.color.colorPrimary, null),
  556. PorterDuff.Mode.SRC_IN);
  557. disengageProgressBar();
  558. }
  559. private void disengageProgressBar() {
  560. if (!alreadyFetching) {
  561. loadingContent.setVisibility(View.GONE);
  562. genericRvLayout.setVisibility(View.VISIBLE);
  563. if (isNewConversationView) {
  564. conversationPrivacyToogleLayout.setVisibility(View.VISIBLE);
  565. joinConversationViaLinkLayout.setVisibility(View.VISIBLE);
  566. }
  567. }
  568. }
  569. private void dispose(@Nullable Disposable disposable) {
  570. if (disposable != null && !disposable.isDisposed()) {
  571. disposable.dispose();
  572. } else if (disposable == null) {
  573. if (contactsQueryDisposable != null && !contactsQueryDisposable.isDisposed()) {
  574. contactsQueryDisposable.dispose();
  575. contactsQueryDisposable = null;
  576. }
  577. if (cacheQueryDisposable != null && !cacheQueryDisposable.isDisposed()) {
  578. cacheQueryDisposable.dispose();
  579. cacheQueryDisposable = null;
  580. }
  581. }
  582. }
  583. @Override
  584. public void onSaveViewState(@NonNull View view, @NonNull Bundle outState) {
  585. adapter.onSaveInstanceState(outState);
  586. super.onSaveViewState(view, outState);
  587. }
  588. @Override
  589. public void onRestoreViewState(@NonNull View view, @NonNull Bundle savedViewState) {
  590. super.onRestoreViewState(view, savedViewState);
  591. if (adapter != null) {
  592. adapter.onRestoreInstanceState(savedViewState);
  593. }
  594. }
  595. @Override
  596. public void onDestroy() {
  597. super.onDestroy();
  598. dispose(null);
  599. }
  600. @Override
  601. public boolean onQueryTextChange(String newText) {
  602. if (!newText.equals("") && adapter.hasNewFilter(newText)) {
  603. adapter.setFilter(newText);
  604. fetchData(true);
  605. } else if (newText.equals("")) {
  606. adapter.setFilter("");
  607. adapter.updateDataSet(contactItems);
  608. }
  609. if (swipeRefreshLayout != null) {
  610. swipeRefreshLayout.setEnabled(!adapter.hasFilter());
  611. }
  612. return true;
  613. }
  614. @Override
  615. public boolean onQueryTextSubmit(String query) {
  616. return onQueryTextChange(query);
  617. }
  618. private void checkAndHandleDoneMenuItem() {
  619. if (adapter != null && doneMenuItem != null) {
  620. if ((selectedEmails.size() + selectedGroupIds.size() + selectedUserIds.size() > 0) || isPublicCall) {
  621. doneMenuItem.setVisible(true);
  622. } else {
  623. doneMenuItem.setVisible(false);
  624. }
  625. } else if (doneMenuItem != null) {
  626. doneMenuItem.setVisible(false);
  627. }
  628. }
  629. @Override
  630. protected String getTitle() {
  631. if (!isNewConversationView && !isAddingParticipantsView) {
  632. return getResources().getString(R.string.nc_app_name);
  633. } else {
  634. return getResources().getString(R.string.nc_select_contacts);
  635. }
  636. }
  637. @Override
  638. public void onFastScrollerStateChange(boolean scrolling) {
  639. swipeRefreshLayout.setEnabled(!scrolling);
  640. }
  641. private void prepareAndShowBottomSheetWithBundle(Bundle bundle, boolean showEntrySheet) {
  642. if (view == null) {
  643. view = getActivity().getLayoutInflater().inflate(R.layout.bottom_sheet, null, false);
  644. }
  645. if (bottomSheet == null) {
  646. bottomSheet = new BottomSheet.Builder(getActivity()).setView(view).create();
  647. }
  648. if (showEntrySheet) {
  649. getChildRouter((ViewGroup) view).setRoot(
  650. RouterTransaction.with(new EntryMenuController(bundle))
  651. .popChangeHandler(new VerticalChangeHandler())
  652. .pushChangeHandler(new VerticalChangeHandler()));
  653. } else {
  654. getChildRouter((ViewGroup) view).setRoot(
  655. RouterTransaction.with(new OperationsMenuController(bundle))
  656. .popChangeHandler(new VerticalChangeHandler())
  657. .pushChangeHandler(new VerticalChangeHandler()));
  658. }
  659. bottomSheet.setOnShowListener(dialog -> {
  660. if (showEntrySheet) {
  661. new KeyboardUtils(getActivity(), bottomSheet.getLayout(), true);
  662. } else {
  663. eventBus.post(new BottomSheetLockEvent(false, 0,
  664. false, false));
  665. }
  666. });
  667. bottomSheet.setOnDismissListener(dialog -> getActionBar().setDisplayHomeAsUpEnabled(getRouter().getBackstackSize() > 1));
  668. bottomSheet.show();
  669. }
  670. @Subscribe(threadMode = ThreadMode.MAIN)
  671. public void onMessageEvent(BottomSheetLockEvent bottomSheetLockEvent) {
  672. if (bottomSheet != null) {
  673. if (!bottomSheetLockEvent.isCancelable()) {
  674. bottomSheet.setCancelable(bottomSheetLockEvent.isCancelable());
  675. } else {
  676. bottomSheet.setCancelable(bottomSheetLockEvent.isCancelable());
  677. if (bottomSheet.isShowing() && bottomSheetLockEvent.isCancel()) {
  678. new Handler().postDelayed(() -> {
  679. bottomSheet.setOnCancelListener(null);
  680. bottomSheet.cancel();
  681. }, bottomSheetLockEvent.getDelay());
  682. }
  683. }
  684. }
  685. }
  686. @Override
  687. protected void onDetach(@NonNull View view) {
  688. super.onDetach(view);
  689. eventBus.unregister(this);
  690. }
  691. @Override
  692. public boolean onItemClick(View view, int position) {
  693. if (adapter.getItem(position) instanceof UserItem) {
  694. if (!isNewConversationView && !isAddingParticipantsView) {
  695. UserItem userItem = (UserItem) adapter.getItem(position);
  696. String roomType = "1";
  697. if ("groups".equals(userItem.getModel().getSource())) {
  698. roomType = "2";
  699. }
  700. int apiVersion = ApiUtils.getConversationApiVersion(currentUser, new int[] {ApiUtils.APIv4, 1});
  701. RetrofitBucket retrofitBucket = ApiUtils.getRetrofitBucketForCreateRoom(apiVersion,
  702. currentUser.getBaseUrl(),
  703. roomType,
  704. userItem.getModel().getActorId(),
  705. null);
  706. ncApi.createRoom(credentials,
  707. retrofitBucket.getUrl(), retrofitBucket.getQueryMap())
  708. .subscribeOn(Schedulers.io())
  709. .observeOn(AndroidSchedulers.mainThread())
  710. .subscribe(new Observer<RoomOverall>() {
  711. @Override
  712. public void onSubscribe(Disposable d) {
  713. }
  714. @Override
  715. public void onNext(RoomOverall roomOverall) {
  716. if (getActivity() != null) {
  717. Intent conversationIntent = new Intent(getActivity(), MagicCallActivity.class);
  718. Bundle bundle = new Bundle();
  719. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY(), currentUser);
  720. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), roomOverall.getOcs().getData().getToken());
  721. bundle.putString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), roomOverall.getOcs().getData().getRoomId());
  722. conversationIntent.putExtras(bundle);
  723. bundle.putParcelable(BundleKeys.INSTANCE.getKEY_ACTIVE_CONVERSATION(),
  724. Parcels.wrap(roomOverall.getOcs().getData()));
  725. ConductorRemapping.INSTANCE.remapChatController(getRouter(), currentUser.getId(),
  726. roomOverall.getOcs().getData().getToken(), bundle, true);
  727. }
  728. }
  729. @Override
  730. public void onError(Throwable e) {
  731. }
  732. @Override
  733. public void onComplete() {
  734. }
  735. });
  736. } else {
  737. Participant participant = ((UserItem) adapter.getItem(position)).getModel();
  738. participant.setSelected(!participant.isSelected());
  739. if ("groups".equals(participant.getSource())) {
  740. if (participant.isSelected()) {
  741. selectedGroupIds.add(participant.getActorId());
  742. } else {
  743. selectedGroupIds.remove(participant.getActorId());
  744. }
  745. } else if ("emails".equals(participant.getSource())) {
  746. if (participant.isSelected()) {
  747. selectedEmails.add(participant.getActorId());
  748. } else {
  749. selectedEmails.remove(participant.getActorId());
  750. }
  751. } else {
  752. if (participant.isSelected()) {
  753. selectedUserIds.add(participant.getActorId());
  754. } else {
  755. selectedUserIds.remove(participant.getActorId());
  756. }
  757. }
  758. if (currentUser.hasSpreedFeatureCapability("last-room-activity")
  759. && !currentUser.hasSpreedFeatureCapability("invite-groups-and-mails") &&
  760. "groups".equals(((UserItem) adapter.getItem(position)).getModel().getSource()) &&
  761. participant.isSelected() &&
  762. adapter.getSelectedItemCount() > 1) {
  763. List<UserItem> currentItems = adapter.getCurrentItems();
  764. Participant internalParticipant;
  765. for (int i = 0; i < currentItems.size(); i++) {
  766. internalParticipant = currentItems.get(i).getModel();
  767. if (internalParticipant.getActorId().equals(participant.getActorId()) &&
  768. internalParticipant.getActorType() == Participant.ActorType.GROUPS &&
  769. internalParticipant.isSelected()) {
  770. internalParticipant.setSelected(false);
  771. selectedGroupIds.remove(internalParticipant.getActorId());
  772. }
  773. }
  774. }
  775. adapter.notifyDataSetChanged();
  776. checkAndHandleDoneMenuItem();
  777. }
  778. }
  779. return true;
  780. }
  781. @Optional
  782. @OnClick(R.id.joinConversationViaLinkRelativeLayout)
  783. void joinConversationViaLink() {
  784. Bundle bundle = new Bundle();
  785. bundle.putInt(BundleKeys.INSTANCE.getKEY_OPERATION_CODE(), 10);
  786. prepareAndShowBottomSheetWithBundle(bundle, true);
  787. }
  788. @Optional
  789. @OnClick(R.id.call_header_layout)
  790. void toggleCallHeader() {
  791. toggleNewCallHeaderVisibility(isPublicCall);
  792. isPublicCall = !isPublicCall;
  793. if (isPublicCall) {
  794. joinConversationViaLinkLayout.setVisibility(View.GONE);
  795. } else {
  796. joinConversationViaLinkLayout.setVisibility(View.VISIBLE);
  797. }
  798. if (isPublicCall) {
  799. List<AbstractFlexibleItem> currentItems = adapter.getCurrentItems();
  800. Participant internalParticipant;
  801. for (int i = 0; i < currentItems.size(); i++) {
  802. if (currentItems.get(i) instanceof UserItem) {
  803. internalParticipant = ((UserItem) currentItems.get(i)).getModel();
  804. if (internalParticipant.getActorType() == Participant.ActorType.GROUPS &&
  805. internalParticipant.isSelected()) {
  806. internalParticipant.setSelected(false);
  807. selectedGroupIds.remove(internalParticipant.getActorId());
  808. }
  809. }
  810. }
  811. }
  812. for (int i = 0; i < adapter.getItemCount(); i++) {
  813. if (adapter.getItem(i) instanceof UserItem) {
  814. UserItem userItem = (UserItem) adapter.getItem(i);
  815. if ("groups".equals(userItem.getModel().getSource())) {
  816. userItem.setEnabled(!isPublicCall);
  817. }
  818. }
  819. }
  820. checkAndHandleDoneMenuItem();
  821. adapter.notifyDataSetChanged();
  822. }
  823. private void toggleNewCallHeaderVisibility(boolean showInitialLayout) {
  824. if (showInitialLayout) {
  825. if (initialRelativeLayout != null) {
  826. initialRelativeLayout.setVisibility(View.VISIBLE);
  827. }
  828. if (secondaryRelativeLayout != null) {
  829. secondaryRelativeLayout.setVisibility(View.GONE);
  830. }
  831. } else {
  832. if (initialRelativeLayout != null) {
  833. initialRelativeLayout.setVisibility(View.GONE);
  834. }
  835. if (secondaryRelativeLayout != null) {
  836. secondaryRelativeLayout.setVisibility(View.VISIBLE);
  837. }
  838. }
  839. }
  840. }