ContactsController.java 45 KB

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