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