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