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