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 @SuppressLint("InflateParams")
726 private void quickEdit(final String previousValue,
727 final OnValueEdited callback,
728 final @StringRes int hint,
729 boolean password,
730 boolean permitEmpty) {
731 AlertDialog.Builder builder = new AlertDialog.Builder(this);
732 DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_quickedit, null, false);
733 if (password) {
734 binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
735 }
736 builder.setPositiveButton(R.string.accept, null);
737 if (hint != 0) {
738 binding.inputLayout.setHint(getString(hint));
739 }
740 binding.inputEditText.requestFocus();
741 if (previousValue != null) {
742 binding.inputEditText.getText().append(previousValue);
743 }
744 builder.setView(binding.getRoot());
745 builder.setNegativeButton(R.string.cancel, null);
746 final AlertDialog dialog = builder.create();
747 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
748 dialog.show();
749 View.OnClickListener clickListener = v -> {
750 String value = binding.inputEditText.getText().toString();
751 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
752 String error = callback.onValueEdited(value);
753 if (error != null) {
754 binding.inputLayout.setError(error);
755 return;
756 }
757 }
758 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
759 dialog.dismiss();
760 };
761 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
762 dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
763 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
764 dialog.dismiss();
765 }));
766 dialog.setCanceledOnTouchOutside(false);
767 dialog.setOnDismissListener(dialog1 -> {
768 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
769 });
770 }
771
772 protected boolean hasStoragePermission(int requestCode) {
773 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
774 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
775 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
776 return false;
777 } else {
778 return true;
779 }
780 } else {
781 return true;
782 }
783 }
784
785 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
786 super.onActivityResult(requestCode, resultCode, data);
787 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
788 mPendingConferenceInvite = ConferenceInvite.parse(data);
789 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
790 if (mPendingConferenceInvite.execute(this)) {
791 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
792 mToast.show();
793 }
794 mPendingConferenceInvite = null;
795 }
796 }
797 }
798
799 public boolean copyTextToClipboard(String text, int labelResId) {
800 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
801 String label = getResources().getString(labelResId);
802 if (mClipBoardManager != null) {
803 ClipData mClipData = ClipData.newPlainText(label, text);
804 mClipBoardManager.setPrimaryClip(mClipData);
805 return true;
806 }
807 return false;
808 }
809
810 protected boolean manuallyChangePresence() {
811 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
812 }
813
814 protected String getShareableUri() {
815 return getShareableUri(false);
816 }
817
818 protected String getShareableUri(boolean http) {
819 return null;
820 }
821
822 protected void shareLink(boolean http) {
823 String uri = getShareableUri(http);
824 if (uri == null || uri.isEmpty()) {
825 return;
826 }
827 Intent intent = new Intent(Intent.ACTION_SEND);
828 intent.setType("text/plain");
829 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
830 try {
831 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
832 } catch (ActivityNotFoundException e) {
833 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
834 }
835 }
836
837 protected void launchOpenKeyChain(long keyId) {
838 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
839 try {
840 startIntentSenderForResult(
841 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
842 0, 0);
843 } catch (Throwable e) {
844 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
845 }
846 }
847
848 @Override
849 protected void onResume(){
850 super.onResume();
851 SettingsUtils.applyScreenshotPreventionSetting(this);
852 }
853
854 protected int findTheme() {
855 return ThemeHelper.find(this);
856 }
857
858 @Override
859 public void onPause() {
860 super.onPause();
861 }
862
863 @Override
864 public boolean onMenuOpened(int id, Menu menu) {
865 if (id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
866 MenuDoubleTabUtil.recordMenuOpen();
867 }
868 return super.onMenuOpened(id, menu);
869 }
870
871 protected void showQrCode() {
872 showQrCode(getShareableUri());
873 }
874
875 protected void showQrCode(final String uri) {
876 if (uri == null || uri.isEmpty()) {
877 return;
878 }
879 Point size = new Point();
880 getWindowManager().getDefaultDisplay().getSize(size);
881 final int width = (size.x < size.y ? size.x : size.y);
882 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
883 ImageView view = new ImageView(this);
884 view.setBackgroundColor(Color.WHITE);
885 view.setImageBitmap(bitmap);
886 AlertDialog.Builder builder = new AlertDialog.Builder(this);
887 builder.setView(view);
888 builder.create().show();
889 }
890
891 protected Account extractAccount(Intent intent) {
892 final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
893 try {
894 return jid != null ? xmppConnectionService.findAccountByJid(Jid.ofEscaped(jid)) : null;
895 } catch (IllegalArgumentException e) {
896 return null;
897 }
898 }
899
900 public AvatarService avatarService() {
901 return xmppConnectionService.getAvatarService();
902 }
903
904 public void loadBitmap(Message message, ImageView imageView) {
905 Drawable bm;
906 try {
907 bm = xmppConnectionService.getFileBackend().getThumbnail(message, getResources(), (int) (metrics.density * 288), true);
908 } catch (IOException e) {
909 bm = null;
910 }
911 if (bm != null) {
912 cancelPotentialWork(message, imageView);
913 imageView.setImageDrawable(bm);
914 imageView.setBackgroundColor(0x00000000);
915 if (Build.VERSION.SDK_INT >= 28 && bm instanceof AnimatedImageDrawable) {
916 ((AnimatedImageDrawable) bm).start();
917 }
918 } else {
919 if (cancelPotentialWork(message, imageView)) {
920 imageView.setBackgroundColor(0xff333333);
921 imageView.setImageDrawable(null);
922 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
923 final BitmapDrawable fallbackThumb = xmppConnectionService.getFileBackend().getFallbackThumbnail(message, (int) (metrics.density * 288));
924 final AsyncDrawable asyncDrawable = new AsyncDrawable(
925 getResources(), fallbackThumb != null ? fallbackThumb.getBitmap() : null, task);
926 imageView.setImageDrawable(asyncDrawable);
927 try {
928 task.execute(message);
929 } catch (final RejectedExecutionException ignored) {
930 ignored.printStackTrace();
931 }
932 }
933 }
934 }
935
936 protected interface OnValueEdited {
937 String onValueEdited(String value);
938 }
939
940 public static class ConferenceInvite {
941 private String uuid;
942 private final List<Jid> jids = new ArrayList<>();
943
944 public static ConferenceInvite parse(Intent data) {
945 ConferenceInvite invite = new ConferenceInvite();
946 invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
947 if (invite.uuid == null) {
948 return null;
949 }
950 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
951 return invite;
952 }
953
954 public boolean execute(XmppActivity activity) {
955 XmppConnectionService service = activity.xmppConnectionService;
956 Conversation conversation = service.findConversationByUuid(this.uuid);
957 if (conversation == null) {
958 return false;
959 }
960 if (conversation.getMode() == Conversation.MODE_MULTI) {
961 for (Jid jid : jids) {
962 service.invite(conversation, jid);
963 }
964 return false;
965 } else {
966 jids.add(conversation.getJid().asBareJid());
967 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
968 }
969 }
970 }
971
972 static class BitmapWorkerTask extends AsyncTask<Message, Void, Drawable> {
973 private final WeakReference<ImageView> imageViewReference;
974 private Message message = null;
975
976 private BitmapWorkerTask(ImageView imageView) {
977 this.imageViewReference = new WeakReference<>(imageView);
978 }
979
980 @Override
981 protected Drawable doInBackground(Message... params) {
982 if (isCancelled()) {
983 return null;
984 }
985 message = params[0];
986 try {
987 final XmppActivity activity = find(imageViewReference);
988 if (activity != null && activity.xmppConnectionService != null) {
989 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, imageViewReference.get().getContext().getResources(), (int) (activity.metrics.density * 288), false);
990 } else {
991 return null;
992 }
993 } catch (IOException e) {
994 return null;
995 }
996 }
997
998 @Override
999 protected void onPostExecute(final Drawable drawable) {
1000 if (!isCancelled()) {
1001 final ImageView imageView = imageViewReference.get();
1002 if (imageView != null) {
1003 Drawable old = imageView.getDrawable();
1004 if (drawable == null && old instanceof AsyncDrawable) {
1005 imageView.setImageDrawable(new BitmapDrawable(((AsyncDrawable) old).getBitmap()));
1006 } else {
1007 imageView.setImageDrawable(drawable);
1008 }
1009 imageView.setBackgroundColor(drawable == null ? 0xff333333 : 0x00000000);
1010 if (Build.VERSION.SDK_INT >= 28 && drawable instanceof AnimatedImageDrawable) {
1011 ((AnimatedImageDrawable) drawable).start();
1012 }
1013 }
1014 }
1015 }
1016 }
1017
1018 private static class AsyncDrawable extends BitmapDrawable {
1019 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1020
1021 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1022 super(res, bitmap);
1023 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1024 }
1025
1026 private BitmapWorkerTask getBitmapWorkerTask() {
1027 return bitmapWorkerTaskReference.get();
1028 }
1029 }
1030
1031 public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
1032 final View view = viewWeakReference.get();
1033 return view == null ? null : find(view);
1034 }
1035
1036 public static XmppActivity find(@NonNull final View view) {
1037 Context context = view.getContext();
1038 while (context instanceof ContextWrapper) {
1039 if (context instanceof XmppActivity) {
1040 return (XmppActivity) context;
1041 }
1042 context = ((ContextWrapper) context).getBaseContext();
1043 }
1044 return null;
1045 }
1046}