XmppActivity.java

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