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