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