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