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.putExtra(ConversationsActivity.EXTRA_JID, (CharSequence) jid);
484 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
485 startActivity(intent);
486 }
487
488 public void switchToConversation(Conversation conversation) {
489 switchToConversation(conversation, null);
490 }
491
492 public void switchToConversationAndQuote(Conversation conversation, String text) {
493 switchToConversation(conversation, text, true, null, false, false);
494 }
495
496 public void switchToConversation(Conversation conversation, String text) {
497 switchToConversation(conversation, text, false, null, false, false);
498 }
499
500 public void switchToConversationDoNotAppend(Conversation conversation, String text) {
501 switchToConversation(conversation, text, false, null, false, true);
502 }
503
504 public void highlightInMuc(Conversation conversation, String nick) {
505 switchToConversation(conversation, null, false, nick, false, false);
506 }
507
508 public void privateMsgInMuc(Conversation conversation, String nick) {
509 switchToConversation(conversation, null, false, nick, true, false);
510 }
511
512 public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
513 switchToConversation(conversation, text, asQuote, nick, pm, doNotAppend, null);
514 }
515
516 public void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend, String postInit) {
517 if (conversation == null) return;
518
519 Intent intent = new Intent(this, ConversationsActivity.class);
520 intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
521 intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
522 if (text != null) {
523 intent.putExtra(Intent.EXTRA_TEXT, text);
524 if (asQuote) {
525 intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
526 }
527 }
528 if (nick != null) {
529 intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
530 intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
531 }
532 if (doNotAppend) {
533 intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
534 }
535 intent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, postInit);
536 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
537 startActivity(intent);
538 finish();
539 }
540
541 public void switchToContactDetails(Contact contact) {
542 switchToContactDetails(contact, null);
543 }
544
545 public void switchToContactDetails(Contact contact, String messageFingerprint) {
546 Intent intent = new Intent(this, ContactDetailsActivity.class);
547 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
548 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toEscapedString());
549 intent.putExtra("contact", contact.getJid().toEscapedString());
550 intent.putExtra("fingerprint", messageFingerprint);
551 startActivity(intent);
552 }
553
554 public void switchToAccount(Account account, String fingerprint) {
555 switchToAccount(account, false, fingerprint);
556 }
557
558 public void switchToAccount(Account account) {
559 switchToAccount(account, false, null);
560 }
561
562 public void switchToAccount(Account account, boolean init, String fingerprint) {
563 Intent intent = new Intent(this, EditAccountActivity.class);
564 intent.putExtra("jid", account.getJid().asBareJid().toEscapedString());
565 intent.putExtra("init", init);
566 if (init) {
567 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
568 }
569 if (fingerprint != null) {
570 intent.putExtra("fingerprint", fingerprint);
571 }
572 startActivity(intent);
573 if (init) {
574 overridePendingTransition(0, 0);
575 }
576 }
577
578 protected void delegateUriPermissionsToService(Uri uri) {
579 Intent intent = new Intent(this, XmppConnectionService.class);
580 intent.setAction(Intent.ACTION_SEND);
581 intent.setData(uri);
582 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
583 try {
584 startService(intent);
585 } catch (Exception e) {
586 Log.e(Config.LOGTAG, "unable to delegate uri permission", e);
587 }
588 }
589
590 protected void inviteToConversation(Conversation conversation) {
591 startActivityForResult(ChooseContactActivity.create(this, conversation), REQUEST_INVITE_TO_CONVERSATION);
592 }
593
594 protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
595 if (account.getPgpId() == 0) {
596 choosePgpSignId(account);
597 } else {
598 final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
599 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
600
601 @Override
602 public void userInputRequired(PendingIntent pi, String signature) {
603 try {
604 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
605 } catch (final SendIntentException ignored) {
606 }
607 }
608
609 @Override
610 public void success(String signature) {
611 account.setPgpSignature(signature);
612 xmppConnectionService.databaseBackend.updateAccount(account);
613 xmppConnectionService.sendPresence(account);
614 if (conversation != null) {
615 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
616 xmppConnectionService.updateConversation(conversation);
617 refreshUi();
618 }
619 if (onSuccess != null) {
620 runOnUiThread(onSuccess);
621 }
622 }
623
624 @Override
625 public void error(int error, String signature) {
626 if (error == 0) {
627 account.setPgpSignId(0);
628 account.unsetPgpSignature();
629 xmppConnectionService.databaseBackend.updateAccount(account);
630 choosePgpSignId(account);
631 } else {
632 displayErrorDialog(error);
633 }
634 }
635 });
636 }
637 }
638
639 @SuppressWarnings("deprecation")
640 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
641 protected void setListItemBackgroundOnView(View view) {
642 int sdk = android.os.Build.VERSION.SDK_INT;
643 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
644 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
645 } else {
646 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
647 }
648 }
649
650 protected void choosePgpSignId(Account account) {
651 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
652 @Override
653 public void success(Account account1) {
654 }
655
656 @Override
657 public void error(int errorCode, Account object) {
658
659 }
660
661 @Override
662 public void userInputRequired(PendingIntent pi, Account object) {
663 try {
664 startIntentSenderForResult(pi.getIntentSender(),
665 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
666 } catch (final SendIntentException ignored) {
667 }
668 }
669 });
670 }
671
672 protected void displayErrorDialog(final int errorCode) {
673 runOnUiThread(() -> {
674 Builder builder = new Builder(XmppActivity.this);
675 builder.setIconAttribute(android.R.attr.alertDialogIcon);
676 builder.setTitle(getString(R.string.error));
677 builder.setMessage(errorCode);
678 builder.setNeutralButton(R.string.accept, null);
679 builder.create().show();
680 });
681
682 }
683
684 protected void showAddToRosterDialog(final Contact contact) {
685 AlertDialog.Builder builder = new AlertDialog.Builder(this);
686 builder.setTitle(contact.getJid().toString());
687 builder.setMessage(getString(R.string.not_in_roster));
688 builder.setNegativeButton(getString(R.string.cancel), null);
689 builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact, true));
690 builder.create().show();
691 }
692
693 private void showAskForPresenceDialog(final Contact contact) {
694 AlertDialog.Builder builder = new AlertDialog.Builder(this);
695 builder.setTitle(contact.getJid().toString());
696 builder.setMessage(R.string.request_presence_updates);
697 builder.setNegativeButton(R.string.cancel, null);
698 builder.setPositiveButton(R.string.request_now,
699 (dialog, which) -> {
700 if (xmppConnectionServiceBound) {
701 xmppConnectionService.sendPresencePacket(contact
702 .getAccount(), xmppConnectionService
703 .getPresenceGenerator()
704 .requestPresenceUpdatesFrom(contact));
705 }
706 });
707 builder.create().show();
708 }
709
710 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
711 quickEdit(previousValue, callback, hint, false, false);
712 }
713
714 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
715 quickEdit(previousValue, callback, hint, false, permitEmpty);
716 }
717
718 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
719 quickEdit(previousValue, callback, R.string.password, true, false);
720 }
721
722 @SuppressLint("InflateParams")
723 private void quickEdit(final String previousValue,
724 final OnValueEdited callback,
725 final @StringRes int hint,
726 boolean password,
727 boolean permitEmpty) {
728 AlertDialog.Builder builder = new AlertDialog.Builder(this);
729 DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_quickedit, null, false);
730 if (password) {
731 binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
732 }
733 builder.setPositiveButton(R.string.accept, null);
734 if (hint != 0) {
735 binding.inputLayout.setHint(getString(hint));
736 }
737 binding.inputEditText.requestFocus();
738 if (previousValue != null) {
739 binding.inputEditText.getText().append(previousValue);
740 }
741 builder.setView(binding.getRoot());
742 builder.setNegativeButton(R.string.cancel, null);
743 final AlertDialog dialog = builder.create();
744 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
745 dialog.show();
746 View.OnClickListener clickListener = v -> {
747 String value = binding.inputEditText.getText().toString();
748 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
749 String error = callback.onValueEdited(value);
750 if (error != null) {
751 binding.inputLayout.setError(error);
752 return;
753 }
754 }
755 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
756 dialog.dismiss();
757 };
758 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
759 dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
760 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
761 dialog.dismiss();
762 }));
763 dialog.setCanceledOnTouchOutside(false);
764 dialog.setOnDismissListener(dialog1 -> {
765 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
766 });
767 }
768
769 protected boolean hasStoragePermission(int requestCode) {
770 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
771 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
772 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
773 return false;
774 } else {
775 return true;
776 }
777 } else {
778 return true;
779 }
780 }
781
782 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
783 super.onActivityResult(requestCode, resultCode, data);
784 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
785 mPendingConferenceInvite = ConferenceInvite.parse(data);
786 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
787 if (mPendingConferenceInvite.execute(this)) {
788 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
789 mToast.show();
790 }
791 mPendingConferenceInvite = null;
792 }
793 }
794 }
795
796 public boolean copyTextToClipboard(String text, int labelResId) {
797 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
798 String label = getResources().getString(labelResId);
799 if (mClipBoardManager != null) {
800 ClipData mClipData = ClipData.newPlainText(label, text);
801 mClipBoardManager.setPrimaryClip(mClipData);
802 return true;
803 }
804 return false;
805 }
806
807 protected boolean manuallyChangePresence() {
808 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
809 }
810
811 protected String getShareableUri() {
812 return getShareableUri(false);
813 }
814
815 protected String getShareableUri(boolean http) {
816 return null;
817 }
818
819 protected void shareLink(boolean http) {
820 String uri = getShareableUri(http);
821 if (uri == null || uri.isEmpty()) {
822 return;
823 }
824 Intent intent = new Intent(Intent.ACTION_SEND);
825 intent.setType("text/plain");
826 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
827 try {
828 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
829 } catch (ActivityNotFoundException e) {
830 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
831 }
832 }
833
834 protected void launchOpenKeyChain(long keyId) {
835 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
836 try {
837 startIntentSenderForResult(
838 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
839 0, 0);
840 } catch (Throwable e) {
841 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
842 }
843 }
844
845 @Override
846 protected void onResume(){
847 super.onResume();
848 SettingsUtils.applyScreenshotPreventionSetting(this);
849 }
850
851 protected int findTheme() {
852 return ThemeHelper.find(this);
853 }
854
855 @Override
856 public void onPause() {
857 super.onPause();
858 }
859
860 @Override
861 public boolean onMenuOpened(int id, Menu menu) {
862 if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
863 MenuDoubleTabUtil.recordMenuOpen();
864 }
865 return super.onMenuOpened(id, menu);
866 }
867
868 protected void showQrCode() {
869 showQrCode(getShareableUri());
870 }
871
872 protected void showQrCode(final String uri) {
873 if (uri == null || uri.isEmpty()) {
874 return;
875 }
876 Point size = new Point();
877 getWindowManager().getDefaultDisplay().getSize(size);
878 final int width = (size.x < size.y ? size.x : size.y);
879 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
880 ImageView view = new ImageView(this);
881 view.setBackgroundColor(Color.WHITE);
882 view.setImageBitmap(bitmap);
883 AlertDialog.Builder builder = new AlertDialog.Builder(this);
884 builder.setView(view);
885 builder.create().show();
886 }
887
888 protected Account extractAccount(Intent intent) {
889 final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
890 try {
891 return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
892 } catch (IllegalArgumentException e) {
893 return null;
894 }
895 }
896
897 public AvatarService avatarService() {
898 return xmppConnectionService.getAvatarService();
899 }
900
901 public void loadBitmap(Message message, ImageView imageView) {
902 Drawable bm;
903 try {
904 bm = xmppConnectionService.getFileBackend().getThumbnail(message, getResources(), (int) (metrics.density * 288), true);
905 } catch (IOException e) {
906 bm = null;
907 }
908 if (bm != null) {
909 cancelPotentialWork(message, imageView);
910 imageView.setImageDrawable(bm);
911 imageView.setBackgroundColor(0x00000000);
912 if (Build.VERSION.SDK_INT >= 28 && bm instanceof AnimatedImageDrawable) {
913 ((AnimatedImageDrawable) bm).start();
914 }
915 } else {
916 if (cancelPotentialWork(message, imageView)) {
917 imageView.setBackgroundColor(0xff333333);
918 imageView.setImageDrawable(null);
919 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
920 final BitmapDrawable fallbackThumb = xmppConnectionService.getFileBackend().getFallbackThumbnail(message, (int) (metrics.density * 288));
921 final AsyncDrawable asyncDrawable = new AsyncDrawable(
922 getResources(), fallbackThumb != null ? fallbackThumb.getBitmap() : null, task);
923 imageView.setImageDrawable(asyncDrawable);
924 try {
925 task.execute(message);
926 } catch (final RejectedExecutionException ignored) {
927 ignored.printStackTrace();
928 }
929 }
930 }
931 }
932
933 protected interface OnValueEdited {
934 String onValueEdited(String value);
935 }
936
937 public static class ConferenceInvite {
938 private String uuid;
939 private final List<Jid> jids = new ArrayList<>();
940
941 public static ConferenceInvite parse(Intent data) {
942 ConferenceInvite invite = new ConferenceInvite();
943 invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
944 if (invite.uuid == null) {
945 return null;
946 }
947 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
948 return invite;
949 }
950
951 public boolean execute(XmppActivity activity) {
952 XmppConnectionService service = activity.xmppConnectionService;
953 Conversation conversation = service.findConversationByUuid(this.uuid);
954 if (conversation == null) {
955 return false;
956 }
957 if (conversation.getMode() == Conversation.MODE_MULTI) {
958 for (Jid jid : jids) {
959 service.invite(conversation, jid);
960 }
961 return false;
962 } else {
963 jids.add(conversation.getJid().asBareJid());
964 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
965 }
966 }
967 }
968
969 static class BitmapWorkerTask extends AsyncTask<Message, Void, Drawable> {
970 private final WeakReference<ImageView> imageViewReference;
971 private Message message = null;
972
973 private BitmapWorkerTask(ImageView imageView) {
974 this.imageViewReference = new WeakReference<>(imageView);
975 }
976
977 @Override
978 protected Drawable doInBackground(Message... params) {
979 if (isCancelled()) {
980 return null;
981 }
982 message = params[0];
983 try {
984 final XmppActivity activity = find(imageViewReference);
985 if (activity != null && activity.xmppConnectionService != null) {
986 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, imageViewReference.get().getContext().getResources(), (int) (activity.metrics.density * 288), false);
987 } else {
988 return null;
989 }
990 } catch (IOException e) {
991 return null;
992 }
993 }
994
995 @Override
996 protected void onPostExecute(final Drawable drawable) {
997 if (!isCancelled()) {
998 final ImageView imageView = imageViewReference.get();
999 if (imageView != null) {
1000 Drawable old = imageView.getDrawable();
1001 if (drawable == null && old instanceof AsyncDrawable) {
1002 imageView.setImageDrawable(new BitmapDrawable(((AsyncDrawable) old).getBitmap()));
1003 } else {
1004 imageView.setImageDrawable(drawable);
1005 }
1006 imageView.setBackgroundColor(drawable == null ? 0xff333333 : 0x00000000);
1007 if (Build.VERSION.SDK_INT >= 28 && drawable instanceof AnimatedImageDrawable) {
1008 ((AnimatedImageDrawable) drawable).start();
1009 }
1010 }
1011 }
1012 }
1013 }
1014
1015 private static class AsyncDrawable extends BitmapDrawable {
1016 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1017
1018 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1019 super(res, bitmap);
1020 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1021 }
1022
1023 private BitmapWorkerTask getBitmapWorkerTask() {
1024 return bitmapWorkerTaskReference.get();
1025 }
1026 }
1027
1028 public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1029 final View view = viewWeakReference.get();
1030 return view == null ? null : find(view);
1031 }
1032
1033 public static XmppActivity find(@NonNull final View view) {
1034 Context context = view.getContext();
1035 while (context instanceof ContextWrapper) {
1036 if (context instanceof XmppActivity) {
1037 return (XmppActivity) context;
1038 }
1039 context = ((ContextWrapper) context).getBaseContext();
1040 }
1041 return null;
1042 }
1043}