1package eu.siacs.conversations.ui;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.app.NotificationManager;
6import android.app.PendingIntent;
7import android.content.ActivityNotFoundException;
8import android.content.ClipData;
9import android.content.ClipboardManager;
10import android.content.ComponentName;
11import android.content.Context;
12import android.content.ContextWrapper;
13import android.content.DialogInterface;
14import android.content.Intent;
15import android.content.IntentSender.SendIntentException;
16import android.content.ServiceConnection;
17import android.content.SharedPreferences;
18import android.content.pm.PackageManager;
19import android.content.res.Resources;
20import android.graphics.Bitmap;
21import android.graphics.Point;
22import android.graphics.drawable.BitmapDrawable;
23import android.graphics.drawable.Drawable;
24import android.net.ConnectivityManager;
25import android.net.Uri;
26import android.os.AsyncTask;
27import android.os.Build;
28import android.os.Bundle;
29import android.os.Handler;
30import android.os.IBinder;
31import android.os.PowerManager;
32import android.os.SystemClock;
33import android.preference.PreferenceManager;
34import android.provider.Settings;
35import android.text.Html;
36import android.text.InputType;
37import android.util.DisplayMetrics;
38import android.util.Log;
39import android.view.Menu;
40import android.view.MenuItem;
41import android.view.View;
42import android.widget.Button;
43import android.widget.CheckBox;
44import android.widget.ImageView;
45import android.widget.Toast;
46import androidx.annotation.BoolRes;
47import androidx.annotation.NonNull;
48import androidx.annotation.RequiresApi;
49import androidx.annotation.StringRes;
50import androidx.appcompat.app.AlertDialog;
51import androidx.appcompat.app.AppCompatDelegate;
52import androidx.core.content.pm.ShortcutInfoCompat;
53import androidx.core.content.pm.ShortcutManagerCompat;
54import androidx.databinding.DataBindingUtil;
55import com.google.android.material.color.MaterialColors;
56import com.google.android.material.dialog.MaterialAlertDialogBuilder;
57import com.google.common.base.Strings;
58import com.google.common.collect.ImmutableSet;
59import com.google.common.util.concurrent.FutureCallback;
60import com.google.common.util.concurrent.Futures;
61import com.google.common.util.concurrent.MoreExecutors;
62import eu.siacs.conversations.AppSettings;
63import eu.siacs.conversations.BuildConfig;
64import eu.siacs.conversations.Config;
65import eu.siacs.conversations.R;
66import eu.siacs.conversations.crypto.PgpEngine;
67import eu.siacs.conversations.databinding.DialogAddReactionBinding;
68import eu.siacs.conversations.databinding.DialogQuickeditBinding;
69import eu.siacs.conversations.entities.Account;
70import eu.siacs.conversations.entities.Contact;
71import eu.siacs.conversations.entities.Conversation;
72import eu.siacs.conversations.entities.Message;
73import eu.siacs.conversations.entities.Presences;
74import eu.siacs.conversations.entities.Reaction;
75import eu.siacs.conversations.services.AvatarService;
76import eu.siacs.conversations.services.BarcodeProvider;
77import eu.siacs.conversations.services.NotificationService;
78import eu.siacs.conversations.services.QuickConversationsService;
79import eu.siacs.conversations.services.XmppConnectionService;
80import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
81import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
82import eu.siacs.conversations.ui.util.PresenceSelector;
83import eu.siacs.conversations.ui.util.SettingsUtils;
84import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
85import eu.siacs.conversations.utils.AccountUtils;
86import eu.siacs.conversations.utils.Compatibility;
87import eu.siacs.conversations.utils.SignupUtils;
88import eu.siacs.conversations.xmpp.Jid;
89import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
90import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
91import eu.siacs.conversations.xmpp.manager.PresenceManager;
92import eu.siacs.conversations.xmpp.manager.RegistrationManager;
93import java.io.IOException;
94import java.lang.ref.WeakReference;
95import java.util.ArrayList;
96import java.util.Collection;
97import java.util.List;
98import java.util.concurrent.RejectedExecutionException;
99import java.util.function.Consumer;
100
101public abstract class XmppActivity extends ActionBarActivity {
102
103 public static final String EXTRA_ACCOUNT = "account";
104 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
105 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
106 protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
107 protected static final int REQUEST_BATTERY_OP = 0x49ff;
108 protected static final int REQUEST_POST_NOTIFICATION = 0x50ff;
109 public XmppConnectionService xmppConnectionService;
110 public boolean xmppConnectionServiceBound = false;
111
112 protected static final String FRAGMENT_TAG_DIALOG = "dialog";
113
114 private boolean isCameraFeatureAvailable = false;
115
116 protected boolean mUsingEnterKey = false;
117 protected boolean mUseTor = false;
118 protected Toast mToast;
119 public Runnable onOpenPGPKeyPublished =
120 () ->
121 Toast.makeText(
122 XmppActivity.this,
123 R.string.openpgp_has_been_published,
124 Toast.LENGTH_SHORT)
125 .show();
126 protected ConferenceInvite mPendingConferenceInvite = null;
127 protected ServiceConnection mConnection =
128 new ServiceConnection() {
129
130 @Override
131 public void onServiceConnected(ComponentName className, IBinder service) {
132 XmppConnectionBinder binder = (XmppConnectionBinder) service;
133 xmppConnectionService = binder.getService();
134 xmppConnectionServiceBound = true;
135 registerListeners();
136 onBackendConnected();
137 }
138
139 @Override
140 public void onServiceDisconnected(ComponentName arg0) {
141 xmppConnectionServiceBound = false;
142 }
143 };
144 private DisplayMetrics metrics;
145 private long mLastUiRefresh = 0;
146 private final Handler mRefreshUiHandler = new Handler();
147 private final Runnable mRefreshUiRunnable =
148 () -> {
149 mLastUiRefresh = SystemClock.elapsedRealtime();
150 refreshUiReal();
151 };
152 private final UiCallback<Conversation> adhocCallback =
153 new UiCallback<Conversation>() {
154 @Override
155 public void success(final Conversation conversation) {
156 runOnUiThread(
157 () -> {
158 switchToConversation(conversation);
159 hideToast();
160 });
161 }
162
163 @Override
164 public void error(final int errorCode, Conversation object) {
165 runOnUiThread(() -> replaceToast(getString(errorCode)));
166 }
167
168 @Override
169 public void userInputRequired(PendingIntent pi, Conversation object) {}
170 };
171
172 public static boolean cancelPotentialWork(Message message, ImageView imageView) {
173 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
174
175 if (bitmapWorkerTask != null) {
176 final Message oldMessage = bitmapWorkerTask.message;
177 if (oldMessage == null || message != oldMessage) {
178 bitmapWorkerTask.cancel(true);
179 } else {
180 return false;
181 }
182 }
183 return true;
184 }
185
186 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
187 if (imageView != null) {
188 final Drawable drawable = imageView.getDrawable();
189 if (drawable instanceof AsyncDrawable asyncDrawable) {
190 return asyncDrawable.getBitmapWorkerTask();
191 }
192 }
193 return null;
194 }
195
196 protected void hideToast() {
197 final var toast = this.mToast;
198 if (toast == null) {
199 return;
200 }
201 toast.cancel();
202 }
203
204 protected void replaceToast(String msg) {
205 replaceToast(msg, true);
206 }
207
208 protected void replaceToast(String msg, boolean showlong) {
209 hideToast();
210 mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
211 mToast.show();
212 }
213
214 protected final void refreshUi() {
215 final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
216 if (diff > Config.REFRESH_UI_INTERVAL) {
217 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
218 runOnUiThread(mRefreshUiRunnable);
219 } else {
220 final long next = Config.REFRESH_UI_INTERVAL - diff;
221 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
222 mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
223 }
224 }
225
226 protected abstract void refreshUiReal();
227
228 @Override
229 public void onStart() {
230 super.onStart();
231 if (!xmppConnectionServiceBound) {
232 connectToBackend();
233 } else {
234 this.registerListeners();
235 this.onBackendConnected();
236 }
237 this.mUsingEnterKey = usingEnterKey();
238 this.mUseTor = useTor();
239 }
240
241 public void connectToBackend() {
242 Intent intent = new Intent(this, XmppConnectionService.class);
243 intent.setAction("ui");
244 try {
245 startService(intent);
246 } catch (IllegalStateException e) {
247 Log.w(Config.LOGTAG, "unable to start service from " + getClass().getSimpleName());
248 }
249 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
250 }
251
252 @Override
253 protected void onStop() {
254 super.onStop();
255 if (xmppConnectionServiceBound) {
256 this.unregisterListeners();
257 unbindService(mConnection);
258 xmppConnectionServiceBound = false;
259 }
260 }
261
262 @RequiresApi(api = Build.VERSION_CODES.R)
263 protected void configureCustomNotification(final ShortcutInfoCompat shortcut) {
264 final var notificationManager = getSystemService(NotificationManager.class);
265 final var channel =
266 notificationManager.getNotificationChannel(
267 NotificationService.MESSAGES_NOTIFICATION_CHANNEL, shortcut.getId());
268 if (channel != null && channel.getConversationId() != null) {
269 ShortcutManagerCompat.pushDynamicShortcut(this, shortcut);
270 openNotificationSettings(shortcut);
271 } else {
272 new MaterialAlertDialogBuilder(this)
273 .setTitle(R.string.custom_notifications)
274 .setMessage(R.string.custom_notifications_enable)
275 .setPositiveButton(
276 R.string.continue_btn,
277 (d, w) -> {
278 NotificationService.createConversationChannel(this, shortcut);
279 ShortcutManagerCompat.pushDynamicShortcut(this, shortcut);
280 openNotificationSettings(shortcut);
281 })
282 .setNegativeButton(R.string.cancel, null)
283 .create()
284 .show();
285 }
286 }
287
288 @RequiresApi(api = Build.VERSION_CODES.R)
289 protected void openNotificationSettings(final ShortcutInfoCompat shortcut) {
290 final var intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
291 intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
292 intent.putExtra(
293 Settings.EXTRA_CHANNEL_ID, NotificationService.MESSAGES_NOTIFICATION_CHANNEL);
294 intent.putExtra(Settings.EXTRA_CONVERSATION_ID, shortcut.getId());
295 startActivity(intent);
296 }
297
298 public boolean hasPgp() {
299 return xmppConnectionService.getPgpEngine() != null;
300 }
301
302 public void showInstallPgpDialog() {
303 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
304 builder.setTitle(getString(R.string.openkeychain_required));
305 builder.setIconAttribute(android.R.attr.alertDialogIcon);
306 builder.setMessage(
307 Html.fromHtml(
308 getString(
309 R.string.openkeychain_required_long,
310 getString(R.string.app_name))));
311 builder.setNegativeButton(getString(R.string.cancel), null);
312 builder.setNeutralButton(
313 getString(R.string.restart),
314 (dialog, which) -> {
315 if (xmppConnectionServiceBound) {
316 unbindService(mConnection);
317 xmppConnectionServiceBound = false;
318 }
319 stopService(new Intent(XmppActivity.this, XmppConnectionService.class));
320 finish();
321 });
322 builder.setPositiveButton(
323 getString(R.string.install),
324 (dialog, which) -> {
325 final Uri uri =
326 Uri.parse("market://details?id=org.sufficientlysecure.keychain");
327 Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri);
328 PackageManager manager = getApplicationContext().getPackageManager();
329 final var infos = manager.queryIntentActivities(marketIntent, 0);
330 if (infos.isEmpty()) {
331 final var website = Uri.parse("http://www.openkeychain.org/");
332 final Intent browserIntent = new Intent(Intent.ACTION_VIEW, website);
333 try {
334 startActivity(browserIntent);
335 } catch (final ActivityNotFoundException e) {
336 Toast.makeText(
337 this,
338 R.string.application_found_to_open_website,
339 Toast.LENGTH_LONG)
340 .show();
341 }
342 } else {
343 startActivity(marketIntent);
344 }
345 finish();
346 });
347 builder.create().show();
348 }
349
350 public void addReaction(final Message message, Consumer<Collection<String>> callback) {
351 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
352 final var layoutInflater = this.getLayoutInflater();
353 final DialogAddReactionBinding viewBinding =
354 DataBindingUtil.inflate(layoutInflater, R.layout.dialog_add_reaction, null, false);
355 builder.setView(viewBinding.getRoot());
356 final var dialog = builder.create();
357 for (final String emoji : Reaction.SUGGESTIONS) {
358 final Button button =
359 (Button)
360 layoutInflater.inflate(
361 R.layout.item_emoji_button, viewBinding.emojis, false);
362 viewBinding.emojis.addView(button);
363 button.setText(emoji);
364 button.setOnClickListener(
365 v -> {
366 final var aggregated = message.getAggregatedReactions();
367 if (aggregated.ourReactions.contains(emoji)) {
368 callback.accept(aggregated.ourReactions);
369 } else {
370 final ImmutableSet.Builder<String> reactionBuilder =
371 new ImmutableSet.Builder<>();
372 reactionBuilder.addAll(aggregated.ourReactions);
373 reactionBuilder.add(emoji);
374 callback.accept(reactionBuilder.build());
375 }
376 dialog.dismiss();
377 });
378 }
379 viewBinding.more.setOnClickListener(
380 v -> {
381 dialog.dismiss();
382 final var intent = new Intent(this, AddReactionActivity.class);
383 intent.putExtra("conversation", message.getConversation().getUuid());
384 intent.putExtra("message", message.getUuid());
385 startActivity(intent);
386 });
387 dialog.show();
388 }
389
390 protected void deleteAccount(final Account account) {
391 this.deleteAccount(account, null);
392 }
393
394 protected void deleteAccount(final Account account, final Runnable postDelete) {
395 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
396 final View dialogView = getLayoutInflater().inflate(R.layout.dialog_delete_account, null);
397 builder.setView(dialogView);
398 builder.setTitle(R.string.mgmt_account_delete);
399 builder.setPositiveButton(getString(R.string.delete), null);
400 builder.setNegativeButton(getString(R.string.cancel), null);
401 final AlertDialog dialog = builder.create();
402 dialog.setOnShowListener(
403 dialogInterface -> onShowDeleteDialog(dialogInterface, account, postDelete));
404 dialog.show();
405 }
406
407 private void onShowDeleteDialog(
408 final DialogInterface dialogInterface,
409 final Account account,
410 final Runnable postDelete) {
411 final AlertDialog alertDialog;
412 if (dialogInterface instanceof AlertDialog dialog) {
413 alertDialog = dialog;
414 } else {
415 throw new IllegalStateException("DialogInterface was not of type AlertDialog");
416 }
417 final var button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
418 button.setOnClickListener(
419 v -> onDeleteDialogButtonClicked(alertDialog, account, postDelete));
420 }
421
422 private void onDeleteDialogButtonClicked(
423 final AlertDialog dialog, final Account account, final Runnable postDelete) {
424 final CheckBox deleteFromServer = dialog.findViewById(R.id.delete_from_server);
425 if (deleteFromServer == null) {
426 throw new IllegalStateException("AlertDialog did not have button");
427 }
428 final var button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
429 final boolean unregister = deleteFromServer.isChecked();
430 if (unregister) {
431 if (account.isOnlineAndConnected()) {
432 final var connection = account.getXmppConnection();
433 deleteFromServer.setEnabled(false);
434 button.setText(R.string.please_wait);
435 button.setEnabled(false);
436 final var future = connection.getManager(RegistrationManager.class).unregister();
437 Futures.addCallback(
438 future,
439 new FutureCallback<>() {
440 @Override
441 public void onSuccess(Void result) {
442 runOnUiThread(
443 () -> onAccountDeletedSuccess(account, dialog, postDelete));
444 }
445
446 @Override
447 public void onFailure(@NonNull Throwable t) {
448 Log.d(Config.LOGTAG, "could not unregister account", t);
449 runOnUiThread(() -> onAccountDeletionFailure(dialog, postDelete));
450 }
451 },
452 MoreExecutors.directExecutor());
453 } else {
454 Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_LONG).show();
455 }
456 } else {
457 onAccountDeletedSuccess(account, dialog, postDelete);
458 }
459 }
460
461 private void onAccountDeletedSuccess(
462 final Account account, final AlertDialog dialog, final Runnable postDelete) {
463 xmppConnectionService.deleteAccount(account);
464 dialog.dismiss();
465 if (xmppConnectionService.getAccounts().isEmpty() && Config.MAGIC_CREATE_DOMAIN != null) {
466 final Intent intent = SignupUtils.getSignUpIntent(this);
467 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
468 startActivity(intent);
469 } else if (postDelete != null) {
470 postDelete.run();
471 }
472 }
473
474 private void onAccountDeletionFailure(final AlertDialog dialog, final Runnable postDelete) {
475 final CheckBox deleteFromServer = dialog.findViewById(R.id.delete_from_server);
476 if (deleteFromServer == null) {
477 throw new IllegalStateException("AlertDialog did not have button");
478 }
479 final var button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
480 deleteFromServer.setEnabled(true);
481 button.setText(R.string.delete);
482 button.setEnabled(true);
483 Toast.makeText(this, R.string.could_not_delete_account_from_server, Toast.LENGTH_LONG)
484 .show();
485 }
486
487 protected abstract void onBackendConnected();
488
489 protected void registerListeners() {
490 if (this instanceof XmppConnectionService.OnConversationUpdate) {
491 this.xmppConnectionService.setOnConversationListChangedListener(
492 (XmppConnectionService.OnConversationUpdate) this);
493 }
494 if (this instanceof XmppConnectionService.OnAccountUpdate) {
495 this.xmppConnectionService.setOnAccountListChangedListener(
496 (XmppConnectionService.OnAccountUpdate) this);
497 }
498 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
499 this.xmppConnectionService.setOnCaptchaRequestedListener(
500 (XmppConnectionService.OnCaptchaRequested) this);
501 }
502 if (this instanceof XmppConnectionService.OnRosterUpdate) {
503 this.xmppConnectionService.setOnRosterUpdateListener(
504 (XmppConnectionService.OnRosterUpdate) this);
505 }
506 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
507 this.xmppConnectionService.setOnMucRosterUpdateListener(
508 (XmppConnectionService.OnMucRosterUpdate) this);
509 }
510 if (this instanceof OnUpdateBlocklist) {
511 this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
512 }
513 if (this instanceof XmppConnectionService.OnShowErrorToast) {
514 this.xmppConnectionService.setOnShowErrorToastListener(
515 (XmppConnectionService.OnShowErrorToast) this);
516 }
517 if (this instanceof OnKeyStatusUpdated) {
518 this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
519 }
520 if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
521 this.xmppConnectionService.setOnRtpConnectionUpdateListener(
522 (XmppConnectionService.OnJingleRtpConnectionUpdate) this);
523 }
524 }
525
526 protected void unregisterListeners() {
527 if (this instanceof XmppConnectionService.OnConversationUpdate) {
528 this.xmppConnectionService.removeOnConversationListChangedListener(
529 (XmppConnectionService.OnConversationUpdate) this);
530 }
531 if (this instanceof XmppConnectionService.OnAccountUpdate) {
532 this.xmppConnectionService.removeOnAccountListChangedListener(
533 (XmppConnectionService.OnAccountUpdate) this);
534 }
535 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
536 this.xmppConnectionService.removeOnCaptchaRequestedListener(
537 (XmppConnectionService.OnCaptchaRequested) this);
538 }
539 if (this instanceof XmppConnectionService.OnRosterUpdate) {
540 this.xmppConnectionService.removeOnRosterUpdateListener(
541 (XmppConnectionService.OnRosterUpdate) this);
542 }
543 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
544 this.xmppConnectionService.removeOnMucRosterUpdateListener(
545 (XmppConnectionService.OnMucRosterUpdate) this);
546 }
547 if (this instanceof OnUpdateBlocklist) {
548 this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
549 }
550 if (this instanceof XmppConnectionService.OnShowErrorToast) {
551 this.xmppConnectionService.removeOnShowErrorToastListener(
552 (XmppConnectionService.OnShowErrorToast) this);
553 }
554 if (this instanceof OnKeyStatusUpdated) {
555 this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
556 }
557 if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
558 this.xmppConnectionService.removeRtpConnectionUpdateListener(
559 (XmppConnectionService.OnJingleRtpConnectionUpdate) this);
560 }
561 }
562
563 @Override
564 public boolean onOptionsItemSelected(final MenuItem item) {
565 switch (item.getItemId()) {
566 case R.id.action_settings:
567 startActivity(
568 new Intent(
569 this, eu.siacs.conversations.ui.activity.SettingsActivity.class));
570 break;
571 case R.id.action_privacy_policy:
572 openPrivacyPolicy();
573 break;
574 case R.id.action_accounts:
575 AccountUtils.launchManageAccounts(this);
576 break;
577 case R.id.action_account:
578 AccountUtils.launchManageAccount(this);
579 break;
580 case android.R.id.home:
581 finish();
582 break;
583 case R.id.action_show_qr_code:
584 showQrCode();
585 break;
586 }
587 return super.onOptionsItemSelected(item);
588 }
589
590 private void openPrivacyPolicy() {
591 if (BuildConfig.PRIVACY_POLICY == null) {
592 return;
593 }
594 final var viewPolicyIntent = new Intent(Intent.ACTION_VIEW);
595 viewPolicyIntent.setData(Uri.parse(BuildConfig.PRIVACY_POLICY));
596 try {
597 startActivity(viewPolicyIntent);
598 } catch (final ActivityNotFoundException e) {
599 Toast.makeText(this, R.string.no_application_found_to_open_link, Toast.LENGTH_SHORT)
600 .show();
601 }
602 }
603
604 public void selectPresence(
605 final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
606 final Contact contact = conversation.getContact();
607 if (contact.showInRoster() || contact.isSelf()) {
608 final Presences presences = contact.getPresences();
609 if (presences.size() == 0) {
610 if (contact.isSelf()) {
611 conversation.setNextCounterpart(null);
612 listener.onPresenceSelected();
613 } else if (!contact.getOption(Contact.Options.TO)
614 && !contact.getOption(Contact.Options.ASKING)
615 && contact.getAccount().getStatus() == Account.State.ONLINE) {
616 showAskForPresenceDialog(contact);
617 } else if (!contact.getOption(Contact.Options.TO)
618 || !contact.getOption(Contact.Options.FROM)) {
619 PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
620 } else {
621 conversation.setNextCounterpart(null);
622 listener.onPresenceSelected();
623 }
624 } else if (presences.size() == 1) {
625 final String presence = presences.toResourceArray()[0];
626 conversation.setNextCounterpart(
627 PresenceSelector.getNextCounterpart(contact, presence));
628 listener.onPresenceSelected();
629 } else {
630 PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
631 }
632 } else {
633 showAddToRosterDialog(conversation.getContact());
634 }
635 }
636
637 @SuppressLint("UnsupportedChromeOsCameraSystemFeature")
638 @Override
639 protected void onCreate(Bundle savedInstanceState) {
640 super.onCreate(savedInstanceState);
641 metrics = getResources().getDisplayMetrics();
642 this.isCameraFeatureAvailable =
643 getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
644 }
645
646 protected boolean isCameraFeatureAvailable() {
647 return this.isCameraFeatureAvailable;
648 }
649
650 protected boolean isOptimizingBattery() {
651 final PowerManager pm = getSystemService(PowerManager.class);
652 return !pm.isIgnoringBatteryOptimizations(getPackageName());
653 }
654
655 protected boolean isAffectedByDataSaver() {
656 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
657 final ConnectivityManager cm =
658 (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
659 return cm != null
660 && cm.isActiveNetworkMetered()
661 && Compatibility.getRestrictBackgroundStatus(cm)
662 == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
663 } else {
664 return false;
665 }
666 }
667
668 private boolean usingEnterKey() {
669 return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
670 }
671
672 private boolean useTor() {
673 return QuickConversationsService.isConversations()
674 && getBooleanPreference("use_tor", R.bool.use_tor);
675 }
676
677 protected SharedPreferences getPreferences() {
678 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
679 }
680
681 protected boolean getBooleanPreference(String name, @BoolRes int res) {
682 return getPreferences().getBoolean(name, getResources().getBoolean(res));
683 }
684
685 public void switchToConversation(Conversation conversation) {
686 switchToConversation(conversation, null);
687 }
688
689 public void switchToConversationAndQuote(Conversation conversation, String text) {
690 switchToConversation(conversation, text, true, null, false, false);
691 }
692
693 public void switchToConversation(Conversation conversation, String text) {
694 switchToConversation(conversation, text, false, null, false, false);
695 }
696
697 public void switchToConversationDoNotAppend(Conversation conversation, String text) {
698 switchToConversation(conversation, text, false, null, false, true);
699 }
700
701 public void highlightInMuc(Conversation conversation, String nick) {
702 switchToConversation(conversation, null, false, nick, false, false);
703 }
704
705 public void privateMsgInMuc(Conversation conversation, String nick) {
706 switchToConversation(conversation, null, false, nick, true, false);
707 }
708
709 private void switchToConversation(
710 Conversation conversation,
711 String text,
712 boolean asQuote,
713 String nick,
714 boolean pm,
715 boolean doNotAppend) {
716 Intent intent = new Intent(this, ConversationsActivity.class);
717 intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
718 intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
719 if (text != null) {
720 intent.putExtra(Intent.EXTRA_TEXT, text);
721 if (asQuote) {
722 intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
723 }
724 }
725 if (nick != null) {
726 intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
727 intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
728 }
729 if (doNotAppend) {
730 intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
731 }
732 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
733 startActivity(intent);
734 finish();
735 }
736
737 public void switchToContactDetails(Contact contact) {
738 switchToContactDetails(contact, null);
739 }
740
741 public void switchToContactDetails(Contact contact, String messageFingerprint) {
742 Intent intent = new Intent(this, ContactDetailsActivity.class);
743 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
744 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString());
745 intent.putExtra("contact", contact.getJid().toString());
746 intent.putExtra("fingerprint", messageFingerprint);
747 startActivity(intent);
748 }
749
750 public void switchToAccount(Account account, String fingerprint) {
751 switchToAccount(account, false, fingerprint);
752 }
753
754 public void switchToAccount(Account account) {
755 switchToAccount(account, false, null);
756 }
757
758 public void switchToAccount(Account account, boolean init, String fingerprint) {
759 Intent intent = new Intent(this, EditAccountActivity.class);
760 intent.putExtra("jid", account.getJid().asBareJid().toString());
761 intent.putExtra("init", init);
762 if (init) {
763 intent.setFlags(
764 Intent.FLAG_ACTIVITY_NEW_TASK
765 | Intent.FLAG_ACTIVITY_CLEAR_TASK
766 | Intent.FLAG_ACTIVITY_NO_ANIMATION);
767 }
768 if (fingerprint != null) {
769 intent.putExtra("fingerprint", fingerprint);
770 }
771 startActivity(intent);
772 if (init) {
773 overridePendingTransition(0, 0);
774 }
775 }
776
777 protected void delegateUriPermissionsToService(Uri uri) {
778 Intent intent = new Intent(this, XmppConnectionService.class);
779 intent.setAction(Intent.ACTION_SEND);
780 intent.setData(uri);
781 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
782 try {
783 startService(intent);
784 } catch (Exception e) {
785 Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
786 }
787 }
788
789 protected void inviteToConversation(Conversation conversation) {
790 startActivityForResult(
791 ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
792 }
793
794 protected void announcePgp(
795 final Account account,
796 final Conversation conversation,
797 Intent intent,
798 final Runnable onSuccess) {
799 if (account.getPgpId() == 0) {
800 choosePgpSignId(account);
801 } else {
802 final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
803 xmppConnectionService
804 .getPgpEngine()
805 .generateSignature(
806 intent,
807 account,
808 status,
809 new UiCallback<String>() {
810
811 @Override
812 public void userInputRequired(
813 final PendingIntent pi, final String signature) {
814 try {
815 startIntentSenderForResult(
816 pi.getIntentSender(),
817 REQUEST_ANNOUNCE_PGP,
818 null,
819 0,
820 0,
821 0,
822 Compatibility.pgpStartIntentSenderOptions());
823 } catch (final SendIntentException ignored) {
824 }
825 }
826
827 @Override
828 public void success(String signature) {
829 account.setPgpSignature(signature);
830 xmppConnectionService.databaseBackend.updateAccount(account);
831 xmppConnectionService.sendPresence(account);
832 if (conversation != null) {
833 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
834 xmppConnectionService.updateConversation(conversation);
835 refreshUi();
836 }
837 if (onSuccess != null) {
838 runOnUiThread(onSuccess);
839 }
840 }
841
842 @Override
843 public void error(int error, String signature) {
844 if (error == 0) {
845 account.setPgpSignId(0);
846 account.unsetPgpSignature();
847 xmppConnectionService.databaseBackend.updateAccount(
848 account);
849 choosePgpSignId(account);
850 } else {
851 displayErrorDialog(error);
852 }
853 }
854 });
855 }
856 }
857
858 protected void choosePgpSignId(final Account account) {
859 xmppConnectionService
860 .getPgpEngine()
861 .chooseKey(
862 account,
863 new UiCallback<>() {
864 @Override
865 public void success(final Account a) {}
866
867 @Override
868 public void error(int errorCode, Account object) {}
869
870 @Override
871 public void userInputRequired(PendingIntent pi, Account object) {
872 try {
873 startIntentSenderForResult(
874 pi.getIntentSender(),
875 REQUEST_CHOOSE_PGP_ID,
876 null,
877 0,
878 0,
879 0,
880 Compatibility.pgpStartIntentSenderOptions());
881 } catch (final SendIntentException ignored) {
882 }
883 }
884 });
885 }
886
887 protected void displayErrorDialog(final int errorCode) {
888 runOnUiThread(
889 () -> {
890 final MaterialAlertDialogBuilder builder =
891 new MaterialAlertDialogBuilder(XmppActivity.this);
892 builder.setTitle(getString(R.string.error));
893 builder.setMessage(errorCode);
894 builder.setNeutralButton(R.string.accept, null);
895 builder.create().show();
896 });
897 }
898
899 protected void showAddToRosterDialog(final Contact contact) {
900 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
901 builder.setTitle(contact.getJid().toString());
902 builder.setMessage(getString(R.string.not_in_roster));
903 builder.setNegativeButton(getString(R.string.cancel), null);
904 builder.setPositiveButton(
905 getString(R.string.add_contact),
906 (dialog, which) -> xmppConnectionService.createContact(contact));
907 builder.create().show();
908 }
909
910 private void showAskForPresenceDialog(final Contact contact) {
911 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
912 builder.setTitle(contact.getJid().toString());
913 builder.setMessage(R.string.request_presence_updates);
914 builder.setNegativeButton(R.string.cancel, null);
915 builder.setPositiveButton(
916 R.string.request_now,
917 (dialog, which) -> {
918 final var connection = contact.getAccount().getXmppConnection();
919 connection
920 .getManager(PresenceManager.class)
921 .subscribe(contact.getJid().asBareJid());
922 });
923 builder.create().show();
924 }
925
926 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
927 quickEdit(previousValue, callback, hint, false, false);
928 }
929
930 protected void quickEdit(
931 String previousValue,
932 @StringRes int hint,
933 OnValueEdited callback,
934 boolean permitEmpty) {
935 quickEdit(previousValue, callback, hint, false, permitEmpty);
936 }
937
938 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
939 quickEdit(previousValue, callback, R.string.password, true, false);
940 }
941
942 @SuppressLint("InflateParams")
943 private void quickEdit(
944 final String previousValue,
945 final OnValueEdited callback,
946 final @StringRes int hint,
947 boolean password,
948 boolean permitEmpty) {
949 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
950 final DialogQuickeditBinding binding =
951 DataBindingUtil.inflate(
952 getLayoutInflater(), R.layout.dialog_quickedit, null, false);
953 if (password) {
954 binding.inputEditText.setInputType(
955 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
956 }
957 builder.setPositiveButton(R.string.accept, null);
958 if (hint != 0) {
959 binding.inputLayout.setHint(getString(hint));
960 }
961 binding.inputEditText.requestFocus();
962 if (previousValue != null) {
963 binding.inputEditText.getText().append(previousValue);
964 }
965 builder.setView(binding.getRoot());
966 builder.setNegativeButton(R.string.cancel, null);
967 final AlertDialog dialog = builder.create();
968 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
969 dialog.show();
970 View.OnClickListener clickListener =
971 v -> {
972 String value = binding.inputEditText.getText().toString();
973 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
974 String error = callback.onValueEdited(value);
975 if (error != null) {
976 binding.inputLayout.setError(error);
977 return;
978 }
979 }
980 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
981 dialog.dismiss();
982 };
983 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
984 dialog.getButton(DialogInterface.BUTTON_NEGATIVE)
985 .setOnClickListener(
986 (v -> {
987 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
988 dialog.dismiss();
989 }));
990 dialog.setCanceledOnTouchOutside(false);
991 dialog.setOnDismissListener(
992 dialog1 -> {
993 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
994 });
995 }
996
997 protected boolean hasStoragePermission(int requestCode) {
998 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
999 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
1000 != PackageManager.PERMISSION_GRANTED) {
1001 requestPermissions(
1002 new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
1003 return false;
1004 } else {
1005 return true;
1006 }
1007 } else {
1008 return true;
1009 }
1010 }
1011
1012 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1013 super.onActivityResult(requestCode, resultCode, data);
1014 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
1015 mPendingConferenceInvite = ConferenceInvite.parse(data);
1016 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
1017 if (mPendingConferenceInvite.execute(this)) {
1018 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1019 mToast.show();
1020 }
1021 mPendingConferenceInvite = null;
1022 }
1023 }
1024 }
1025
1026 public boolean copyTextToClipboard(String text, int labelResId) {
1027 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1028 String label = getResources().getString(labelResId);
1029 if (mClipBoardManager != null) {
1030 ClipData mClipData = ClipData.newPlainText(label, text);
1031 mClipBoardManager.setPrimaryClip(mClipData);
1032 return true;
1033 }
1034 return false;
1035 }
1036
1037 protected boolean manuallyChangePresence() {
1038 return getBooleanPreference(
1039 AppSettings.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
1040 }
1041
1042 protected String getShareableUri() {
1043 return getShareableUri(false);
1044 }
1045
1046 protected String getShareableUri(boolean http) {
1047 return null;
1048 }
1049
1050 protected void shareLink(boolean http) {
1051 String uri = getShareableUri(http);
1052 if (uri == null || uri.isEmpty()) {
1053 return;
1054 }
1055 Intent intent = new Intent(Intent.ACTION_SEND);
1056 intent.setType("text/plain");
1057 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
1058 try {
1059 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
1060 } catch (ActivityNotFoundException e) {
1061 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
1062 }
1063 }
1064
1065 protected void launchOpenKeyChain(long keyId) {
1066 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
1067 try {
1068 startIntentSenderForResult(
1069 pgp.getIntentForKey(keyId).getIntentSender(),
1070 0,
1071 null,
1072 0,
1073 0,
1074 0,
1075 Compatibility.pgpStartIntentSenderOptions());
1076 } catch (final Throwable e) {
1077 Log.d(Config.LOGTAG, "could not launch OpenKeyChain", e);
1078 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
1079 }
1080 }
1081
1082 @Override
1083 protected void onResume() {
1084 super.onResume();
1085 SettingsUtils.applyScreenshotSetting(this);
1086 }
1087
1088 @Override
1089 public void onPause() {
1090 super.onPause();
1091 }
1092
1093 @Override
1094 public boolean onMenuOpened(int id, Menu menu) {
1095 if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
1096 MenuDoubleTabUtil.recordMenuOpen();
1097 }
1098 return super.onMenuOpened(id, menu);
1099 }
1100
1101 protected void showQrCode() {
1102 showQrCode(getShareableUri());
1103 }
1104
1105 protected void showQrCode(final String uri) {
1106 if (uri == null || uri.isEmpty()) {
1107 return;
1108 }
1109 final Point size = new Point();
1110 getWindowManager().getDefaultDisplay().getSize(size);
1111 final int width = Math.min(size.x, size.y);
1112 final int black;
1113 final int white;
1114 if (Activities.isNightMode(this)) {
1115 black =
1116 MaterialColors.getColor(
1117 this,
1118 com.google.android.material.R.attr.colorSurfaceContainerHighest,
1119 "No surface color configured");
1120 white =
1121 MaterialColors.getColor(
1122 this,
1123 com.google.android.material.R.attr.colorSurfaceInverse,
1124 "No inverse surface color configured");
1125 } else {
1126 black =
1127 MaterialColors.getColor(
1128 this,
1129 com.google.android.material.R.attr.colorSurfaceInverse,
1130 "No inverse surface color configured");
1131 white =
1132 MaterialColors.getColor(
1133 this,
1134 com.google.android.material.R.attr.colorSurfaceContainerHighest,
1135 "No surface color configured");
1136 }
1137 final var bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width, black, white);
1138 final ImageView view = new ImageView(this);
1139 view.setBackgroundColor(white);
1140 view.setImageBitmap(bitmap);
1141 MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
1142 builder.setView(view);
1143 builder.create().show();
1144 }
1145
1146 protected Account extractAccount(Intent intent) {
1147 final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1148 try {
1149 return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
1150 } catch (IllegalArgumentException e) {
1151 return null;
1152 }
1153 }
1154
1155 public AvatarService avatarService() {
1156 return xmppConnectionService.getAvatarService();
1157 }
1158
1159 public void loadBitmap(Message message, ImageView imageView) {
1160 Bitmap bm;
1161 try {
1162 bm =
1163 xmppConnectionService
1164 .getFileBackend()
1165 .getThumbnail(message, (int) (metrics.density * 288), true);
1166 } catch (IOException e) {
1167 bm = null;
1168 }
1169 if (bm != null) {
1170 cancelPotentialWork(message, imageView);
1171 imageView.setImageBitmap(bm);
1172 imageView.setBackgroundColor(0x00000000);
1173 } else {
1174 if (cancelPotentialWork(message, imageView)) {
1175 imageView.setBackgroundColor(0xff333333);
1176 imageView.setImageDrawable(null);
1177 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1178 final AsyncDrawable asyncDrawable = new AsyncDrawable(getResources(), null, task);
1179 imageView.setImageDrawable(asyncDrawable);
1180 try {
1181 task.execute(message);
1182 } catch (final RejectedExecutionException ignored) {
1183 ignored.printStackTrace();
1184 }
1185 }
1186 }
1187 }
1188
1189 protected interface OnValueEdited {
1190 String onValueEdited(String value);
1191 }
1192
1193 public static class ConferenceInvite {
1194 private String uuid;
1195 private final List<Jid> jids = new ArrayList<>();
1196
1197 public static ConferenceInvite parse(Intent data) {
1198 ConferenceInvite invite = new ConferenceInvite();
1199 invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
1200 if (invite.uuid == null) {
1201 return null;
1202 }
1203 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
1204 return invite;
1205 }
1206
1207 public boolean execute(final XmppActivity activity) {
1208 final XmppConnectionService service = activity.xmppConnectionService;
1209 final Conversation conversation = service.findConversationByUuid(this.uuid);
1210 if (conversation == null) {
1211 return false;
1212 }
1213 if (conversation.getMode() == Conversation.MODE_MULTI) {
1214 for (final Jid jid : jids) {
1215 // TODO use direct invites for public conferences
1216 service.invite(conversation, jid);
1217 }
1218 return false;
1219 } else {
1220 jids.add(conversation.getJid().asBareJid());
1221 return service.createAdhocConference(
1222 conversation.getAccount(), null, jids, activity.adhocCallback);
1223 }
1224 }
1225 }
1226
1227 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1228 private final WeakReference<ImageView> imageViewReference;
1229 private Message message = null;
1230
1231 private BitmapWorkerTask(ImageView imageView) {
1232 this.imageViewReference = new WeakReference<>(imageView);
1233 }
1234
1235 @Override
1236 protected Bitmap doInBackground(Message... params) {
1237 if (isCancelled()) {
1238 return null;
1239 }
1240 message = params[0];
1241 try {
1242 final XmppActivity activity = find(imageViewReference);
1243 if (activity != null && activity.xmppConnectionService != null) {
1244 return activity.xmppConnectionService
1245 .getFileBackend()
1246 .getThumbnail(message, (int) (activity.metrics.density * 288), false);
1247 } else {
1248 return null;
1249 }
1250 } catch (IOException e) {
1251 return null;
1252 }
1253 }
1254
1255 @Override
1256 protected void onPostExecute(final Bitmap bitmap) {
1257 if (!isCancelled()) {
1258 final ImageView imageView = imageViewReference.get();
1259 if (imageView != null) {
1260 imageView.setImageBitmap(bitmap);
1261 imageView.setBackgroundColor(bitmap == null ? 0xff333333 : 0x00000000);
1262 }
1263 }
1264 }
1265 }
1266
1267 private static class AsyncDrawable extends BitmapDrawable {
1268 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1269
1270 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1271 super(res, bitmap);
1272 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1273 }
1274
1275 private BitmapWorkerTask getBitmapWorkerTask() {
1276 return bitmapWorkerTaskReference.get();
1277 }
1278 }
1279
1280 public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1281 final View view = viewWeakReference.get();
1282 return view == null ? null : find(view);
1283 }
1284
1285 public static XmppActivity find(@NonNull final View view) {
1286 Context context = view.getContext();
1287 while (context instanceof ContextWrapper) {
1288 if (context instanceof XmppActivity) {
1289 return (XmppActivity) context;
1290 }
1291 context = ((ContextWrapper) context).getBaseContext();
1292 }
1293 return null;
1294 }
1295}