1/*
2 * Copyright (c) 2018, Daniel Gultsch All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without modification,
5 * are permitted provided that the following conditions are met:
6 *
7 * 1. Redistributions of source code must retain the above copyright notice, this
8 * list of conditions and the following disclaimer.
9 *
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation and/or
12 * other materials provided with the distribution.
13 *
14 * 3. Neither the name of the copyright holder nor the names of its contributors
15 * may be used to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30package eu.siacs.conversations.ui;
31
32import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
33
34import android.Manifest;
35import android.annotation.SuppressLint;
36import android.app.Activity;
37import android.app.Fragment;
38import android.app.FragmentManager;
39import android.app.FragmentTransaction;
40import android.content.ActivityNotFoundException;
41import android.content.ComponentName;
42import android.content.Context;
43import android.content.Intent;
44import android.content.pm.PackageManager;
45import android.graphics.Bitmap;
46import android.net.Uri;
47import android.os.Build;
48import android.os.Bundle;
49import android.provider.Settings;
50import android.util.Log;
51import android.util.Pair;
52import android.view.KeyEvent;
53import android.view.Menu;
54import android.view.MenuItem;
55import android.widget.Toast;
56
57import androidx.annotation.IdRes;
58import androidx.annotation.NonNull;
59import androidx.appcompat.app.ActionBar;
60import androidx.appcompat.app.AlertDialog;
61import androidx.core.app.ActivityCompat;
62import androidx.core.content.ContextCompat;
63import androidx.databinding.DataBindingUtil;
64
65import com.cheogram.android.DownloadDefaultStickers;
66import com.cheogram.android.FinishOnboarding;
67
68import com.google.common.collect.ImmutableList;
69
70import io.michaelrocks.libphonenumber.android.NumberParseException;
71import com.google.android.material.dialog.MaterialAlertDialogBuilder;
72import com.google.android.material.color.MaterialColors;
73
74import org.openintents.openpgp.util.OpenPgpApi;
75
76import java.util.Arrays;
77import java.util.ArrayList;
78import java.util.HashSet;
79import java.util.HashMap;
80import java.util.List;
81import java.util.Objects;
82import java.util.Set;
83import java.util.TreeMap;
84import java.util.concurrent.atomic.AtomicBoolean;
85import java.util.stream.Collectors;
86import java.util.stream.Stream;
87
88import eu.siacs.conversations.Config;
89import eu.siacs.conversations.R;
90import eu.siacs.conversations.crypto.OmemoSetting;
91import eu.siacs.conversations.databinding.ActivityConversationsBinding;
92import eu.siacs.conversations.entities.Account;
93import eu.siacs.conversations.entities.Contact;
94import eu.siacs.conversations.entities.Conversation;
95import eu.siacs.conversations.entities.Conversational;
96import eu.siacs.conversations.entities.ListItem.Tag;
97import eu.siacs.conversations.persistance.FileBackend;
98import eu.siacs.conversations.services.XmppConnectionService;
99import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
100import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
101import eu.siacs.conversations.ui.interfaces.OnConversationRead;
102import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
103import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
104import eu.siacs.conversations.ui.util.ActivityResult;
105import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
106import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
107import eu.siacs.conversations.ui.util.PendingItem;
108import eu.siacs.conversations.ui.util.ToolbarUtils;
109import eu.siacs.conversations.utils.AccountUtils;
110import eu.siacs.conversations.utils.ExceptionHelper;
111import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
112import eu.siacs.conversations.utils.SignupUtils;
113import eu.siacs.conversations.utils.ThemeHelper;
114import eu.siacs.conversations.utils.XmppUri;
115import eu.siacs.conversations.xmpp.Jid;
116import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
117
118public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged {
119
120 public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
121 public static final String EXTRA_CONVERSATION = "conversationUuid";
122 public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
123 public static final String EXTRA_AS_QUOTE = "eu.siacs.conversations.as_quote";
124 public static final String EXTRA_NICK = "nick";
125 public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
126 public static final String EXTRA_DO_NOT_APPEND = "do_not_append";
127 public static final String EXTRA_POST_INIT_ACTION = "post_init_action";
128 public static final String POST_ACTION_RECORD_VOICE = "record_voice";
129 public static final String EXTRA_THREAD = "threadId";
130 public static final String EXTRA_TYPE = "type";
131 public static final String EXTRA_NODE = "node";
132 public static final String EXTRA_JID = "jid";
133
134 private static final List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList(
135 ACTION_VIEW_CONVERSATION,
136 Intent.ACTION_SEND,
137 Intent.ACTION_SEND_MULTIPLE
138 );
139
140 public static final int REQUEST_OPEN_MESSAGE = 0x9876;
141 public static final int REQUEST_PLAY_PAUSE = 0x5432;
142 public static final int REQUEST_MICROPHONE = 0x5432f;
143 public static final int DIALLER_INTEGRATION = 0x5432ff;
144 public static final int REQUEST_DOWNLOAD_STICKERS = 0xbf8702;
145
146 public static final long DRAWER_ALL_CHATS = 1;
147 public static final long DRAWER_DIRECT_MESSAGES = 2;
148 public static final long DRAWER_MANAGE_ACCOUNT = 3;
149 public static final long DRAWER_MANAGE_PHONE_ACCOUNTS = 4;
150 public static final long DRAWER_CHANNELS = 5;
151 public static final long DRAWER_SETTINGS = 6;
152 public static final long DRAWER_START_CHAT = 7;
153 public static final long DRAWER_START_CHAT_CONTACT = 8;
154 public static final long DRAWER_START_CHAT_NEW = 9;
155 public static final long DRAWER_START_CHAT_GROUP = 10;
156 public static final long DRAWER_START_CHAT_PUBLIC = 11;
157 public static final long DRAWER_START_CHAT_DISCOVER = 12;
158
159 //secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
160 private static final @IdRes
161 int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
162 private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
163 private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
164 private ActivityConversationsBinding binding;
165 private boolean mActivityPaused = true;
166 private final AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
167 private boolean refreshForNewCaps = false;
168 private Set<Jid> newCapsJids = new HashSet<>();
169 private int mRequestCode = -1;
170 private com.mikepenz.materialdrawer.widget.AccountHeaderView accountHeader;
171 private Bundle savedState = null;
172 private Tag selectedTag = null;
173 private long mainFilter = DRAWER_ALL_CHATS;
174 private boolean refreshAccounts = true;
175
176 private static boolean isViewOrShareIntent(Intent i) {
177 Log.d(Config.LOGTAG, "action: " + (i == null ? null : i.getAction()));
178 return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
179 }
180
181 private static Intent createLauncherIntent(Context context) {
182 final Intent intent = new Intent(context, ConversationsActivity.class);
183 intent.setAction(Intent.ACTION_MAIN);
184 intent.addCategory(Intent.CATEGORY_LAUNCHER);
185 return intent;
186 }
187
188 @Override
189 protected void refreshUiReal() {
190 invalidateOptionsMenu();
191 for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
192 refreshFragment(id);
193 }
194 refreshForNewCaps = false;
195 newCapsJids.clear();
196
197 if (accountHeader == null) return;
198
199 accountHeader.apply(ah -> {
200 if (!refreshAccounts) return kotlin.Unit.INSTANCE;
201 refreshAccounts = false;
202 final var accounts = xmppConnectionService.getAccounts();
203 final var inHeader = new HashSet<>();
204 for (final var p : ImmutableList.copyOf(accountHeader.getProfiles())) {
205 if (p instanceof com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem) continue;
206 if (accounts.contains(p.getTag()) || (accounts.size() > 1 && p.getTag() == null)) {
207 inHeader.add(p.getTag());
208 } else {
209 accountHeader.removeProfile(p);
210 }
211 }
212
213 if (accounts.size() > 1 && !inHeader.contains(null)) {
214 final var all = new com.mikepenz.materialdrawer.model.ProfileDrawerItem();
215 all.setIdentifier(100);
216 com.mikepenz.materialdrawer.model.interfaces.DescribableKt.setDescriptionText(all, "All Accounts");
217 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(all, R.drawable.main_logo);
218 accountHeader.addProfile(all, 0);
219 }
220
221 accountHeader.removeProfileByIdentifier(DRAWER_MANAGE_PHONE_ACCOUNTS);
222 final var hasPhoneAccounts = accounts.stream().anyMatch(a -> a.getGateways("pstn").size() > 0);
223 if (hasPhoneAccounts) {
224 final var phoneAccounts = new com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem();
225 phoneAccounts.setIdentifier(DRAWER_MANAGE_PHONE_ACCOUNTS);
226 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(phoneAccounts, "Manage Phone Accounts");
227 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(phoneAccounts, R.drawable.ic_call_24dp);
228 accountHeader.addProfile(phoneAccounts, accountHeader.getProfiles().size() - 1);
229 }
230
231 long id = 101;
232 for (final var a : accounts) {
233 final var avatar = xmppConnectionService.getAvatarService().get(a, (int) getResources().getDimension(R.dimen.avatar_on_drawer), false);
234 final var p = new com.mikepenz.materialdrawer.model.ProfileDrawerItem();
235 p.setIdentifier(id++);
236 p.setTag(a);
237 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(p, a.getDisplayName() == null ? "" : a.getDisplayName());
238 com.mikepenz.materialdrawer.model.interfaces.DescribableKt.setDescriptionText(p, a.getJid().asBareJid().toString());
239 if (avatar != null) com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconBitmap(p, FileBackend.drawDrawable(avatar).copy(Bitmap.Config.ARGB_8888, false));
240 if (inHeader.contains(a)) {
241 accountHeader.updateProfile(p);
242 } else {
243 accountHeader.addProfile(p, accountHeader.getProfiles().size() - (hasPhoneAccounts ? 2 : 1));
244 }
245 }
246 return kotlin.Unit.INSTANCE;
247 });
248
249 binding.drawer.apply(dr -> {
250 final var items = binding.drawer.getItemAdapter().getAdapterItems();
251 final var tags = new TreeMap<Tag, Integer>();
252 final var conversations = new ArrayList<Conversation>();
253 populateWithOrderedConversations(conversations, false, false);
254 for (final var c : conversations) {
255 for (final var tag : c.getTags(this)) {
256 if ("Channel".equals(tag.getName())) continue;
257 var count = tags.get(tag);
258 if (count == null) count = 0;
259 tags.put(tag, count + c.unreadCount());
260 }
261 }
262
263 long id = 1000;
264 final var inDrawer = new HashMap<Tag, Long>();
265 for (final var item : ImmutableList.copyOf(items)) {
266 if (item.getIdentifier() >= 1000 && !tags.containsKey(item.getTag())) {
267 com.mikepenz.materialdrawer.util.MaterialDrawerSliderViewExtensionsKt.removeItems(binding.drawer, item);
268 } else if (item.getIdentifier() >= 1000) {
269 inDrawer.put((Tag)item.getTag(), item.getIdentifier());
270 id = item.getIdentifier() + 1;
271 }
272 }
273
274 for (final var entry : tags.entrySet()) {
275 final var badge = entry.getValue() > 0 ? entry.getValue().toString() : null;
276 if (inDrawer.containsKey(entry.getKey())) {
277 com.mikepenz.materialdrawer.util.MaterialDrawerSliderViewExtensionsKt.updateBadge(
278 binding.drawer,
279 inDrawer.get(entry.getKey()),
280 new com.mikepenz.materialdrawer.holder.StringHolder(badge)
281 );
282 } else {
283 final var item = new com.mikepenz.materialdrawer.model.SecondaryDrawerItem();
284 item.setIdentifier(id++);
285 item.setTag(entry.getKey());
286 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(item, entry.getKey().getName());
287 if (badge != null) com.mikepenz.materialdrawer.model.interfaces.BadgeableKt.setBadgeText(item, badge);
288 final var color = MaterialColors.getColor(binding.drawer, com.google.android.material.R.attr.colorPrimaryContainer);
289 final var textColor = MaterialColors.getColor(binding.drawer, com.google.android.material.R.attr.colorOnPrimaryContainer);
290 item.setBadgeStyle(new com.mikepenz.materialdrawer.holder.BadgeStyle(com.mikepenz.materialdrawer.R.drawable.material_drawer_badge, color, color, textColor));
291 binding.drawer.getItemAdapter().add(binding.drawer.getItemAdapter().getGlobalPosition(4), item);
292 }
293 }
294
295 items.subList(4, 4 + tags.size()).sort((x, y) -> x.getTag() == null ? -1 : ((Comparable) x.getTag()).compareTo(y.getTag()));
296 binding.drawer.getItemAdapter().getFastAdapter().notifyDataSetChanged();
297 return kotlin.Unit.INSTANCE;
298 });
299 }
300
301 @Override
302 protected void onBackendConnected() {
303 final var useSavedState = savedState;
304 savedState = null;
305 if (performRedirectIfNecessary(true)) {
306 return;
307 }
308 xmppConnectionService.getNotificationService().setIsInForeground(true);
309 final Intent intent = pendingViewIntent.pop();
310 if (intent != null) {
311 if (processViewIntent(intent)) {
312 if (binding.secondaryFragment != null) {
313 notifyFragmentOfBackendConnected(R.id.main_fragment);
314 }
315 invalidateActionBarTitle();
316 return;
317 }
318 }
319 for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
320 notifyFragmentOfBackendConnected(id);
321 }
322
323 final ActivityResult activityResult = postponedActivityResult.pop();
324 if (activityResult != null) {
325 handleActivityResult(activityResult);
326 }
327
328 if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
329 Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
330 if (conversation != null) {
331 openConversation(conversation, null);
332 }
333 }
334 showDialogsIfMainIsOverview();
335
336 if (accountHeader != null || binding == null || binding.drawer == null) {
337 refreshUiReal();
338 return;
339 }
340
341 accountHeader = new com.mikepenz.materialdrawer.widget.AccountHeaderView(this);
342 final var manageAccount = new com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem();
343 manageAccount.setIdentifier(DRAWER_MANAGE_ACCOUNT);
344 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(manageAccount, xmppConnectionService.getAccounts().size() > 1 ? "Manage Accounts" : "Manage Account");
345 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(manageAccount, R.drawable.ic_settings_24dp);
346 accountHeader.addProfiles(manageAccount);
347
348 final var allChats = new com.mikepenz.materialdrawer.model.PrimaryDrawerItem();
349 allChats.setIdentifier(DRAWER_ALL_CHATS);
350 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(allChats, "All Chats");
351 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(allChats, R.drawable.ic_chat_24dp);
352
353 final var directMessages = new com.mikepenz.materialdrawer.model.PrimaryDrawerItem();
354 directMessages.setIdentifier(DRAWER_DIRECT_MESSAGES);
355 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(directMessages, "Direct Messages");
356 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(directMessages, R.drawable.ic_person_24dp);
357
358 final var channels = new com.mikepenz.materialdrawer.model.PrimaryDrawerItem();
359 channels.setIdentifier(DRAWER_CHANNELS);
360 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(channels, "Channels");
361 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(channels, R.drawable.ic_group_24dp);
362
363 final var startChat = new com.mikepenz.materialdrawer.model.ExpandableDrawerItem();
364 startChat.setIdentifier(DRAWER_START_CHAT);
365 startChat.setSelectable(false);
366 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(startChat, "Start Chat");
367 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(startChat, R.drawable.ic_chat_24dp);
368
369 final var startChatWithContact = new com.mikepenz.materialdrawer.model.SecondaryDrawerItem();
370 startChatWithContact.setIdentifier(DRAWER_START_CHAT_CONTACT);
371 startChatWithContact.setSelectable(false);
372 startChatWithContact.setLevel(2);
373 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(startChatWithContact, "With Contact");
374 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(startChatWithContact, R.drawable.ic_person_24dp);
375
376 final var startChatWithNew = new com.mikepenz.materialdrawer.model.SecondaryDrawerItem();
377 startChatWithNew.setIdentifier(DRAWER_START_CHAT_NEW);
378 startChatWithNew.setSelectable(false);
379 startChatWithNew.setLevel(2);
380 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameRes(startChatWithNew, R.string.new_contact);
381 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(startChatWithNew, R.drawable.ic_person_add_24dp);
382
383 final var startChatWithGroup = new com.mikepenz.materialdrawer.model.SecondaryDrawerItem();
384 startChatWithGroup.setIdentifier(DRAWER_START_CHAT_GROUP);
385 startChatWithGroup.setSelectable(false);
386 startChatWithGroup.setLevel(2);
387 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameRes(startChatWithGroup, R.string.create_private_group_chat);
388 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(startChatWithGroup, R.drawable.ic_group_24dp);
389
390 final var startChatPublic = new com.mikepenz.materialdrawer.model.SecondaryDrawerItem();
391 startChatPublic.setIdentifier(DRAWER_START_CHAT_PUBLIC);
392 startChatPublic.setSelectable(false);
393 startChatPublic.setLevel(2);
394 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameRes(startChatPublic, R.string.create_public_channel);
395 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(startChatPublic, R.drawable.ic_public_24dp);
396
397 final var startChatDiscover = new com.mikepenz.materialdrawer.model.SecondaryDrawerItem();
398 startChatDiscover.setIdentifier(DRAWER_START_CHAT_DISCOVER);
399 startChatDiscover.setSelectable(false);
400 startChatDiscover.setLevel(2);
401 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameRes(startChatDiscover, R.string.discover_channels);
402 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(startChatDiscover, R.drawable.ic_travel_explore_24dp);
403
404 startChat.setSubItems(startChatWithContact, startChatWithNew, startChatWithGroup, startChatPublic, startChatDiscover);
405
406 binding.drawer.getItemAdapter().add(
407 allChats,
408 directMessages,
409 channels,
410 new com.mikepenz.materialdrawer.model.DividerDrawerItem(),
411 new com.mikepenz.materialdrawer.model.DividerDrawerItem(),
412 startChat
413 );
414
415 final var settings = new com.mikepenz.materialdrawer.model.PrimaryDrawerItem();
416 settings.setIdentifier(DRAWER_SETTINGS);
417 settings.setSelectable(false);
418 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(settings, "Settings");
419 com.mikepenz.materialdrawer.model.interfaces.IconableKt.setIconRes(settings, R.drawable.ic_settings_24dp);
420 com.mikepenz.materialdrawer.util.MaterialDrawerSliderViewExtensionsKt.addStickyDrawerItems(binding.drawer, settings);
421
422 if (useSavedState != null) {
423 mainFilter = useSavedState.getLong("mainFilter", DRAWER_ALL_CHATS);
424 selectedTag = (Tag) useSavedState.getSerializable("selectedTag");
425 }
426 refreshUiReal();
427 if (useSavedState != null) binding.drawer.setSavedInstance(useSavedState);
428 accountHeader.attachToSliderView(binding.drawer);
429 if (useSavedState != null) accountHeader.withSavedInstance(useSavedState);
430
431 if (mainFilter == DRAWER_ALL_CHATS && selectedTag == null) {
432 binding.drawer.setSelectedItemIdentifier(DRAWER_ALL_CHATS);
433 }
434
435 binding.drawer.setOnDrawerItemClickListener((v, drawerItem, pos) -> {
436 final var id = drawerItem.getIdentifier();
437 if (id != DRAWER_START_CHAT) binding.drawer.getExpandableExtension().collapse(false);
438 if (id == DRAWER_SETTINGS) {
439 startActivity(new Intent(this, eu.siacs.conversations.ui.activity.SettingsActivity.class));
440 return false;
441 } else if (id == DRAWER_START_CHAT_CONTACT) {
442 launchStartConversation();
443 } else if (id == DRAWER_START_CHAT_NEW) {
444 launchStartConversation(R.id.create_contact);
445 } else if (id == DRAWER_START_CHAT_GROUP) {
446 launchStartConversation(R.id.create_private_group_chat);
447 } else if (id == DRAWER_START_CHAT_PUBLIC) {
448 launchStartConversation(R.id.create_public_channel);
449 } else if (id == DRAWER_START_CHAT_DISCOVER) {
450 launchStartConversation(R.id.discover_public_channels);
451 } else if (id == DRAWER_ALL_CHATS || id == DRAWER_DIRECT_MESSAGES || id == DRAWER_CHANNELS) {
452 selectedTag = null;
453 mainFilter = id;
454 binding.drawer.getSelectExtension().deselect();
455 } else if (id >= 1000) {
456 selectedTag = (Tag) drawerItem.getTag();
457 }
458 binding.drawer.getSelectExtension().selectByIdentifier(mainFilter, false, true);
459
460 final var fm = getFragmentManager();
461 while (fm.getBackStackEntryCount() > 0) {
462 try {
463 fm.popBackStackImmediate();
464 } catch (IllegalStateException e) {
465 break;
466 }
467 }
468
469 refreshUi();
470 return false;
471 });
472
473 accountHeader.setOnAccountHeaderListener((v, profile, isCurrent) -> {
474 final var id = profile.getIdentifier();
475 if (isCurrent) return false; // Ignore switching to already selected profile
476
477 if (id == DRAWER_MANAGE_ACCOUNT) {
478 final Account account = (Account) accountHeader.getActiveProfile().getTag();
479 if (account == null) {
480 AccountUtils.launchManageAccounts(this);
481 } else {
482 switchToAccount(account);
483 }
484 return false;
485 }
486
487 if (id == DRAWER_MANAGE_PHONE_ACCOUNTS) {
488 final String[] permissions;
489 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
490 permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.BLUETOOTH_CONNECT};
491 } else {
492 permissions = new String[]{Manifest.permission.RECORD_AUDIO};
493 }
494 requestPermissions(permissions, REQUEST_MICROPHONE);
495 return false;
496 }
497
498 // Clicked on an actual profile
499 if (profile.getTag() == null) {
500 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(manageAccount, "Manage Accounts");
501 } else {
502 com.mikepenz.materialdrawer.model.interfaces.NameableKt.setNameText(manageAccount, "Manage Account");
503 }
504 accountHeader.updateProfile(manageAccount);
505
506 final var fm = getFragmentManager();
507 while (fm.getBackStackEntryCount() > 0) {
508 try {
509 fm.popBackStackImmediate();
510 } catch (IllegalStateException e) {
511 break;
512 }
513 }
514
515 refreshUi();
516
517 return false;
518 });
519
520 accountHeader.setOnAccountHeaderProfileImageListener((v, profile, isCurrent) -> {
521 if (isCurrent) {
522 final Account account = (Account) accountHeader.getActiveProfile().getTag();
523 if (account == null) {
524 AccountUtils.launchManageAccounts(this);
525 } else {
526 switchToAccount(account);
527 }
528 }
529 return false;
530 });
531 }
532
533 @Override
534 public boolean colorCodeAccounts() {
535 if (accountHeader != null) {
536 final var active = accountHeader.getActiveProfile();
537 if (active != null && active.getTag() != null) return false;
538 }
539 return super.colorCodeAccounts();
540 }
541
542 @Override
543 public void populateWithOrderedConversations(List<Conversation> list) {
544 populateWithOrderedConversations(list, true, true);
545 }
546
547 public void populateWithOrderedConversations(List<Conversation> list, final boolean tagFilter, final boolean sort) {
548 if (sort) {
549 super.populateWithOrderedConversations(list);
550 } else {
551 list.addAll(xmppConnectionService.getConversations());
552 }
553 if (accountHeader == null || accountHeader.getActiveProfile() == null) return;
554
555 final var selectedAccount =
556 accountHeader.getActiveProfile().getTag() != null ?
557 ((Account) accountHeader.getActiveProfile().getTag()).getUuid() :
558 null;
559
560 for (final var c : ImmutableList.copyOf(list)) {
561 if (mainFilter == DRAWER_CHANNELS && c.getMode() != Conversation.MODE_MULTI) {
562 list.remove(c);
563 } else if (mainFilter == DRAWER_DIRECT_MESSAGES && c.getMode() == Conversation.MODE_MULTI) {
564 list.remove(c);
565 } else if (selectedAccount != null && !selectedAccount.equals(c.getAccount().getUuid())) {
566 list.remove(c);
567 } else if (selectedTag != null && tagFilter && !c.getTags(this).contains(selectedTag)) {
568 list.remove(c);
569 }
570 }
571 }
572
573 @Override
574 public void launchStartConversation() {
575 launchStartConversation(0);
576 }
577
578 public void launchStartConversation(int goTo) {
579 StartConversationActivity.launch(this, (Account) accountHeader.getActiveProfile().getTag(), selectedTag == null ? null : selectedTag.getName(), goTo);
580 }
581
582 private boolean performRedirectIfNecessary(boolean noAnimation) {
583 return performRedirectIfNecessary(null, noAnimation);
584 }
585
586 private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
587 if (xmppConnectionService == null) {
588 return false;
589 }
590
591 boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
592 if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
593 final Intent intent = SignupUtils.getRedirectionIntent(this);
594 if (noAnimation) {
595 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
596 }
597 runOnUiThread(() -> {
598 startActivity(intent);
599 if (noAnimation) {
600 overridePendingTransition(0, 0);
601 }
602 });
603 }
604 return mRedirectInProcess.get();
605 }
606
607 private void showDialogsIfMainIsOverview() {
608 Pair<Account, Account> incomplete = null;
609 if (xmppConnectionService != null && (incomplete = xmppConnectionService.onboardingIncomplete()) != null) {
610 FinishOnboarding.finish(xmppConnectionService, this, incomplete.first, incomplete.second);
611 }
612 if (xmppConnectionService == null || xmppConnectionService.isOnboarding()) {
613 return;
614 }
615 final Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
616 if (fragment instanceof ConversationsOverviewFragment) {
617 if (ExceptionHelper.checkForCrash(this)) return;
618 if (offerToSetupDiallerIntegration()) return;
619 if (offerToDownloadStickers()) return;
620 if (openBatteryOptimizationDialogIfNeeded()) return;
621 requestNotificationPermissionIfNeeded();
622 xmppConnectionService.rescanStickers();
623 }
624 }
625
626 private String getBatteryOptimizationPreferenceKey() {
627 @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
628 return "show_battery_optimization" + (device == null ? "" : device);
629 }
630
631 private void setNeverAskForBatteryOptimizationsAgain() {
632 getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
633 }
634
635 private boolean openBatteryOptimizationDialogIfNeeded() {
636 if (isOptimizingBattery() && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
637 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
638 builder.setTitle(R.string.battery_optimizations_enabled);
639 builder.setMessage(getString(R.string.battery_optimizations_enabled_dialog, getString(R.string.app_name)));
640 builder.setPositiveButton(R.string.next, (dialog, which) -> {
641 final Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
642 final Uri uri = Uri.parse("package:" + getPackageName());
643 intent.setData(uri);
644 try {
645 startActivityForResult(intent, REQUEST_BATTERY_OP);
646 } catch (final ActivityNotFoundException e) {
647 Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
648 }
649 });
650 builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
651 final AlertDialog dialog = builder.create();
652 dialog.setCanceledOnTouchOutside(false);
653 dialog.show();
654 return true;
655 }
656 return false;
657 }
658
659 private void requestNotificationPermissionIfNeeded() {
660 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
661 requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_POST_NOTIFICATION);
662 }
663 }
664
665 private boolean offerToDownloadStickers() {
666 int offered = getPreferences().getInt("default_stickers_offered", 0);
667 if (offered > 0) return false;
668 getPreferences().edit().putInt("default_stickers_offered", 1).apply();
669
670 AlertDialog.Builder builder = new AlertDialog.Builder(this);
671 builder.setTitle("Download Stickers?");
672 builder.setMessage("Would you like to download some default sticker packs?");
673 builder.setPositiveButton(R.string.yes, (dialog, which) -> {
674 if (hasStoragePermission(REQUEST_DOWNLOAD_STICKERS)) {
675 downloadStickers();
676 }
677 });
678 builder.setNegativeButton(R.string.no, (dialog, which) -> {
679 showDialogsIfMainIsOverview();
680 });
681 final AlertDialog dialog = builder.create();
682 dialog.setCanceledOnTouchOutside(false);
683 dialog.show();
684 return true;
685 }
686
687 private boolean offerToSetupDiallerIntegration() {
688 if (mRequestCode == DIALLER_INTEGRATION) {
689 mRequestCode = -1;
690 return true;
691 }
692 if (Build.VERSION.SDK_INT < 23) return false;
693 if (Build.VERSION.SDK_INT >= 33) {
694 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELECOM) && !getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) return false;
695 } else {
696 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) return false;
697 }
698
699 Set<String> pstnGateways = xmppConnectionService.getAccounts().stream()
700 .flatMap(a -> a.getGateways("pstn").stream())
701 .map(a -> a.getJid().asBareJid().toString()).collect(Collectors.toSet());
702
703 if (pstnGateways.size() < 1) return false;
704 Set<String> fromPrefs = getPreferences().getStringSet("pstn_gateways", Set.of("UPGRADE"));
705 getPreferences().edit().putStringSet("pstn_gateways", pstnGateways).apply();
706 pstnGateways.removeAll(fromPrefs);
707 if (pstnGateways.size() < 1) return false;
708
709 if (fromPrefs.contains("UPGRADE")) return false;
710
711 AlertDialog.Builder builder = new AlertDialog.Builder(this);
712 builder.setTitle("Dialler Integration");
713 builder.setMessage("Cheogram Android is able to integrate with your system's dialler app to allow dialling calls via your configured gateway " + String.join(", ", pstnGateways) + ".\n\nEnabling this integration will require granting microphone permission to the app. Would you like to enable it now?");
714 builder.setPositiveButton(R.string.yes, (dialog, which) -> {
715 final String[] permissions;
716 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
717 permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.BLUETOOTH_CONNECT};
718 } else {
719 permissions = new String[]{Manifest.permission.RECORD_AUDIO};
720 }
721 requestPermissions(permissions, REQUEST_MICROPHONE);
722 });
723 builder.setNegativeButton(R.string.no, (dialog, which) -> {
724 showDialogsIfMainIsOverview();
725 });
726 final AlertDialog dialog = builder.create();
727 dialog.setCanceledOnTouchOutside(false);
728 dialog.show();
729 return true;
730 }
731
732 private void notifyFragmentOfBackendConnected(@IdRes int id) {
733 final Fragment fragment = getFragmentManager().findFragmentById(id);
734 if (fragment instanceof OnBackendConnected callback) {
735 callback.onBackendConnected();
736 }
737 }
738
739 private void refreshFragment(@IdRes int id) {
740 final Fragment fragment = getFragmentManager().findFragmentById(id);
741 if (fragment instanceof XmppFragment xmppFragment) {
742 xmppFragment.refresh();
743 if (refreshForNewCaps) xmppFragment.refreshForNewCaps(newCapsJids);
744 }
745 }
746
747 private boolean processViewIntent(Intent intent) {
748 final String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
749 final Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
750 if (conversation == null) {
751 Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
752 return false;
753 }
754 openConversation(conversation, intent.getExtras());
755 return true;
756 }
757
758 @Override
759 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
760 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
761 UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
762 if (grantResults.length > 0) {
763 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
764 switch (requestCode) {
765 case REQUEST_OPEN_MESSAGE:
766 refreshUiReal();
767 ConversationFragment.openPendingMessage(this);
768 break;
769 case REQUEST_PLAY_PAUSE:
770 ConversationFragment.startStopPending(this);
771 break;
772 case REQUEST_MICROPHONE:
773 Intent intent = new Intent();
774 intent.setComponent(new ComponentName("com.android.server.telecom",
775 "com.android.server.telecom.settings.EnableAccountPreferenceActivity"));
776 try {
777 startActivityForResult(intent, DIALLER_INTEGRATION);
778 } catch (ActivityNotFoundException e) {
779 displayToast("Dialler integration not available on your OS");
780 }
781 break;
782 case REQUEST_DOWNLOAD_STICKERS:
783 downloadStickers();
784 break;
785 }
786 } else {
787 showDialogsIfMainIsOverview();
788 }
789 } else {
790 showDialogsIfMainIsOverview();
791 }
792 }
793
794 private void downloadStickers() {
795 Intent intent = new Intent(this, DownloadDefaultStickers.class);
796 intent.putExtra("tor", xmppConnectionService.useTorToConnect());
797 ContextCompat.startForegroundService(this, intent);
798 displayToast("Sticker download started");
799 showDialogsIfMainIsOverview();
800 }
801
802 @Override
803 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
804 super.onActivityResult(requestCode, resultCode, data);
805
806 if (requestCode == DIALLER_INTEGRATION) {
807 mRequestCode = requestCode;
808 try {
809 startActivity(new Intent(android.telecom.TelecomManager.ACTION_CHANGE_PHONE_ACCOUNTS));
810 } catch (ActivityNotFoundException e) {
811 displayToast("Dialler integration not available on your OS");
812 }
813 return;
814 }
815
816 ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
817 if (xmppConnectionService != null) {
818 handleActivityResult(activityResult);
819 } else {
820 this.postponedActivityResult.push(activityResult);
821 }
822 }
823
824 private void handleActivityResult(final ActivityResult activityResult) {
825 if (activityResult.resultCode == Activity.RESULT_OK) {
826 handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
827 } else {
828 handleNegativeActivityResult(activityResult.requestCode);
829 }
830 if (activityResult.requestCode == REQUEST_BATTERY_OP) {
831 // the result code is always 0 even when battery permission were granted
832 requestNotificationPermissionIfNeeded();
833 XmppConnectionService.toggleForegroundService(xmppConnectionService);
834 }
835 }
836
837 private void handleNegativeActivityResult(int requestCode) {
838 Conversation conversation = ConversationFragment.getConversationReliable(this);
839 switch (requestCode) {
840 case REQUEST_DECRYPT_PGP:
841 if (conversation == null) {
842 break;
843 }
844 conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
845 break;
846 case REQUEST_BATTERY_OP:
847 setNeverAskForBatteryOptimizationsAgain();
848 break;
849 }
850 }
851
852 private void handlePositiveActivityResult(int requestCode, final Intent data) {
853 Conversation conversation = ConversationFragment.getConversationReliable(this);
854 if (conversation == null) {
855 Log.d(Config.LOGTAG, "conversation not found");
856 return;
857 }
858 switch (requestCode) {
859 case REQUEST_DECRYPT_PGP:
860 conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
861 break;
862 case REQUEST_CHOOSE_PGP_ID:
863 long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
864 if (id != 0) {
865 conversation.getAccount().setPgpSignId(id);
866 announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
867 } else {
868 choosePgpSignId(conversation.getAccount());
869 }
870 break;
871 case REQUEST_ANNOUNCE_PGP:
872 announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
873 break;
874 }
875 }
876
877 @Override
878 protected void onCreate(final Bundle savedInstanceState) {
879 super.onCreate(savedInstanceState);
880 savedState = savedInstanceState;
881 ConversationMenuConfigurator.reloadFeatures(this);
882 OmemoSetting.load(this);
883 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
884 Activities.setStatusAndNavigationBarColors(this, binding.getRoot());
885 setSupportActionBar(binding.toolbar);
886 configureActionBar(getSupportActionBar());
887 this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
888 this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
889 this.initializeFragments();
890 this.invalidateActionBarTitle();
891 final Intent intent;
892 if (savedInstanceState == null) {
893 intent = getIntent();
894 } else {
895 intent = savedInstanceState.getParcelable("intent");
896 }
897 if (isViewOrShareIntent(intent)) {
898 pendingViewIntent.push(intent);
899 setIntent(createLauncherIntent(this));
900 }
901 }
902
903 @Override
904 public boolean onCreateOptionsMenu(Menu menu) {
905 getMenuInflater().inflate(R.menu.activity_conversations, menu);
906 final MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
907 if (qrCodeScanMenuItem != null) {
908 if (isCameraFeatureAvailable() && (xmppConnectionService == null || !xmppConnectionService.isOnboarding())) {
909 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
910 boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
911 && fragment instanceof ConversationsOverviewFragment;
912 qrCodeScanMenuItem.setVisible(visible);
913 } else {
914 qrCodeScanMenuItem.setVisible(false);
915 }
916 }
917 return super.onCreateOptionsMenu(menu);
918 }
919
920 @Override
921 public void onConversationSelected(Conversation conversation) {
922 clearPendingViewIntent();
923 if (ConversationFragment.getConversation(this) == conversation) {
924 Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
925 return;
926 }
927 openConversation(conversation, null);
928 }
929
930 public void clearPendingViewIntent() {
931 if (pendingViewIntent.clear()) {
932 Log.e(Config.LOGTAG, "cleared pending view intent");
933 }
934 }
935
936 private void displayToast(final String msg) {
937 runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
938 }
939
940 @Override
941 public void onAffiliationChangedSuccessful(Jid jid) {
942
943 }
944
945 @Override
946 public void onAffiliationChangeFailed(Jid jid, int resId) {
947 displayToast(getString(resId, jid.asBareJid().toString()));
948 }
949
950 private void openConversation(Conversation conversation, Bundle extras) {
951 final FragmentManager fragmentManager = getFragmentManager();
952 executePendingTransactions(fragmentManager);
953 ConversationFragment conversationFragment = (ConversationFragment) fragmentManager.findFragmentById(R.id.secondary_fragment);
954 final boolean mainNeedsRefresh;
955 if (conversationFragment == null) {
956 mainNeedsRefresh = false;
957 final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
958 if (mainFragment instanceof ConversationFragment) {
959 conversationFragment = (ConversationFragment) mainFragment;
960 } else {
961 conversationFragment = new ConversationFragment();
962 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
963 fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
964 fragmentTransaction.addToBackStack(null);
965 try {
966 fragmentTransaction.commit();
967 } catch (IllegalStateException e) {
968 Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
969 //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
970 return;
971 }
972 }
973 } else {
974 mainNeedsRefresh = true;
975 }
976 conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
977 if (mainNeedsRefresh) {
978 refreshFragment(R.id.main_fragment);
979 }
980 invalidateActionBarTitle();
981 }
982
983 private static void executePendingTransactions(final FragmentManager fragmentManager) {
984 try {
985 fragmentManager.executePendingTransactions();
986 } catch (final Exception e) {
987 Log.e(Config.LOGTAG,"unable to execute pending fragment transactions");
988 }
989 }
990
991 public boolean onXmppUriClicked(Uri uri) {
992 XmppUri xmppUri = new XmppUri(uri);
993 if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
994 final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
995 if (conversation != null) {
996 if (xmppUri.getParameter("password") != null) {
997 xmppConnectionService.providePasswordForMuc(conversation, xmppUri.getParameter("password"));
998 }
999 if (xmppUri.isAction("command")) {
1000 startCommand(conversation.getAccount(), xmppUri.getJid(), xmppUri.getParameter("node"));
1001 } else {
1002 Bundle extras = new Bundle();
1003 extras.putString(Intent.EXTRA_TEXT, xmppUri.getBody());
1004 if (xmppUri.isAction("message")) extras.putString(EXTRA_POST_INIT_ACTION, "message");
1005 openConversation(conversation, extras);
1006 }
1007 return true;
1008 }
1009 }
1010 return false;
1011 }
1012
1013 public boolean onTelUriClicked(Uri uri, Account acct) {
1014 final String tel;
1015 try {
1016 tel = PhoneNumberUtilWrapper.normalize(this, uri.getSchemeSpecificPart());
1017 } catch (final IllegalArgumentException | NumberParseException | NullPointerException e) {
1018 return false;
1019 }
1020
1021 Set<String> gateways = (acct == null ? xmppConnectionService.getAccounts().stream() : List.of(acct).stream()).flatMap(account ->
1022 Stream.concat(
1023 account.getGateways("pstn").stream(),
1024 account.getGateways("sms").stream()
1025 )
1026 ).map(a -> a.getJid().asBareJid().toString()).collect(Collectors.toSet());
1027
1028 for (String gateway : gateways) {
1029 if (onXmppUriClicked(Uri.parse("xmpp:" + tel + "@" + gateway))) return true;
1030 }
1031
1032 if (gateways.size() == 1 && acct != null) {
1033 openConversation(xmppConnectionService.findOrCreateConversation(acct, Jid.ofLocalAndDomain(tel, gateways.iterator().next()), false, true), null);
1034 return true;
1035 }
1036
1037 return false;
1038 }
1039
1040 @Override
1041 public boolean onOptionsItemSelected(MenuItem item) {
1042 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1043 return false;
1044 }
1045 switch (item.getItemId()) {
1046 case android.R.id.home:
1047 FragmentManager fm = getFragmentManager();
1048 if (android.os.Build.VERSION.SDK_INT >= 26) {
1049 Fragment f = fm.getFragments().get(fm.getFragments().size() - 1);
1050 if (f != null && f instanceof ConversationFragment) {
1051 if (((ConversationFragment) f).onBackPressed()) {
1052 return true;
1053 }
1054 }
1055 }
1056 if (fm.getBackStackEntryCount() > 0) {
1057 try {
1058 fm.popBackStack();
1059 } catch (IllegalStateException e) {
1060 Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
1061 }
1062 return true;
1063 }
1064 break;
1065 case R.id.action_scan_qr_code:
1066 UriHandlerActivity.scan(this);
1067 return true;
1068 case R.id.action_search_all_conversations:
1069 startActivity(new Intent(this, SearchActivity.class));
1070 return true;
1071 case R.id.action_search_this_conversation:
1072 final Conversation conversation = ConversationFragment.getConversation(this);
1073 if (conversation == null) {
1074 return true;
1075 }
1076 final Intent intent = new Intent(this, SearchActivity.class);
1077 intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
1078 startActivity(intent);
1079 return true;
1080 }
1081 return super.onOptionsItemSelected(item);
1082 }
1083
1084 @Override
1085 public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
1086 if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
1087 final ConversationFragment conversationFragment = ConversationFragment.get(this);
1088 if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
1089 return true;
1090 }
1091 }
1092 return super.onKeyDown(keyCode, keyEvent);
1093 }
1094
1095 @Override
1096 public void onSaveInstanceState(Bundle savedInstanceState) {
1097 final Intent pendingIntent = pendingViewIntent.peek();
1098 savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
1099 savedInstanceState.putLong("mainFilter", mainFilter);
1100 savedInstanceState.putSerializable("selectedTag", selectedTag);
1101 savedInstanceState = binding.drawer.saveInstanceState(savedInstanceState);
1102 if (accountHeader != null) savedInstanceState = accountHeader.saveInstanceState(savedInstanceState);
1103 super.onSaveInstanceState(savedInstanceState);
1104 }
1105
1106 @Override
1107 public void onStart() {
1108 super.onStart();
1109 mRedirectInProcess.set(false);
1110 }
1111
1112 @Override
1113 protected void onNewIntent(final Intent intent) {
1114 super.onNewIntent(intent);
1115 if (isViewOrShareIntent(intent)) {
1116 if (xmppConnectionService != null) {
1117 clearPendingViewIntent();
1118 processViewIntent(intent);
1119 } else {
1120 pendingViewIntent.push(intent);
1121 }
1122 }
1123 setIntent(createLauncherIntent(this));
1124 }
1125
1126 @Override
1127 public void onPause() {
1128 this.mActivityPaused = true;
1129 super.onPause();
1130 }
1131
1132 @Override
1133 public void onResume() {
1134 super.onResume();
1135 this.mActivityPaused = false;
1136 }
1137
1138 private void initializeFragments() {
1139 final FragmentManager fragmentManager = getFragmentManager();
1140 FragmentTransaction transaction = fragmentManager.beginTransaction();
1141 final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
1142 final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
1143 if (mainFragment != null) {
1144 if (binding.secondaryFragment != null) {
1145 if (mainFragment instanceof ConversationFragment) {
1146 getFragmentManager().popBackStack();
1147 transaction.remove(mainFragment);
1148 transaction.commit();
1149 fragmentManager.executePendingTransactions();
1150 transaction = fragmentManager.beginTransaction();
1151 transaction.replace(R.id.secondary_fragment, mainFragment);
1152 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
1153 transaction.commit();
1154 return;
1155 }
1156 } else {
1157 if (secondaryFragment instanceof ConversationFragment) {
1158 transaction.remove(secondaryFragment);
1159 transaction.commit();
1160 getFragmentManager().executePendingTransactions();
1161 transaction = fragmentManager.beginTransaction();
1162 transaction.replace(R.id.main_fragment, secondaryFragment);
1163 transaction.addToBackStack(null);
1164 transaction.commit();
1165 return;
1166 }
1167 }
1168 } else {
1169 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
1170 }
1171 if (binding.secondaryFragment != null && secondaryFragment == null) {
1172 transaction.replace(R.id.secondary_fragment, new ConversationFragment());
1173 }
1174 transaction.commit();
1175 }
1176
1177 private void invalidateActionBarTitle() {
1178 final ActionBar actionBar = getSupportActionBar();
1179 if (actionBar == null) {
1180 return;
1181 }
1182 final FragmentManager fragmentManager = getFragmentManager();
1183 final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
1184 if (mainFragment instanceof ConversationFragment conversationFragment) {
1185 final Conversation conversation = conversationFragment.getConversation();
1186 if (conversation != null) {
1187 actionBar.setTitle(conversation.getName());
1188 actionBar.setDisplayHomeAsUpEnabled(!xmppConnectionService.isOnboarding() || !conversation.getJid().equals(Jid.of("cheogram.com")));
1189 ToolbarUtils.setActionBarOnClickListener(
1190 binding.toolbar,
1191 (v) -> { if(!xmppConnectionService.isOnboarding()) openConversationDetails(conversation); }
1192 );
1193 return;
1194 }
1195 }
1196 final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
1197 if (secondaryFragment instanceof ConversationFragment conversationFragment) {
1198 final Conversation conversation = conversationFragment.getConversation();
1199 if (conversation != null) {
1200 actionBar.setTitle(conversation.getName());
1201 } else {
1202 actionBar.setTitle(R.string.app_name);
1203 }
1204 } else {
1205 actionBar.setTitle(R.string.app_name);
1206 }
1207 actionBar.setDisplayHomeAsUpEnabled(false);
1208 ToolbarUtils.resetActionBarOnClickListeners(binding.toolbar);
1209 }
1210
1211 private void openConversationDetails(final Conversation conversation) {
1212 if (conversation.getMode() == Conversational.MODE_MULTI) {
1213 ConferenceDetailsActivity.open(this, conversation);
1214 } else {
1215 final Contact contact = conversation.getContact();
1216 if (contact.isSelf()) {
1217 switchToAccount(conversation.getAccount());
1218 } else {
1219 switchToContactDetails(contact);
1220 }
1221 }
1222 }
1223
1224 @Override
1225 public void onConversationArchived(Conversation conversation) {
1226 if (performRedirectIfNecessary(conversation, false)) {
1227 return;
1228 }
1229 final FragmentManager fragmentManager = getFragmentManager();
1230 final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
1231 if (mainFragment instanceof ConversationFragment) {
1232 try {
1233 fragmentManager.popBackStack();
1234 } catch (final IllegalStateException e) {
1235 Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
1236 //this usually means activity is no longer active; meaning on the next open we will run through this again
1237 }
1238 return;
1239 }
1240 final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
1241 if (secondaryFragment instanceof ConversationFragment) {
1242 if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
1243 Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
1244 if (suggestion != null) {
1245 openConversation(suggestion, null);
1246 }
1247 }
1248 }
1249 }
1250
1251 @Override
1252 public void onConversationsListItemUpdated() {
1253 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
1254 if (fragment instanceof ConversationsOverviewFragment) {
1255 ((ConversationsOverviewFragment) fragment).refresh();
1256 }
1257 }
1258
1259 @Override
1260 public void switchToConversation(Conversation conversation) {
1261 Log.d(Config.LOGTAG, "override");
1262 openConversation(conversation, null);
1263 }
1264
1265 @Override
1266 public void onConversationRead(Conversation conversation, String upToUuid) {
1267 if (!mActivityPaused && pendingViewIntent.peek() == null) {
1268 xmppConnectionService.sendReadMarker(conversation, upToUuid);
1269 } else {
1270 Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
1271 }
1272 }
1273
1274 @Override
1275 public void onAccountUpdate() {
1276 refreshAccounts = true;
1277 this.refreshUi();
1278 }
1279
1280 @Override
1281 public void onConversationUpdate(boolean newCaps) {
1282 if (performRedirectIfNecessary(false)) {
1283 return;
1284 }
1285 refreshForNewCaps = newCaps;
1286 this.refreshUi();
1287 }
1288
1289 @Override
1290 public void onRosterUpdate(final XmppConnectionService.UpdateRosterReason reason, final Contact contact) {
1291 if (reason != XmppConnectionService.UpdateRosterReason.AVATAR) {
1292 refreshForNewCaps = true;
1293 if (contact != null) newCapsJids.add(contact.getJid().asBareJid());
1294 }
1295 this.refreshUi();
1296 }
1297
1298 @Override
1299 public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
1300 this.refreshUi();
1301 }
1302
1303 @Override
1304 public void onShowErrorToast(int resId) {
1305 runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
1306 }
1307}