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