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