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 account.getXmppConnection()
832 .getManager(PresenceManager.class)
833 .available();
834 if (conversation != null) {
835 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
836 xmppConnectionService.updateConversation(conversation);
837 refreshUi();
838 }
839 if (onSuccess != null) {
840 runOnUiThread(onSuccess);
841 }
842 }
843
844 @Override
845 public void error(int error, String signature) {
846 if (error == 0) {
847 account.setPgpSignId(0);
848 account.unsetPgpSignature();
849 xmppConnectionService.databaseBackend.updateAccount(
850 account);
851 choosePgpSignId(account);
852 } else {
853 displayErrorDialog(error);
854 }
855 }
856 });
857 }
858 }
859
860 protected void choosePgpSignId(final Account account) {
861 xmppConnectionService
862 .getPgpEngine()
863 .chooseKey(
864 account,
865 new UiCallback<>() {
866 @Override
867 public void success(final Account a) {}
868
869 @Override
870 public void error(int errorCode, Account object) {}
871
872 @Override
873 public void userInputRequired(PendingIntent pi, Account object) {
874 try {
875 startIntentSenderForResult(
876 pi.getIntentSender(),
877 REQUEST_CHOOSE_PGP_ID,
878 null,
879 0,
880 0,
881 0,
882 Compatibility.pgpStartIntentSenderOptions());
883 } catch (final SendIntentException ignored) {
884 }
885 }
886 });
887 }
888
889 protected void displayErrorDialog(final int errorCode) {
890 runOnUiThread(
891 () -> {
892 final MaterialAlertDialogBuilder builder =
893 new MaterialAlertDialogBuilder(XmppActivity.this);
894 builder.setTitle(getString(R.string.error));
895 builder.setMessage(errorCode);
896 builder.setNeutralButton(R.string.accept, null);
897 builder.create().show();
898 });
899 }
900
901 protected void showAddToRosterDialog(final Contact contact) {
902 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
903 builder.setTitle(contact.getJid().toString());
904 builder.setMessage(getString(R.string.not_in_roster));
905 builder.setNegativeButton(getString(R.string.cancel), null);
906 builder.setPositiveButton(
907 getString(R.string.add_contact),
908 (dialog, which) -> xmppConnectionService.createContact(contact));
909 builder.create().show();
910 }
911
912 private void showAskForPresenceDialog(final Contact contact) {
913 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
914 builder.setTitle(contact.getJid().toString());
915 builder.setMessage(R.string.request_presence_updates);
916 builder.setNegativeButton(R.string.cancel, null);
917 builder.setPositiveButton(
918 R.string.request_now,
919 (dialog, which) -> {
920 final var connection = contact.getAccount().getXmppConnection();
921 connection
922 .getManager(PresenceManager.class)
923 .subscribe(contact.getJid().asBareJid());
924 });
925 builder.create().show();
926 }
927
928 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
929 quickEdit(previousValue, callback, hint, false, false);
930 }
931
932 protected void quickEdit(
933 String previousValue,
934 @StringRes int hint,
935 OnValueEdited callback,
936 boolean permitEmpty) {
937 quickEdit(previousValue, callback, hint, false, permitEmpty);
938 }
939
940 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
941 quickEdit(previousValue, callback, R.string.password, true, false);
942 }
943
944 @SuppressLint("InflateParams")
945 private void quickEdit(
946 final String previousValue,
947 final OnValueEdited callback,
948 final @StringRes int hint,
949 boolean password,
950 boolean permitEmpty) {
951 final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
952 final DialogQuickeditBinding binding =
953 DataBindingUtil.inflate(
954 getLayoutInflater(), R.layout.dialog_quickedit, null, false);
955 if (password) {
956 binding.inputEditText.setInputType(
957 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
958 }
959 builder.setPositiveButton(R.string.accept, null);
960 if (hint != 0) {
961 binding.inputLayout.setHint(getString(hint));
962 }
963 binding.inputEditText.requestFocus();
964 if (previousValue != null) {
965 binding.inputEditText.getText().append(previousValue);
966 }
967 builder.setView(binding.getRoot());
968 builder.setNegativeButton(R.string.cancel, null);
969 final AlertDialog dialog = builder.create();
970 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
971 dialog.show();
972 View.OnClickListener clickListener =
973 v -> {
974 String value = binding.inputEditText.getText().toString();
975 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
976 String error = callback.onValueEdited(value);
977 if (error != null) {
978 binding.inputLayout.setError(error);
979 return;
980 }
981 }
982 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
983 dialog.dismiss();
984 };
985 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
986 dialog.getButton(DialogInterface.BUTTON_NEGATIVE)
987 .setOnClickListener(
988 (v -> {
989 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
990 dialog.dismiss();
991 }));
992 dialog.setCanceledOnTouchOutside(false);
993 dialog.setOnDismissListener(
994 dialog1 -> {
995 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
996 });
997 }
998
999 protected boolean hasStoragePermission(int requestCode) {
1000 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
1001 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
1002 != PackageManager.PERMISSION_GRANTED) {
1003 requestPermissions(
1004 new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
1005 return false;
1006 } else {
1007 return true;
1008 }
1009 } else {
1010 return true;
1011 }
1012 }
1013
1014 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1015 super.onActivityResult(requestCode, resultCode, data);
1016 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
1017 mPendingConferenceInvite = ConferenceInvite.parse(data);
1018 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
1019 if (mPendingConferenceInvite.execute(this)) {
1020 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1021 mToast.show();
1022 }
1023 mPendingConferenceInvite = null;
1024 }
1025 }
1026 }
1027
1028 public boolean copyTextToClipboard(String text, int labelResId) {
1029 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1030 String label = getResources().getString(labelResId);
1031 if (mClipBoardManager != null) {
1032 ClipData mClipData = ClipData.newPlainText(label, text);
1033 mClipBoardManager.setPrimaryClip(mClipData);
1034 return true;
1035 }
1036 return false;
1037 }
1038
1039 protected boolean manuallyChangePresence() {
1040 return getBooleanPreference(
1041 AppSettings.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
1042 }
1043
1044 protected String getShareableUri() {
1045 return getShareableUri(false);
1046 }
1047
1048 protected String getShareableUri(boolean http) {
1049 return null;
1050 }
1051
1052 protected void shareLink(boolean http) {
1053 String uri = getShareableUri(http);
1054 if (uri == null || uri.isEmpty()) {
1055 return;
1056 }
1057 Intent intent = new Intent(Intent.ACTION_SEND);
1058 intent.setType("text/plain");
1059 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
1060 try {
1061 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
1062 } catch (ActivityNotFoundException e) {
1063 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
1064 }
1065 }
1066
1067 protected void launchOpenKeyChain(long keyId) {
1068 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
1069 try {
1070 startIntentSenderForResult(
1071 pgp.getIntentForKey(keyId).getIntentSender(),
1072 0,
1073 null,
1074 0,
1075 0,
1076 0,
1077 Compatibility.pgpStartIntentSenderOptions());
1078 } catch (final Throwable e) {
1079 Log.d(Config.LOGTAG, "could not launch OpenKeyChain", e);
1080 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
1081 }
1082 }
1083
1084 @Override
1085 protected void onResume() {
1086 super.onResume();
1087 SettingsUtils.applyScreenshotSetting(this);
1088 }
1089
1090 @Override
1091 public void onPause() {
1092 super.onPause();
1093 }
1094
1095 @Override
1096 public boolean onMenuOpened(int id, Menu menu) {
1097 if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
1098 MenuDoubleTabUtil.recordMenuOpen();
1099 }
1100 return super.onMenuOpened(id, menu);
1101 }
1102
1103 protected void showQrCode() {
1104 showQrCode(getShareableUri());
1105 }
1106
1107 protected void showQrCode(final String uri) {
1108 if (uri == null || uri.isEmpty()) {
1109 return;
1110 }
1111 final Point size = new Point();
1112 getWindowManager().getDefaultDisplay().getSize(size);
1113 final int width = Math.min(size.x, size.y);
1114 final int black;
1115 final int white;
1116 if (Activities.isNightMode(this)) {
1117 black =
1118 MaterialColors.getColor(
1119 this,
1120 com.google.android.material.R.attr.colorSurfaceContainerHighest,
1121 "No surface color configured");
1122 white =
1123 MaterialColors.getColor(
1124 this,
1125 com.google.android.material.R.attr.colorSurfaceInverse,
1126 "No inverse surface color configured");
1127 } else {
1128 black =
1129 MaterialColors.getColor(
1130 this,
1131 com.google.android.material.R.attr.colorSurfaceInverse,
1132 "No inverse surface color configured");
1133 white =
1134 MaterialColors.getColor(
1135 this,
1136 com.google.android.material.R.attr.colorSurfaceContainerHighest,
1137 "No surface color configured");
1138 }
1139 final var bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width, black, white);
1140 final ImageView view = new ImageView(this);
1141 view.setBackgroundColor(white);
1142 view.setImageBitmap(bitmap);
1143 MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
1144 builder.setView(view);
1145 builder.create().show();
1146 }
1147
1148 protected Account extractAccount(Intent intent) {
1149 final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
1150 try {
1151 return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
1152 } catch (IllegalArgumentException e) {
1153 return null;
1154 }
1155 }
1156
1157 public AvatarService avatarService() {
1158 return xmppConnectionService.getAvatarService();
1159 }
1160
1161 public void loadBitmap(Message message, ImageView imageView) {
1162 Bitmap bm;
1163 try {
1164 bm =
1165 xmppConnectionService
1166 .getFileBackend()
1167 .getThumbnail(message, (int) (metrics.density * 288), true);
1168 } catch (IOException e) {
1169 bm = null;
1170 }
1171 if (bm != null) {
1172 cancelPotentialWork(message, imageView);
1173 imageView.setImageBitmap(bm);
1174 imageView.setBackgroundColor(0x00000000);
1175 } else {
1176 if (cancelPotentialWork(message, imageView)) {
1177 imageView.setBackgroundColor(0xff333333);
1178 imageView.setImageDrawable(null);
1179 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1180 final AsyncDrawable asyncDrawable = new AsyncDrawable(getResources(), null, task);
1181 imageView.setImageDrawable(asyncDrawable);
1182 try {
1183 task.execute(message);
1184 } catch (final RejectedExecutionException ignored) {
1185 ignored.printStackTrace();
1186 }
1187 }
1188 }
1189 }
1190
1191 protected interface OnValueEdited {
1192 String onValueEdited(String value);
1193 }
1194
1195 public static class ConferenceInvite {
1196 private String uuid;
1197 private final List<Jid> jids = new ArrayList<>();
1198
1199 public static ConferenceInvite parse(Intent data) {
1200 ConferenceInvite invite = new ConferenceInvite();
1201 invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
1202 if (invite.uuid == null) {
1203 return null;
1204 }
1205 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
1206 return invite;
1207 }
1208
1209 public boolean execute(final XmppActivity activity) {
1210 final XmppConnectionService service = activity.xmppConnectionService;
1211 final Conversation conversation = service.findConversationByUuid(this.uuid);
1212 if (conversation == null) {
1213 return false;
1214 }
1215 if (conversation.getMode() == Conversation.MODE_MULTI) {
1216 for (final Jid jid : jids) {
1217 // TODO use direct invites for public conferences
1218 service.invite(conversation, jid);
1219 }
1220 return false;
1221 } else {
1222 jids.add(conversation.getJid().asBareJid());
1223 return service.createAdhocConference(
1224 conversation.getAccount(), null, jids, activity.adhocCallback);
1225 }
1226 }
1227 }
1228
1229 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1230 private final WeakReference<ImageView> imageViewReference;
1231 private Message message = null;
1232
1233 private BitmapWorkerTask(ImageView imageView) {
1234 this.imageViewReference = new WeakReference<>(imageView);
1235 }
1236
1237 @Override
1238 protected Bitmap doInBackground(Message... params) {
1239 if (isCancelled()) {
1240 return null;
1241 }
1242 message = params[0];
1243 try {
1244 final XmppActivity activity = find(imageViewReference);
1245 if (activity != null && activity.xmppConnectionService != null) {
1246 return activity.xmppConnectionService
1247 .getFileBackend()
1248 .getThumbnail(message, (int) (activity.metrics.density * 288), false);
1249 } else {
1250 return null;
1251 }
1252 } catch (IOException e) {
1253 return null;
1254 }
1255 }
1256
1257 @Override
1258 protected void onPostExecute(final Bitmap bitmap) {
1259 if (!isCancelled()) {
1260 final ImageView imageView = imageViewReference.get();
1261 if (imageView != null) {
1262 imageView.setImageBitmap(bitmap);
1263 imageView.setBackgroundColor(bitmap == null ? 0xff333333 : 0x00000000);
1264 }
1265 }
1266 }
1267 }
1268
1269 private static class AsyncDrawable extends BitmapDrawable {
1270 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1271
1272 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1273 super(res, bitmap);
1274 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1275 }
1276
1277 private BitmapWorkerTask getBitmapWorkerTask() {
1278 return bitmapWorkerTaskReference.get();
1279 }
1280 }
1281
1282 public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1283 final View view = viewWeakReference.get();
1284 return view == null ? null : find(view);
1285 }
1286
1287 public static XmppActivity find(@NonNull final View view) {
1288 Context context = view.getContext();
1289 while (context instanceof ContextWrapper) {
1290 if (context instanceof XmppActivity) {
1291 return (XmppActivity) context;
1292 }
1293 context = ((ContextWrapper) context).getBaseContext();
1294 }
1295 return null;
1296 }
1297}