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