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