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
32
33import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
34
35import android.Manifest;
36import android.annotation.SuppressLint;
37import android.app.Activity;
38import android.app.Fragment;
39import android.app.FragmentManager;
40import android.app.FragmentTransaction;
41import android.content.ActivityNotFoundException;
42import android.content.ComponentName;
43import android.content.Context;
44import android.content.Intent;
45import android.content.pm.PackageManager;
46import android.net.Uri;
47import android.os.Build;
48import android.os.Bundle;
49import android.provider.Settings;
50import android.util.Log;
51import android.view.KeyEvent;
52import android.view.Menu;
53import android.view.MenuItem;
54import android.widget.Toast;
55
56import androidx.annotation.IdRes;
57import androidx.annotation.NonNull;
58import androidx.appcompat.app.ActionBar;
59import androidx.appcompat.app.AlertDialog;
60import androidx.core.content.ContextCompat;
61import androidx.databinding.DataBindingUtil;
62
63import com.cheogram.android.DownloadDefaultStickers;
64
65import org.openintents.openpgp.util.OpenPgpApi;
66
67import java.util.Arrays;
68import java.util.List;
69import java.util.HashSet;
70import java.util.Set;
71import java.util.concurrent.atomic.AtomicBoolean;
72
73import eu.siacs.conversations.Config;
74import eu.siacs.conversations.R;
75import eu.siacs.conversations.crypto.OmemoSetting;
76import eu.siacs.conversations.databinding.ActivityConversationsBinding;
77import eu.siacs.conversations.entities.Account;
78import eu.siacs.conversations.entities.Contact;
79import eu.siacs.conversations.entities.Conversation;
80import eu.siacs.conversations.entities.Conversational;
81import eu.siacs.conversations.services.XmppConnectionService;
82import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
83import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
84import eu.siacs.conversations.ui.interfaces.OnConversationRead;
85import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
86import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
87import eu.siacs.conversations.ui.util.ActionBarUtil;
88import eu.siacs.conversations.ui.util.ActivityResult;
89import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
90import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
91import eu.siacs.conversations.ui.util.PendingItem;
92import eu.siacs.conversations.utils.ExceptionHelper;
93import eu.siacs.conversations.utils.SignupUtils;
94import eu.siacs.conversations.utils.ThemeHelper;
95import eu.siacs.conversations.utils.XmppUri;
96import eu.siacs.conversations.xmpp.Jid;
97import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
98
99public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged {
100
101 public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
102 public static final String EXTRA_CONVERSATION = "conversationUuid";
103 public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
104 public static final String EXTRA_AS_QUOTE = "eu.siacs.conversations.as_quote";
105 public static final String EXTRA_NICK = "nick";
106 public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
107 public static final String EXTRA_DO_NOT_APPEND = "do_not_append";
108 public static final String EXTRA_POST_INIT_ACTION = "post_init_action";
109 public static final String POST_ACTION_RECORD_VOICE = "record_voice";
110 public static final String EXTRA_TYPE = "type";
111 public static final String EXTRA_NODE = "node";
112 public static final String EXTRA_JID = "jid";
113
114 private static final List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList(
115 ACTION_VIEW_CONVERSATION,
116 Intent.ACTION_SEND,
117 Intent.ACTION_SEND_MULTIPLE
118 );
119
120 public static final int REQUEST_OPEN_MESSAGE = 0x9876;
121 public static final int REQUEST_PLAY_PAUSE = 0x5432;
122 public static final int REQUEST_MICROPHONE = 0x5432f;
123 public static final int DIALLER_INTEGRATION = 0x5432ff;
124 public static final int REQUEST_DOWNLOAD_STICKERS = 0xbf8702;
125
126
127 //secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
128 private static final @IdRes
129 int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
130 private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
131 private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>();
132 private ActivityConversationsBinding binding;
133 private boolean mActivityPaused = true;
134 private final AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
135 private boolean refreshForNewCaps = false;
136 private int mRequestCode = -1;
137
138 private static boolean isViewOrShareIntent(Intent i) {
139 Log.d(Config.LOGTAG, "action: " + (i == null ? null : i.getAction()));
140 return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
141 }
142
143 private static Intent createLauncherIntent(Context context) {
144 final Intent intent = new Intent(context, ConversationsActivity.class);
145 intent.setAction(Intent.ACTION_MAIN);
146 intent.addCategory(Intent.CATEGORY_LAUNCHER);
147 return intent;
148 }
149
150 @Override
151 protected void refreshUiReal() {
152 invalidateOptionsMenu();
153 for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
154 refreshFragment(id);
155 }
156 refreshForNewCaps = false;
157 }
158
159 @Override
160 void onBackendConnected() {
161 if (performRedirectIfNecessary(true)) {
162 return;
163 }
164 xmppConnectionService.getNotificationService().setIsInForeground(true);
165 final Intent intent = pendingViewIntent.pop();
166 if (intent != null) {
167 if (processViewIntent(intent)) {
168 if (binding.secondaryFragment != null) {
169 notifyFragmentOfBackendConnected(R.id.main_fragment);
170 }
171 invalidateActionBarTitle();
172 return;
173 }
174 }
175 for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
176 notifyFragmentOfBackendConnected(id);
177 }
178
179 final ActivityResult activityResult = postponedActivityResult.pop();
180 if (activityResult != null) {
181 handleActivityResult(activityResult);
182 }
183
184 invalidateActionBarTitle();
185 if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
186 Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
187 if (conversation != null) {
188 openConversation(conversation, null);
189 }
190 }
191 showDialogsIfMainIsOverview();
192 }
193
194 private boolean performRedirectIfNecessary(boolean noAnimation) {
195 return performRedirectIfNecessary(null, noAnimation);
196 }
197
198 private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
199 if (xmppConnectionService == null) {
200 return false;
201 }
202 boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
203 if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
204 final Intent intent = SignupUtils.getRedirectionIntent(this);
205 if (noAnimation) {
206 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
207 }
208 runOnUiThread(() -> {
209 startActivity(intent);
210 if (noAnimation) {
211 overridePendingTransition(0, 0);
212 }
213 });
214 }
215 return mRedirectInProcess.get();
216 }
217
218 private void showDialogsIfMainIsOverview() {
219 if (xmppConnectionService == null) {
220 return;
221 }
222 final Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
223 if (fragment instanceof ConversationsOverviewFragment) {
224 if (ExceptionHelper.checkForCrash(this)) return;
225 if (offerToSetupDiallerIntegration()) return;
226 if (offerToDownloadStickers()) return;
227 openBatteryOptimizationDialogIfNeeded();
228 }
229 }
230
231 private String getBatteryOptimizationPreferenceKey() {
232 @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
233 return "show_battery_optimization" + (device == null ? "" : device);
234 }
235
236 private void setNeverAskForBatteryOptimizationsAgain() {
237 getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
238 }
239
240 private void openBatteryOptimizationDialogIfNeeded() {
241 if (isOptimizingBattery()
242 && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M
243 && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
244 AlertDialog.Builder builder = new AlertDialog.Builder(this);
245 builder.setTitle(R.string.battery_optimizations_enabled);
246 builder.setMessage(getString(R.string.battery_optimizations_enabled_dialog, getString(R.string.app_name)));
247 builder.setPositiveButton(R.string.next, (dialog, which) -> {
248 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
249 Uri uri = Uri.parse("package:" + getPackageName());
250 intent.setData(uri);
251 try {
252 startActivityForResult(intent, REQUEST_BATTERY_OP);
253 } catch (ActivityNotFoundException e) {
254 Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
255 }
256 });
257 builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
258 final AlertDialog dialog = builder.create();
259 dialog.setCanceledOnTouchOutside(false);
260 dialog.show();
261 }
262 }
263
264 private boolean offerToDownloadStickers() {
265 int offered = getPreferences().getInt("default_stickers_offered", 0);
266 if (offered > 0) return false;
267 getPreferences().edit().putInt("default_stickers_offered", 1).apply();
268
269 AlertDialog.Builder builder = new AlertDialog.Builder(this);
270 builder.setTitle("Download Stickers?");
271 builder.setMessage("Would you like to download some default sticker packs?");
272 builder.setPositiveButton(R.string.yes, (dialog, which) -> {
273 if (hasStoragePermission(REQUEST_DOWNLOAD_STICKERS)) {
274 downloadStickers();
275 }
276 });
277 builder.setNegativeButton(R.string.no, (dialog, which) -> { });
278 final AlertDialog dialog = builder.create();
279 dialog.setCanceledOnTouchOutside(false);
280 dialog.show();
281 return true;
282 }
283
284 private boolean offerToSetupDiallerIntegration() {
285 if (mRequestCode == DIALLER_INTEGRATION) {
286 mRequestCode = -1;
287 return true;
288 }
289 if (Build.VERSION.SDK_INT < 23) return false;
290 if (Build.VERSION.SDK_INT >= 33) {
291 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELECOM)) return false;
292 } else {
293 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) return false;
294 }
295
296 Set<String> pstnGateways = new HashSet<>();
297 for (Account account : xmppConnectionService.getAccounts()) {
298 for (Contact contact : account.getRoster().getContacts()) {
299 if (contact.getPresences().anyIdentity("gateway", "pstn")) {
300 pstnGateways.add(contact.getJid().asBareJid().toEscapedString());
301 }
302 }
303 }
304
305 if (pstnGateways.size() < 1) return false;
306 Set<String> fromPrefs = getPreferences().getStringSet("pstn_gateways", Set.of("UPGRADE"));
307 getPreferences().edit().putStringSet("pstn_gateways", pstnGateways).apply();
308 pstnGateways.removeAll(fromPrefs);
309 if (pstnGateways.size() < 1) return false;
310
311 if (fromPrefs.contains("UPGRADE")) return false;
312
313 AlertDialog.Builder builder = new AlertDialog.Builder(this);
314 builder.setTitle("Dialler Integration");
315 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?");
316 builder.setPositiveButton(R.string.yes, (dialog, which) -> {
317 final String[] permissions;
318 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
319 permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.BLUETOOTH_CONNECT};
320 } else {
321 permissions = new String[]{Manifest.permission.RECORD_AUDIO};
322 }
323 requestPermissions(permissions, REQUEST_MICROPHONE);
324 });
325 builder.setNegativeButton(R.string.no, (dialog, which) -> { });
326 final AlertDialog dialog = builder.create();
327 dialog.setCanceledOnTouchOutside(false);
328 dialog.show();
329 return true;
330 }
331
332 private void notifyFragmentOfBackendConnected(@IdRes int id) {
333 final Fragment fragment = getFragmentManager().findFragmentById(id);
334 if (fragment instanceof OnBackendConnected) {
335 ((OnBackendConnected) fragment).onBackendConnected();
336 }
337 }
338
339 private void refreshFragment(@IdRes int id) {
340 final Fragment fragment = getFragmentManager().findFragmentById(id);
341 if (fragment instanceof XmppFragment) {
342 ((XmppFragment) fragment).refresh();
343 if (refreshForNewCaps) ((XmppFragment) fragment).refreshForNewCaps();
344 }
345 }
346
347 private boolean processViewIntent(Intent intent) {
348 final String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
349 final Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
350 if (conversation == null) {
351 Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
352 return false;
353 }
354 openConversation(conversation, intent.getExtras());
355 return true;
356 }
357
358 @Override
359 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
360 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
361 UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
362 if (grantResults.length > 0) {
363 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
364 switch (requestCode) {
365 case REQUEST_OPEN_MESSAGE:
366 refreshUiReal();
367 ConversationFragment.openPendingMessage(this);
368 break;
369 case REQUEST_PLAY_PAUSE:
370 ConversationFragment.startStopPending(this);
371 break;
372 case REQUEST_MICROPHONE:
373 Intent intent = new Intent();
374 intent.setComponent(new ComponentName("com.android.server.telecom",
375 "com.android.server.telecom.settings.EnableAccountPreferenceActivity"));
376 startActivityForResult(intent, DIALLER_INTEGRATION);
377 break;
378 case REQUEST_DOWNLOAD_STICKERS:
379 downloadStickers();
380 break;
381 }
382 }
383 }
384 }
385
386 private void downloadStickers() {
387 Intent intent = new Intent(this, DownloadDefaultStickers.class);
388 ContextCompat.startForegroundService(this, intent);
389 displayToast("Sticker download started");
390 showDialogsIfMainIsOverview();
391 }
392
393 @Override
394 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
395 super.onActivityResult(requestCode, resultCode, data);
396
397 if (requestCode == DIALLER_INTEGRATION) {
398 mRequestCode = requestCode;
399 startActivity(new Intent(android.telecom.TelecomManager.ACTION_CHANGE_PHONE_ACCOUNTS));
400 return;
401 }
402
403 ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data);
404 if (xmppConnectionService != null) {
405 handleActivityResult(activityResult);
406 } else {
407 this.postponedActivityResult.push(activityResult);
408 }
409 }
410
411 private void handleActivityResult(ActivityResult activityResult) {
412 if (activityResult.resultCode == Activity.RESULT_OK) {
413 handlePositiveActivityResult(activityResult.requestCode, activityResult.data);
414 } else {
415 handleNegativeActivityResult(activityResult.requestCode);
416 }
417 }
418
419 private void handleNegativeActivityResult(int requestCode) {
420 Conversation conversation = ConversationFragment.getConversationReliable(this);
421 switch (requestCode) {
422 case REQUEST_DECRYPT_PGP:
423 if (conversation == null) {
424 break;
425 }
426 conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
427 break;
428 case REQUEST_BATTERY_OP:
429 setNeverAskForBatteryOptimizationsAgain();
430 break;
431 }
432 }
433
434 private void handlePositiveActivityResult(int requestCode, final Intent data) {
435 Conversation conversation = ConversationFragment.getConversationReliable(this);
436 if (conversation == null) {
437 Log.d(Config.LOGTAG, "conversation not found");
438 return;
439 }
440 switch (requestCode) {
441 case REQUEST_DECRYPT_PGP:
442 conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
443 break;
444 case REQUEST_CHOOSE_PGP_ID:
445 long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0);
446 if (id != 0) {
447 conversation.getAccount().setPgpSignId(id);
448 announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished);
449 } else {
450 choosePgpSignId(conversation.getAccount());
451 }
452 break;
453 case REQUEST_ANNOUNCE_PGP:
454 announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished);
455 break;
456 }
457 }
458
459 @Override
460 protected void onCreate(final Bundle savedInstanceState) {
461 super.onCreate(savedInstanceState);
462 ConversationMenuConfigurator.reloadFeatures(this);
463 OmemoSetting.load(this);
464 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
465 setSupportActionBar(binding.toolbar);
466 configureActionBar(getSupportActionBar());
467 this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
468 this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
469 this.initializeFragments();
470 this.invalidateActionBarTitle();
471 final Intent intent;
472 if (savedInstanceState == null) {
473 intent = getIntent();
474 } else {
475 intent = savedInstanceState.getParcelable("intent");
476 }
477 if (isViewOrShareIntent(intent)) {
478 pendingViewIntent.push(intent);
479 setIntent(createLauncherIntent(this));
480 }
481 }
482
483 @Override
484 public boolean onCreateOptionsMenu(Menu menu) {
485 getMenuInflater().inflate(R.menu.activity_conversations, menu);
486 final MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
487 if (qrCodeScanMenuItem != null) {
488 if (isCameraFeatureAvailable()) {
489 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
490 boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
491 && fragment instanceof ConversationsOverviewFragment;
492 qrCodeScanMenuItem.setVisible(visible);
493 } else {
494 qrCodeScanMenuItem.setVisible(false);
495 }
496 }
497 return super.onCreateOptionsMenu(menu);
498 }
499
500 @Override
501 public void onConversationSelected(Conversation conversation) {
502 clearPendingViewIntent();
503 if (ConversationFragment.getConversation(this) == conversation) {
504 Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open");
505 return;
506 }
507 openConversation(conversation, null);
508 }
509
510 public void clearPendingViewIntent() {
511 if (pendingViewIntent.clear()) {
512 Log.e(Config.LOGTAG, "cleared pending view intent");
513 }
514 }
515
516 private void displayToast(final String msg) {
517 runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show());
518 }
519
520 @Override
521 public void onAffiliationChangedSuccessful(Jid jid) {
522
523 }
524
525 @Override
526 public void onAffiliationChangeFailed(Jid jid, int resId) {
527 displayToast(getString(resId, jid.asBareJid().toString()));
528 }
529
530 private void openConversation(Conversation conversation, Bundle extras) {
531 final FragmentManager fragmentManager = getFragmentManager();
532 executePendingTransactions(fragmentManager);
533 ConversationFragment conversationFragment = (ConversationFragment) fragmentManager.findFragmentById(R.id.secondary_fragment);
534 final boolean mainNeedsRefresh;
535 if (conversationFragment == null) {
536 mainNeedsRefresh = false;
537 final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
538 if (mainFragment instanceof ConversationFragment) {
539 conversationFragment = (ConversationFragment) mainFragment;
540 } else {
541 conversationFragment = new ConversationFragment();
542 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
543 fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
544 fragmentTransaction.addToBackStack(null);
545 try {
546 fragmentTransaction.commit();
547 } catch (IllegalStateException e) {
548 Log.w(Config.LOGTAG, "sate loss while opening conversation", e);
549 //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored'
550 return;
551 }
552 }
553 } else {
554 mainNeedsRefresh = true;
555 }
556 conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras);
557 if (mainNeedsRefresh) {
558 refreshFragment(R.id.main_fragment);
559 } else {
560 invalidateActionBarTitle();
561 }
562 }
563
564 private static void executePendingTransactions(final FragmentManager fragmentManager) {
565 try {
566 fragmentManager.executePendingTransactions();
567 } catch (final Exception e) {
568 Log.e(Config.LOGTAG,"unable to execute pending fragment transactions");
569 }
570 }
571
572 public boolean onXmppUriClicked(Uri uri) {
573 XmppUri xmppUri = new XmppUri(uri);
574 if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
575 final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri);
576 if (conversation != null) {
577 if (xmppUri.isAction("command")) {
578 startCommand(conversation.getAccount(), conversation.getJid(), xmppUri.getParameter("node"));
579 } else {
580 Bundle extras = new Bundle();
581 extras.putString(Intent.EXTRA_TEXT, xmppUri.getBody());
582 if (xmppUri.isAction("message")) extras.putString(EXTRA_POST_INIT_ACTION, "message");
583 openConversation(conversation, extras);
584 }
585 return true;
586 }
587 }
588 return false;
589 }
590
591 @Override
592 public boolean onOptionsItemSelected(MenuItem item) {
593 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
594 return false;
595 }
596 switch (item.getItemId()) {
597 case android.R.id.home:
598 FragmentManager fm = getFragmentManager();
599 if (android.os.Build.VERSION.SDK_INT >= 26) {
600 Fragment f = fm.getFragments().get(fm.getFragments().size() - 1);
601 if (f != null && f instanceof ConversationFragment) {
602 if (((ConversationFragment) f).onBackPressed()) {
603 return true;
604 }
605 }
606 }
607 if (fm.getBackStackEntryCount() > 0) {
608 try {
609 fm.popBackStack();
610 } catch (IllegalStateException e) {
611 Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button");
612 }
613 return true;
614 }
615 break;
616 case R.id.action_scan_qr_code:
617 UriHandlerActivity.scan(this);
618 return true;
619 case R.id.action_search_all_conversations:
620 startActivity(new Intent(this, SearchActivity.class));
621 return true;
622 case R.id.action_search_this_conversation:
623 final Conversation conversation = ConversationFragment.getConversation(this);
624 if (conversation == null) {
625 return true;
626 }
627 final Intent intent = new Intent(this, SearchActivity.class);
628 intent.putExtra(SearchActivity.EXTRA_CONVERSATION_UUID, conversation.getUuid());
629 startActivity(intent);
630 return true;
631 }
632 return super.onOptionsItemSelected(item);
633 }
634
635 @Override
636 public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
637 if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyEvent.isCtrlPressed()) {
638 final ConversationFragment conversationFragment = ConversationFragment.get(this);
639 if (conversationFragment != null && conversationFragment.onArrowUpCtrlPressed()) {
640 return true;
641 }
642 }
643 return super.onKeyDown(keyCode, keyEvent);
644 }
645
646 @Override
647 public void onSaveInstanceState(final Bundle savedInstanceState) {
648 final Intent pendingIntent = pendingViewIntent.peek();
649 savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent());
650 super.onSaveInstanceState(savedInstanceState);
651 }
652
653 @Override
654 protected void onStart() {
655 super.onStart();
656 final int theme = findTheme();
657 if (this.mTheme != theme || !this.mCustomColors.equals(ThemeHelper.applyCustomColors(this))) {
658 this.mSkipBackgroundBinding = true;
659 recreate();
660 } else {
661 this.mSkipBackgroundBinding = false;
662 }
663 mRedirectInProcess.set(false);
664 }
665
666 @Override
667 protected void onNewIntent(final Intent intent) {
668 super.onNewIntent(intent);
669 if (isViewOrShareIntent(intent)) {
670 if (xmppConnectionService != null) {
671 clearPendingViewIntent();
672 processViewIntent(intent);
673 } else {
674 pendingViewIntent.push(intent);
675 }
676 }
677 setIntent(createLauncherIntent(this));
678 }
679
680 @Override
681 public void onPause() {
682 this.mActivityPaused = true;
683 super.onPause();
684 }
685
686 @Override
687 public void onResume() {
688 super.onResume();
689 this.mActivityPaused = false;
690 }
691
692 private void initializeFragments() {
693 final FragmentManager fragmentManager = getFragmentManager();
694 FragmentTransaction transaction = fragmentManager.beginTransaction();
695 final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
696 final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
697 if (mainFragment != null) {
698 if (binding.secondaryFragment != null) {
699 if (mainFragment instanceof ConversationFragment) {
700 getFragmentManager().popBackStack();
701 transaction.remove(mainFragment);
702 transaction.commit();
703 fragmentManager.executePendingTransactions();
704 transaction = fragmentManager.beginTransaction();
705 transaction.replace(R.id.secondary_fragment, mainFragment);
706 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
707 transaction.commit();
708 return;
709 }
710 } else {
711 if (secondaryFragment instanceof ConversationFragment) {
712 transaction.remove(secondaryFragment);
713 transaction.commit();
714 getFragmentManager().executePendingTransactions();
715 transaction = fragmentManager.beginTransaction();
716 transaction.replace(R.id.main_fragment, secondaryFragment);
717 transaction.addToBackStack(null);
718 transaction.commit();
719 return;
720 }
721 }
722 } else {
723 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
724 }
725 if (binding.secondaryFragment != null && secondaryFragment == null) {
726 transaction.replace(R.id.secondary_fragment, new ConversationFragment());
727 }
728 transaction.commit();
729 }
730
731 private void invalidateActionBarTitle() {
732 final ActionBar actionBar = getSupportActionBar();
733 if (actionBar == null) {
734 return;
735 }
736 final FragmentManager fragmentManager = getFragmentManager();
737 final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
738 if (mainFragment instanceof ConversationFragment) {
739 final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
740 if (conversation != null) {
741 actionBar.setTitle(conversation.getName());
742 actionBar.setDisplayHomeAsUpEnabled(true);
743 ActionBarUtil.setActionBarOnClickListener(
744 binding.toolbar,
745 (v) -> openConversationDetails(conversation)
746 );
747 return;
748 }
749 }
750 actionBar.setTitle(R.string.app_name);
751 actionBar.setDisplayHomeAsUpEnabled(false);
752 ActionBarUtil.resetActionBarOnClickListeners(binding.toolbar);
753 }
754
755 private void openConversationDetails(final Conversation conversation) {
756 if (conversation.getMode() == Conversational.MODE_MULTI) {
757 ConferenceDetailsActivity.open(this, conversation);
758 } else {
759 final Contact contact = conversation.getContact();
760 if (contact.isSelf()) {
761 switchToAccount(conversation.getAccount());
762 } else {
763 switchToContactDetails(contact);
764 }
765 }
766 }
767
768 @Override
769 public void onConversationArchived(Conversation conversation) {
770 if (performRedirectIfNecessary(conversation, false)) {
771 return;
772 }
773 final FragmentManager fragmentManager = getFragmentManager();
774 final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
775 if (mainFragment instanceof ConversationFragment) {
776 try {
777 fragmentManager.popBackStack();
778 } catch (final IllegalStateException e) {
779 Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
780 //this usually means activity is no longer active; meaning on the next open we will run through this again
781 }
782 return;
783 }
784 final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
785 if (secondaryFragment instanceof ConversationFragment) {
786 if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
787 Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
788 if (suggestion != null) {
789 openConversation(suggestion, null);
790 }
791 }
792 }
793 }
794
795 @Override
796 public void onConversationsListItemUpdated() {
797 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
798 if (fragment instanceof ConversationsOverviewFragment) {
799 ((ConversationsOverviewFragment) fragment).refresh();
800 }
801 }
802
803 @Override
804 public void switchToConversation(Conversation conversation) {
805 Log.d(Config.LOGTAG, "override");
806 openConversation(conversation, null);
807 }
808
809 @Override
810 public void onConversationRead(Conversation conversation, String upToUuid) {
811 if (!mActivityPaused && pendingViewIntent.peek() == null) {
812 xmppConnectionService.sendReadMarker(conversation, upToUuid);
813 } else {
814 Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + mActivityPaused);
815 }
816 }
817
818 @Override
819 public void onAccountUpdate() {
820 this.refreshUi();
821 }
822
823 @Override
824 public void onConversationUpdate(boolean newCaps) {
825 if (performRedirectIfNecessary(false)) {
826 return;
827 }
828 refreshForNewCaps = newCaps;
829 this.refreshUi();
830 }
831
832 @Override
833 public void onRosterUpdate() {
834 refreshForNewCaps = true;
835 this.refreshUi();
836 }
837
838 @Override
839 public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
840 this.refreshUi();
841 }
842
843 @Override
844 public void onShowErrorToast(int resId) {
845 runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
846 }
847}