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