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