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