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