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