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