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