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