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