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