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