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