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