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