ContactsController.java 42 KB

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