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