XmppActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.annotation.TargetApi;
   5import android.app.ActionBar;
   6import android.app.Activity;
   7import android.app.AlertDialog;
   8import android.app.AlertDialog.Builder;
   9import android.app.PendingIntent;
  10import android.content.ClipData;
  11import android.content.ClipboardManager;
  12import android.content.ComponentName;
  13import android.content.Context;
  14import android.content.DialogInterface;
  15import android.content.DialogInterface.OnClickListener;
  16import android.content.Intent;
  17import android.content.IntentSender.SendIntentException;
  18import android.content.ServiceConnection;
  19import android.content.SharedPreferences;
  20import android.content.pm.PackageManager;
  21import android.content.pm.ResolveInfo;
  22import android.content.res.Resources;
  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.Uri;
  29import android.nfc.NdefMessage;
  30import android.nfc.NdefRecord;
  31import android.nfc.NfcAdapter;
  32import android.nfc.NfcEvent;
  33import android.os.AsyncTask;
  34import android.os.Build;
  35import android.os.Bundle;
  36import android.os.Handler;
  37import android.os.IBinder;
  38import android.os.SystemClock;
  39import android.preference.PreferenceManager;
  40import android.text.InputType;
  41import android.util.DisplayMetrics;
  42import android.util.Log;
  43import android.view.MenuItem;
  44import android.view.View;
  45import android.view.inputmethod.InputMethodManager;
  46import android.widget.CompoundButton;
  47import android.widget.EditText;
  48import android.widget.ImageView;
  49import android.widget.LinearLayout;
  50import android.widget.TextView;
  51import android.widget.Toast;
  52
  53import com.google.zxing.BarcodeFormat;
  54import com.google.zxing.EncodeHintType;
  55import com.google.zxing.WriterException;
  56import com.google.zxing.common.BitMatrix;
  57import com.google.zxing.qrcode.QRCodeWriter;
  58import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  59
  60import net.java.otr4j.session.SessionID;
  61
  62import org.whispersystems.libaxolotl.IdentityKey;
  63
  64import java.io.FileNotFoundException;
  65import java.lang.ref.WeakReference;
  66import java.util.ArrayList;
  67import java.util.Hashtable;
  68import java.util.List;
  69import java.util.concurrent.RejectedExecutionException;
  70
  71import eu.siacs.conversations.Config;
  72import eu.siacs.conversations.R;
  73import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  74import eu.siacs.conversations.entities.Account;
  75import eu.siacs.conversations.entities.Contact;
  76import eu.siacs.conversations.entities.Conversation;
  77import eu.siacs.conversations.entities.Message;
  78import eu.siacs.conversations.entities.MucOptions;
  79import eu.siacs.conversations.entities.Presences;
  80import eu.siacs.conversations.services.AvatarService;
  81import eu.siacs.conversations.services.XmppConnectionService;
  82import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
  83import eu.siacs.conversations.ui.widget.Switch;
  84import eu.siacs.conversations.utils.CryptoHelper;
  85import eu.siacs.conversations.utils.ExceptionHelper;
  86import eu.siacs.conversations.xmpp.OnNewKeysAvailable;
  87import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  88import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  89import eu.siacs.conversations.xmpp.jid.Jid;
  90
  91public abstract class XmppActivity extends Activity {
  92
  93	protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
  94	protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
  95
  96	public XmppConnectionService xmppConnectionService;
  97	public boolean xmppConnectionServiceBound = false;
  98	protected boolean registeredListeners = false;
  99
 100	protected int mPrimaryTextColor;
 101	protected int mSecondaryTextColor;
 102	protected int mPrimaryBackgroundColor;
 103	protected int mSecondaryBackgroundColor;
 104	protected int mColorRed;
 105	protected int mColorOrange;
 106	protected int mColorGreen;
 107	protected int mPrimaryColor;
 108
 109	protected boolean mUseSubject = true;
 110
 111	private DisplayMetrics metrics;
 112	protected int mTheme;
 113	protected boolean mUsingEnterKey = false;
 114
 115	private long mLastUiRefresh = 0;
 116	private Handler mRefreshUiHandler = new Handler();
 117	private Runnable mRefreshUiRunnable = new Runnable() {
 118		@Override
 119		public void run() {
 120			mLastUiRefresh = SystemClock.elapsedRealtime();
 121			refreshUiReal();
 122		}
 123	};
 124
 125	protected ConferenceInvite mPendingConferenceInvite = null;
 126
 127
 128	protected void refreshUi() {
 129		final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
 130		if (diff > Config.REFRESH_UI_INTERVAL) {
 131			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 132			runOnUiThread(mRefreshUiRunnable);
 133		} else {
 134			final long next = Config.REFRESH_UI_INTERVAL - diff;
 135			mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
 136			mRefreshUiHandler.postDelayed(mRefreshUiRunnable,next);
 137		}
 138	}
 139
 140	protected void refreshUiReal() {
 141
 142	};
 143
 144	protected interface OnValueEdited {
 145		public void onValueEdited(String value);
 146	}
 147
 148	public interface OnPresenceSelected {
 149		public void onPresenceSelected();
 150	}
 151
 152	protected ServiceConnection mConnection = new ServiceConnection() {
 153
 154		@Override
 155		public void onServiceConnected(ComponentName className, IBinder service) {
 156			XmppConnectionBinder binder = (XmppConnectionBinder) service;
 157			xmppConnectionService = binder.getService();
 158			xmppConnectionServiceBound = true;
 159			if (!registeredListeners && shouldRegisterListeners()) {
 160				registerListeners();
 161				registeredListeners = true;
 162			}
 163			onBackendConnected();
 164		}
 165
 166		@Override
 167		public void onServiceDisconnected(ComponentName arg0) {
 168			xmppConnectionServiceBound = false;
 169		}
 170	};
 171
 172	@Override
 173	protected void onStart() {
 174		super.onStart();
 175		if (!xmppConnectionServiceBound) {
 176			connectToBackend();
 177		} else {
 178			if (!registeredListeners) {
 179				this.registerListeners();
 180				this.registeredListeners = true;
 181			}
 182			this.onBackendConnected();
 183		}
 184	}
 185
 186	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
 187	protected boolean shouldRegisterListeners() {
 188		if  (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
 189			return !isDestroyed() && !isFinishing();
 190		} else {
 191			return !isFinishing();
 192		}
 193	}
 194
 195	public void connectToBackend() {
 196		Intent intent = new Intent(this, XmppConnectionService.class);
 197		intent.setAction("ui");
 198		startService(intent);
 199		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 200	}
 201
 202	@Override
 203	protected void onStop() {
 204		super.onStop();
 205		if (xmppConnectionServiceBound) {
 206			if (registeredListeners) {
 207				this.unregisterListeners();
 208				this.registeredListeners = false;
 209			}
 210			unbindService(mConnection);
 211			xmppConnectionServiceBound = false;
 212		}
 213	}
 214
 215	protected void hideKeyboard() {
 216		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 217
 218		View focus = getCurrentFocus();
 219
 220		if (focus != null) {
 221
 222			inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
 223					InputMethodManager.HIDE_NOT_ALWAYS);
 224		}
 225	}
 226
 227	public boolean hasPgp() {
 228		return xmppConnectionService.getPgpEngine() != null;
 229	}
 230
 231	public void showInstallPgpDialog() {
 232		Builder builder = new AlertDialog.Builder(this);
 233		builder.setTitle(getString(R.string.openkeychain_required));
 234		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 235		builder.setMessage(getText(R.string.openkeychain_required_long));
 236		builder.setNegativeButton(getString(R.string.cancel), null);
 237		builder.setNeutralButton(getString(R.string.restart),
 238				new OnClickListener() {
 239
 240					@Override
 241					public void onClick(DialogInterface dialog, int which) {
 242						if (xmppConnectionServiceBound) {
 243							unbindService(mConnection);
 244							xmppConnectionServiceBound = false;
 245						}
 246						stopService(new Intent(XmppActivity.this,
 247									XmppConnectionService.class));
 248						finish();
 249					}
 250				});
 251		builder.setPositiveButton(getString(R.string.install),
 252				new OnClickListener() {
 253
 254					@Override
 255					public void onClick(DialogInterface dialog, int which) {
 256						Uri uri = Uri
 257							.parse("market://details?id=org.sufficientlysecure.keychain");
 258						Intent marketIntent = new Intent(Intent.ACTION_VIEW,
 259								uri);
 260						PackageManager manager = getApplicationContext()
 261							.getPackageManager();
 262						List<ResolveInfo> infos = manager
 263							.queryIntentActivities(marketIntent, 0);
 264						if (infos.size() > 0) {
 265							startActivity(marketIntent);
 266						} else {
 267							uri = Uri.parse("http://www.openkeychain.org/");
 268							Intent browserIntent = new Intent(
 269									Intent.ACTION_VIEW, uri);
 270							startActivity(browserIntent);
 271						}
 272						finish();
 273					}
 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.OnRosterUpdate) {
 288			this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
 289		}
 290		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 291			this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
 292		}
 293		if (this instanceof OnUpdateBlocklist) {
 294			this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
 295		}
 296		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 297			this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
 298		}
 299		if (this instanceof OnNewKeysAvailable) {
 300			this.xmppConnectionService.setOnNewKeysAvailableListener((OnNewKeysAvailable) this);
 301		}
 302	}
 303
 304	protected void unregisterListeners() {
 305		if (this instanceof XmppConnectionService.OnConversationUpdate) {
 306			this.xmppConnectionService.removeOnConversationListChangedListener();
 307		}
 308		if (this instanceof XmppConnectionService.OnAccountUpdate) {
 309			this.xmppConnectionService.removeOnAccountListChangedListener();
 310		}
 311		if (this instanceof XmppConnectionService.OnRosterUpdate) {
 312			this.xmppConnectionService.removeOnRosterUpdateListener();
 313		}
 314		if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
 315			this.xmppConnectionService.removeOnMucRosterUpdateListener();
 316		}
 317		if (this instanceof OnUpdateBlocklist) {
 318			this.xmppConnectionService.removeOnUpdateBlocklistListener();
 319		}
 320		if (this instanceof XmppConnectionService.OnShowErrorToast) {
 321			this.xmppConnectionService.removeOnShowErrorToastListener();
 322		}
 323		if (this instanceof OnNewKeysAvailable) {
 324			this.xmppConnectionService.removeOnNewKeysAvailableListener();
 325		}
 326	}
 327
 328	@Override
 329	public boolean onOptionsItemSelected(final MenuItem item) {
 330		switch (item.getItemId()) {
 331			case R.id.action_settings:
 332				startActivity(new Intent(this, SettingsActivity.class));
 333				break;
 334			case R.id.action_accounts:
 335				startActivity(new Intent(this, ManageAccountActivity.class));
 336				break;
 337			case android.R.id.home:
 338				finish();
 339				break;
 340			case R.id.action_show_qr_code:
 341				showQrCode();
 342				break;
 343		}
 344		return super.onOptionsItemSelected(item);
 345	}
 346
 347	@Override
 348	protected void onCreate(Bundle savedInstanceState) {
 349		super.onCreate(savedInstanceState);
 350		metrics = getResources().getDisplayMetrics();
 351		ExceptionHelper.init(getApplicationContext());
 352		mPrimaryTextColor = getResources().getColor(R.color.black87);
 353		mSecondaryTextColor = getResources().getColor(R.color.black54);
 354		mColorRed = getResources().getColor(R.color.red500);
 355		mColorOrange = getResources().getColor(R.color.orange500);
 356		mColorGreen = getResources().getColor(R.color.green500);
 357		mPrimaryColor = getResources().getColor(R.color.green500);
 358		mPrimaryBackgroundColor = getResources().getColor(R.color.grey50);
 359		mSecondaryBackgroundColor = getResources().getColor(R.color.grey200);
 360		this.mTheme = findTheme();
 361		setTheme(this.mTheme);
 362		this.mUsingEnterKey = usingEnterKey();
 363		mUseSubject = getPreferences().getBoolean("use_subject", true);
 364		final ActionBar ab = getActionBar();
 365		if (ab!=null) {
 366			ab.setDisplayHomeAsUpEnabled(true);
 367		}
 368	}
 369
 370	protected boolean usingEnterKey() {
 371		return getPreferences().getBoolean("display_enter_key", false);
 372	}
 373
 374	protected SharedPreferences getPreferences() {
 375		return PreferenceManager
 376			.getDefaultSharedPreferences(getApplicationContext());
 377	}
 378
 379	public boolean useSubjectToIdentifyConference() {
 380		return mUseSubject;
 381	}
 382
 383	public void switchToConversation(Conversation conversation) {
 384		switchToConversation(conversation, null, false);
 385	}
 386
 387	public void switchToConversation(Conversation conversation, String text,
 388			boolean newTask) {
 389		switchToConversation(conversation,text,null,newTask);
 390	}
 391
 392	public void highlightInMuc(Conversation conversation, String nick) {
 393		switchToConversation(conversation, null, nick, false);
 394	}
 395
 396	private void switchToConversation(Conversation conversation, String text, String nick, boolean newTask) {
 397		Intent viewConversationIntent = new Intent(this,
 398				ConversationActivity.class);
 399		viewConversationIntent.setAction(Intent.ACTION_VIEW);
 400		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
 401				conversation.getUuid());
 402		if (text != null) {
 403			viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
 404		}
 405		if (nick != null) {
 406			viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
 407		}
 408		viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
 409		if (newTask) {
 410			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 411					| Intent.FLAG_ACTIVITY_NEW_TASK
 412					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
 413		} else {
 414			viewConversationIntent.setFlags(viewConversationIntent.getFlags()
 415					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
 416		}
 417		startActivity(viewConversationIntent);
 418		finish();
 419	}
 420
 421	public void switchToContactDetails(Contact contact) {
 422		Intent intent = new Intent(this, ContactDetailsActivity.class);
 423		intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
 424		intent.putExtra("account", contact.getAccount().getJid().toBareJid().toString());
 425		intent.putExtra("contact", contact.getJid().toString());
 426		startActivity(intent);
 427	}
 428
 429	public void switchToAccount(Account account) {
 430		Intent intent = new Intent(this, EditAccountActivity.class);
 431		intent.putExtra("jid", account.getJid().toBareJid().toString());
 432		startActivity(intent);
 433	}
 434
 435	protected void inviteToConversation(Conversation conversation) {
 436		Intent intent = new Intent(getApplicationContext(),
 437				ChooseContactActivity.class);
 438		List<String> contacts = new ArrayList<>();
 439		if (conversation.getMode() == Conversation.MODE_MULTI) {
 440			for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
 441				Jid jid = user.getJid();
 442				if (jid != null) {
 443					contacts.add(jid.toBareJid().toString());
 444				}
 445			}
 446		} else {
 447			contacts.add(conversation.getJid().toBareJid().toString());
 448		}
 449		intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
 450		intent.putExtra("conversation", conversation.getUuid());
 451		intent.putExtra("multiple", true);
 452		startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
 453	}
 454
 455	protected void announcePgp(Account account, final Conversation conversation) {
 456		xmppConnectionService.getPgpEngine().generateSignature(account,
 457				"online", new UiCallback<Account>() {
 458
 459					@Override
 460					public void userInputRequried(PendingIntent pi,
 461					                              Account account) {
 462						try {
 463							startIntentSenderForResult(pi.getIntentSender(),
 464									REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
 465						} catch (final SendIntentException ignored) {
 466						}
 467					}
 468
 469					@Override
 470					public void success(Account account) {
 471						xmppConnectionService.databaseBackend.updateAccount(account);
 472						xmppConnectionService.sendPresence(account);
 473						if (conversation != null) {
 474							conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 475							xmppConnectionService.databaseBackend.updateConversation(conversation);
 476						}
 477					}
 478
 479					@Override
 480					public void error(int error, Account account) {
 481						displayErrorDialog(error);
 482					}
 483				});
 484	}
 485
 486	protected void displayErrorDialog(final int errorCode) {
 487		runOnUiThread(new Runnable() {
 488
 489			@Override
 490			public void run() {
 491				AlertDialog.Builder builder = new AlertDialog.Builder(
 492						XmppActivity.this);
 493				builder.setIconAttribute(android.R.attr.alertDialogIcon);
 494				builder.setTitle(getString(R.string.error));
 495				builder.setMessage(errorCode);
 496				builder.setNeutralButton(R.string.accept, null);
 497				builder.create().show();
 498			}
 499		});
 500
 501	}
 502
 503	protected void showAddToRosterDialog(final Conversation conversation) {
 504		showAddToRosterDialog(conversation.getContact());
 505	}
 506
 507	protected void showAddToRosterDialog(final Contact contact) {
 508		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 509		builder.setTitle(contact.getJid().toString());
 510		builder.setMessage(getString(R.string.not_in_roster));
 511		builder.setNegativeButton(getString(R.string.cancel), null);
 512		builder.setPositiveButton(getString(R.string.add_contact),
 513				new DialogInterface.OnClickListener() {
 514
 515					@Override
 516					public void onClick(DialogInterface dialog, int which) {
 517						final Jid jid = contact.getJid();
 518						Account account = contact.getAccount();
 519						Contact contact = account.getRoster().getContact(jid);
 520						xmppConnectionService.createContact(contact);
 521					}
 522				});
 523		builder.create().show();
 524	}
 525
 526	private void showAskForPresenceDialog(final Contact contact) {
 527		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 528		builder.setTitle(contact.getJid().toString());
 529		builder.setMessage(R.string.request_presence_updates);
 530		builder.setNegativeButton(R.string.cancel, null);
 531		builder.setPositiveButton(R.string.request_now,
 532				new DialogInterface.OnClickListener() {
 533
 534					@Override
 535					public void onClick(DialogInterface dialog, int which) {
 536						if (xmppConnectionServiceBound) {
 537							xmppConnectionService.sendPresencePacket(contact
 538									.getAccount(), xmppConnectionService
 539									.getPresenceGenerator()
 540									.requestPresenceUpdatesFrom(contact));
 541						}
 542					}
 543				});
 544		builder.create().show();
 545	}
 546
 547	private void warnMutalPresenceSubscription(final Conversation conversation,
 548			final OnPresenceSelected listener) {
 549		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 550		builder.setTitle(conversation.getContact().getJid().toString());
 551		builder.setMessage(R.string.without_mutual_presence_updates);
 552		builder.setNegativeButton(R.string.cancel, null);
 553		builder.setPositiveButton(R.string.ignore, new OnClickListener() {
 554
 555			@Override
 556			public void onClick(DialogInterface dialog, int which) {
 557				conversation.setNextCounterpart(null);
 558				if (listener != null) {
 559					listener.onPresenceSelected();
 560				}
 561			}
 562		});
 563		builder.create().show();
 564	}
 565
 566	protected void quickEdit(String previousValue, OnValueEdited callback) {
 567		quickEdit(previousValue, callback, false);
 568	}
 569
 570	protected void quickPasswordEdit(String previousValue,
 571			OnValueEdited callback) {
 572		quickEdit(previousValue, callback, true);
 573	}
 574
 575	@SuppressLint("InflateParams")
 576	private void quickEdit(final String previousValue,
 577			final OnValueEdited callback, boolean password) {
 578		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 579		View view = getLayoutInflater().inflate(R.layout.quickedit, null);
 580		final EditText editor = (EditText) view.findViewById(R.id.editor);
 581		OnClickListener mClickListener = new OnClickListener() {
 582
 583			@Override
 584			public void onClick(DialogInterface dialog, int which) {
 585				String value = editor.getText().toString();
 586				if (!previousValue.equals(value) && value.trim().length() > 0) {
 587					callback.onValueEdited(value);
 588				}
 589			}
 590		};
 591		if (password) {
 592			editor.setInputType(InputType.TYPE_CLASS_TEXT
 593					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
 594			editor.setHint(R.string.password);
 595			builder.setPositiveButton(R.string.accept, mClickListener);
 596		} else {
 597			builder.setPositiveButton(R.string.edit, mClickListener);
 598		}
 599		editor.requestFocus();
 600		editor.setText(previousValue);
 601		builder.setView(view);
 602		builder.setNegativeButton(R.string.cancel, null);
 603		builder.create().show();
 604	}
 605
 606	protected void addFingerprintRow(LinearLayout keys, final Account account, IdentityKey identityKey) {
 607		final String fingerprint = identityKey.getFingerprint().replaceAll("\\s", "");
 608		final AxolotlService.SQLiteAxolotlStore.Trust trust = account.getAxolotlService()
 609				.getFingerprintTrust(fingerprint);
 610		addFingerprintRowWithListeners(keys, account, identityKey, trust, true,
 611				new CompoundButton.OnCheckedChangeListener() {
 612					@Override
 613					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 614						if (isChecked != (trust == AxolotlService.SQLiteAxolotlStore.Trust.TRUSTED)) {
 615							account.getAxolotlService().setFingerprintTrust(fingerprint,
 616									(isChecked) ? AxolotlService.SQLiteAxolotlStore.Trust.TRUSTED :
 617											AxolotlService.SQLiteAxolotlStore.Trust.UNTRUSTED);
 618						}
 619						refreshUi();
 620						xmppConnectionService.updateAccountUi();
 621						xmppConnectionService.updateConversationUi();
 622					}
 623				},
 624				new View.OnClickListener() {
 625					@Override
 626					public void onClick(View v) {
 627						account.getAxolotlService().setFingerprintTrust(fingerprint,
 628								AxolotlService.SQLiteAxolotlStore.Trust.UNTRUSTED);
 629						refreshUi();
 630						xmppConnectionService.updateAccountUi();
 631						xmppConnectionService.updateConversationUi();
 632					}
 633				}
 634
 635		);
 636	}
 637
 638	protected void addFingerprintRowWithListeners(LinearLayout keys, final Account account,
 639	                                              IdentityKey identityKey,
 640	                                              AxolotlService.SQLiteAxolotlStore.Trust trust,
 641	                                              boolean showTag,
 642	                                              CompoundButton.OnCheckedChangeListener
 643			                                             onCheckedChangeListener,
 644	                                              View.OnClickListener onClickListener) {
 645		View view = getLayoutInflater().inflate(R.layout.contact_key, keys, false);
 646		TextView key = (TextView) view.findViewById(R.id.key);
 647		TextView keyType = (TextView) view.findViewById(R.id.key_type);
 648		Switch trustToggle = (Switch) view.findViewById(R.id.tgl_trust);
 649		trustToggle.setVisibility(View.VISIBLE);
 650		trustToggle.setOnCheckedChangeListener(onCheckedChangeListener);
 651		trustToggle.setOnClickListener(onClickListener);
 652
 653		switch (trust) {
 654			case UNTRUSTED:
 655			case TRUSTED:
 656				trustToggle.setChecked(trust == AxolotlService.SQLiteAxolotlStore.Trust.TRUSTED, false);
 657				trustToggle.setEnabled(true);
 658				break;
 659			case UNDECIDED:
 660				trustToggle.setChecked(false, false);
 661				trustToggle.setEnabled(false);
 662				break;
 663		}
 664
 665		if (showTag) {
 666			keyType.setText(getString(R.string.axolotl_fingerprint));
 667		} else {
 668			keyType.setVisibility(View.GONE);
 669		}
 670
 671		key.setText(CryptoHelper.prettifyFingerprint(identityKey.getFingerprint()));
 672		keys.addView(view);
 673
 674	}
 675
 676	public void selectPresence(final Conversation conversation,
 677			final OnPresenceSelected listener) {
 678		final Contact contact = conversation.getContact();
 679		if (conversation.hasValidOtrSession()) {
 680			SessionID id = conversation.getOtrSession().getSessionID();
 681			Jid jid;
 682			try {
 683				jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
 684			} catch (InvalidJidException e) {
 685				jid = null;
 686			}
 687			conversation.setNextCounterpart(jid);
 688			listener.onPresenceSelected();
 689		} else 	if (!contact.showInRoster()) {
 690			showAddToRosterDialog(conversation);
 691		} else {
 692			Presences presences = contact.getPresences();
 693			if (presences.size() == 0) {
 694				if (!contact.getOption(Contact.Options.TO)
 695						&& !contact.getOption(Contact.Options.ASKING)
 696						&& contact.getAccount().getStatus() == Account.State.ONLINE) {
 697					showAskForPresenceDialog(contact);
 698				} else if (!contact.getOption(Contact.Options.TO)
 699						|| !contact.getOption(Contact.Options.FROM)) {
 700					warnMutalPresenceSubscription(conversation, listener);
 701				} else {
 702					conversation.setNextCounterpart(null);
 703					listener.onPresenceSelected();
 704				}
 705			} else if (presences.size() == 1) {
 706				String presence = presences.asStringArray()[0];
 707				try {
 708					conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
 709				} catch (InvalidJidException e) {
 710					conversation.setNextCounterpart(null);
 711				}
 712				listener.onPresenceSelected();
 713			} else {
 714				final StringBuilder presence = new StringBuilder();
 715				AlertDialog.Builder builder = new AlertDialog.Builder(this);
 716				builder.setTitle(getString(R.string.choose_presence));
 717				final String[] presencesArray = presences.asStringArray();
 718				int preselectedPresence = 0;
 719				for (int i = 0; i < presencesArray.length; ++i) {
 720					if (presencesArray[i].equals(contact.lastseen.presence)) {
 721						preselectedPresence = i;
 722						break;
 723					}
 724				}
 725				presence.append(presencesArray[preselectedPresence]);
 726				builder.setSingleChoiceItems(presencesArray,
 727						preselectedPresence,
 728						new DialogInterface.OnClickListener() {
 729
 730							@Override
 731							public void onClick(DialogInterface dialog,
 732									int which) {
 733								presence.delete(0, presence.length());
 734								presence.append(presencesArray[which]);
 735							}
 736						});
 737				builder.setNegativeButton(R.string.cancel, null);
 738				builder.setPositiveButton(R.string.ok, new OnClickListener() {
 739
 740					@Override
 741					public void onClick(DialogInterface dialog, int which) {
 742						try {
 743							conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence.toString()));
 744						} catch (InvalidJidException e) {
 745							conversation.setNextCounterpart(null);
 746						}
 747						listener.onPresenceSelected();
 748					}
 749				});
 750				builder.create().show();
 751			}
 752		}
 753	}
 754
 755	protected void onActivityResult(int requestCode, int resultCode,
 756			final Intent data) {
 757		super.onActivityResult(requestCode, resultCode, data);
 758		if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
 759			mPendingConferenceInvite = ConferenceInvite.parse(data);
 760			if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
 761				mPendingConferenceInvite.execute(this);
 762				mPendingConferenceInvite = null;
 763			}
 764		}
 765	}
 766
 767	private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
 768		@Override
 769		public void success(final Conversation conversation) {
 770			switchToConversation(conversation);
 771			runOnUiThread(new Runnable() {
 772				@Override
 773				public void run() {
 774					Toast.makeText(XmppActivity.this,R.string.conference_created,Toast.LENGTH_LONG).show();
 775				}
 776			});
 777		}
 778
 779		@Override
 780		public void error(final int errorCode, Conversation object) {
 781			runOnUiThread(new Runnable() {
 782				@Override
 783				public void run() {
 784					Toast.makeText(XmppActivity.this,errorCode,Toast.LENGTH_LONG).show();
 785				}
 786			});
 787		}
 788
 789		@Override
 790		public void userInputRequried(PendingIntent pi, Conversation object) {
 791
 792		}
 793	};
 794
 795	public int getSecondaryTextColor() {
 796		return this.mSecondaryTextColor;
 797	}
 798
 799	public int getPrimaryTextColor() {
 800		return this.mPrimaryTextColor;
 801	}
 802
 803	public int getWarningTextColor() {
 804		return this.mColorRed;
 805	}
 806
 807	public int getOnlineColor() {
 808		return this.mColorGreen;
 809	}
 810
 811	public int getPrimaryBackgroundColor() {
 812		return this.mPrimaryBackgroundColor;
 813	}
 814
 815	public int getSecondaryBackgroundColor() {
 816		return this.mSecondaryBackgroundColor;
 817	}
 818
 819	public int getPixel(int dp) {
 820		DisplayMetrics metrics = getResources().getDisplayMetrics();
 821		return ((int) (dp * metrics.density));
 822	}
 823
 824	public boolean copyTextToClipboard(String text, int labelResId) {
 825		ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
 826		String label = getResources().getString(labelResId);
 827		if (mClipBoardManager != null) {
 828			ClipData mClipData = ClipData.newPlainText(label, text);
 829			mClipBoardManager.setPrimaryClip(mClipData);
 830			return true;
 831		}
 832		return false;
 833	}
 834
 835	protected void registerNdefPushMessageCallback() {
 836		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 837		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 838			nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
 839				@Override
 840				public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
 841					return new NdefMessage(new NdefRecord[]{
 842						NdefRecord.createUri(getShareableUri()),
 843							NdefRecord.createApplicationRecord("eu.siacs.conversations")
 844					});
 845				}
 846			}, this);
 847		}
 848	}
 849
 850	protected void unregisterNdefPushMessageCallback() {
 851		NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
 852		if (nfcAdapter != null && nfcAdapter.isEnabled()) {
 853			nfcAdapter.setNdefPushMessageCallback(null,this);
 854		}
 855	}
 856
 857	protected String getShareableUri() {
 858		return null;
 859	}
 860
 861	@Override
 862	public void onResume() {
 863		super.onResume();
 864		if (this.getShareableUri()!=null) {
 865			this.registerNdefPushMessageCallback();
 866		}
 867	}
 868
 869	protected int findTheme() {
 870		if (getPreferences().getBoolean("use_larger_font", false)) {
 871			return R.style.ConversationsTheme_LargerText;
 872		} else {
 873			return R.style.ConversationsTheme;
 874		}
 875	}
 876
 877	@Override
 878	public void onPause() {
 879		super.onPause();
 880		this.unregisterNdefPushMessageCallback();
 881	}
 882
 883	protected void showQrCode() {
 884		String uri = getShareableUri();
 885		if (uri!=null) {
 886			Point size = new Point();
 887			getWindowManager().getDefaultDisplay().getSize(size);
 888			final int width = (size.x < size.y ? size.x : size.y);
 889			Bitmap bitmap = createQrCodeBitmap(uri, width);
 890			ImageView view = new ImageView(this);
 891			view.setImageBitmap(bitmap);
 892			AlertDialog.Builder builder = new AlertDialog.Builder(this);
 893			builder.setView(view);
 894			builder.create().show();
 895		}
 896	}
 897
 898	protected Bitmap createQrCodeBitmap(String input, int size) {
 899		Log.d(Config.LOGTAG,"qr code requested size: "+size);
 900		try {
 901			final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
 902			final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
 903			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
 904			final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
 905			final int width = result.getWidth();
 906			final int height = result.getHeight();
 907			final int[] pixels = new int[width * height];
 908			for (int y = 0; y < height; y++) {
 909				final int offset = y * width;
 910				for (int x = 0; x < width; x++) {
 911					pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
 912				}
 913			}
 914			final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
 915			Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
 916			bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
 917			return bitmap;
 918		} catch (final WriterException e) {
 919			return null;
 920		}
 921	}
 922
 923	public static class ConferenceInvite {
 924		private String uuid;
 925		private List<Jid> jids = new ArrayList<>();
 926
 927		public static ConferenceInvite parse(Intent data) {
 928			ConferenceInvite invite = new ConferenceInvite();
 929			invite.uuid = data.getStringExtra("conversation");
 930			if (invite.uuid == null) {
 931				return null;
 932			}
 933			try {
 934				if (data.getBooleanExtra("multiple", false)) {
 935					String[] toAdd = data.getStringArrayExtra("contacts");
 936					for (String item : toAdd) {
 937						invite.jids.add(Jid.fromString(item));
 938					}
 939				} else {
 940					invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
 941				}
 942			} catch (final InvalidJidException ignored) {
 943				return null;
 944			}
 945			return invite;
 946		}
 947
 948		public void execute(XmppActivity activity) {
 949			XmppConnectionService service = activity.xmppConnectionService;
 950			Conversation conversation = service.findConversationByUuid(this.uuid);
 951			if (conversation == null) {
 952				return;
 953			}
 954			if (conversation.getMode() == Conversation.MODE_MULTI) {
 955				for (Jid jid : jids) {
 956					service.invite(conversation, jid);
 957				}
 958			} else {
 959				jids.add(conversation.getJid().toBareJid());
 960				service.createAdhocConference(conversation.getAccount(), jids, activity.adhocCallback);
 961			}
 962		}
 963	}
 964
 965	public AvatarService avatarService() {
 966		return xmppConnectionService.getAvatarService();
 967	}
 968
 969	class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
 970		private final WeakReference<ImageView> imageViewReference;
 971		private Message message = null;
 972
 973		public BitmapWorkerTask(ImageView imageView) {
 974			imageViewReference = new WeakReference<>(imageView);
 975		}
 976
 977		@Override
 978		protected Bitmap doInBackground(Message... params) {
 979			message = params[0];
 980			try {
 981				return xmppConnectionService.getFileBackend().getThumbnail(
 982						message, (int) (metrics.density * 288), false);
 983			} catch (FileNotFoundException e) {
 984				return null;
 985			}
 986		}
 987
 988		@Override
 989		protected void onPostExecute(Bitmap bitmap) {
 990			if (bitmap != null) {
 991				final ImageView imageView = imageViewReference.get();
 992				if (imageView != null) {
 993					imageView.setImageBitmap(bitmap);
 994					imageView.setBackgroundColor(0x00000000);
 995				}
 996			}
 997		}
 998	}
 999
1000	public void loadBitmap(Message message, ImageView imageView) {
1001		Bitmap bm;
1002		try {
1003			bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1004					(int) (metrics.density * 288), true);
1005		} catch (FileNotFoundException e) {
1006			bm = null;
1007		}
1008		if (bm != null) {
1009			imageView.setImageBitmap(bm);
1010			imageView.setBackgroundColor(0x00000000);
1011		} else {
1012			if (cancelPotentialWork(message, imageView)) {
1013				imageView.setBackgroundColor(0xff333333);
1014				final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1015				final AsyncDrawable asyncDrawable = new AsyncDrawable(
1016						getResources(), null, task);
1017				imageView.setImageDrawable(asyncDrawable);
1018				try {
1019					task.execute(message);
1020				} catch (final RejectedExecutionException ignored) {
1021				}
1022			}
1023		}
1024	}
1025
1026	public static boolean cancelPotentialWork(Message message,
1027			ImageView imageView) {
1028		final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1029
1030		if (bitmapWorkerTask != null) {
1031			final Message oldMessage = bitmapWorkerTask.message;
1032			if (oldMessage == null || message != oldMessage) {
1033				bitmapWorkerTask.cancel(true);
1034			} else {
1035				return false;
1036			}
1037		}
1038		return true;
1039	}
1040
1041	private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1042		if (imageView != null) {
1043			final Drawable drawable = imageView.getDrawable();
1044			if (drawable instanceof AsyncDrawable) {
1045				final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1046				return asyncDrawable.getBitmapWorkerTask();
1047			}
1048		}
1049		return null;
1050	}
1051
1052	static class AsyncDrawable extends BitmapDrawable {
1053		private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1054
1055		public AsyncDrawable(Resources res, Bitmap bitmap,
1056				BitmapWorkerTask bitmapWorkerTask) {
1057			super(res, bitmap);
1058			bitmapWorkerTaskReference = new WeakReference<>(
1059					bitmapWorkerTask);
1060		}
1061
1062		public BitmapWorkerTask getBitmapWorkerTask() {
1063			return bitmapWorkerTaskReference.get();
1064		}
1065	}
1066}