XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.annotation.SuppressLint;
   4import android.app.AlarmManager;
   5import android.app.PendingIntent;
   6import android.app.Service;
   7import android.content.Context;
   8import android.content.Intent;
   9import android.content.IntentFilter;
  10import android.content.SharedPreferences;
  11import android.database.ContentObserver;
  12import android.graphics.Bitmap;
  13import android.media.AudioManager;
  14import android.net.ConnectivityManager;
  15import android.net.NetworkInfo;
  16import android.net.Uri;
  17import android.os.Binder;
  18import android.os.Build;
  19import android.os.Bundle;
  20import android.os.FileObserver;
  21import android.os.IBinder;
  22import android.os.Looper;
  23import android.os.PowerManager;
  24import android.os.PowerManager.WakeLock;
  25import android.os.SystemClock;
  26import android.preference.PreferenceManager;
  27import android.provider.ContactsContract;
  28import android.security.KeyChain;
  29import android.util.DisplayMetrics;
  30import android.util.Log;
  31import android.util.LruCache;
  32import android.util.Pair;
  33
  34import net.java.otr4j.OtrException;
  35import net.java.otr4j.session.Session;
  36import net.java.otr4j.session.SessionID;
  37import net.java.otr4j.session.SessionImpl;
  38import net.java.otr4j.session.SessionStatus;
  39
  40import org.openintents.openpgp.util.OpenPgpApi;
  41import org.openintents.openpgp.util.OpenPgpServiceConnection;
  42
  43import java.math.BigInteger;
  44import java.security.SecureRandom;
  45import java.security.cert.CertificateException;
  46import java.security.cert.X509Certificate;
  47import java.util.ArrayList;
  48import java.util.Arrays;
  49import java.util.Collection;
  50import java.util.Collections;
  51import java.util.Comparator;
  52import java.util.Hashtable;
  53import java.util.Iterator;
  54import java.util.List;
  55import java.util.Locale;
  56import java.util.Map;
  57import java.util.concurrent.CopyOnWriteArrayList;
  58
  59import de.duenndns.ssl.MemorizingTrustManager;
  60import eu.siacs.conversations.Config;
  61import eu.siacs.conversations.R;
  62import eu.siacs.conversations.crypto.PgpEngine;
  63import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  64import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  65import eu.siacs.conversations.entities.Account;
  66import eu.siacs.conversations.entities.Blockable;
  67import eu.siacs.conversations.entities.Bookmark;
  68import eu.siacs.conversations.entities.Contact;
  69import eu.siacs.conversations.entities.Conversation;
  70import eu.siacs.conversations.entities.Message;
  71import eu.siacs.conversations.entities.MucOptions;
  72import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  73import eu.siacs.conversations.entities.Presences;
  74import eu.siacs.conversations.entities.Transferable;
  75import eu.siacs.conversations.entities.TransferablePlaceholder;
  76import eu.siacs.conversations.generator.IqGenerator;
  77import eu.siacs.conversations.generator.MessageGenerator;
  78import eu.siacs.conversations.generator.PresenceGenerator;
  79import eu.siacs.conversations.http.HttpConnectionManager;
  80import eu.siacs.conversations.parser.IqParser;
  81import eu.siacs.conversations.parser.MessageParser;
  82import eu.siacs.conversations.parser.PresenceParser;
  83import eu.siacs.conversations.persistance.DatabaseBackend;
  84import eu.siacs.conversations.persistance.FileBackend;
  85import eu.siacs.conversations.ui.UiCallback;
  86import eu.siacs.conversations.utils.CryptoHelper;
  87import eu.siacs.conversations.utils.ExceptionHelper;
  88import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
  89import eu.siacs.conversations.utils.PRNGFixes;
  90import eu.siacs.conversations.utils.PhoneHelper;
  91import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  92import eu.siacs.conversations.utils.Xmlns;
  93import eu.siacs.conversations.xml.Element;
  94import eu.siacs.conversations.xmpp.OnBindListener;
  95import eu.siacs.conversations.xmpp.OnContactStatusChanged;
  96import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  97import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  98import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
  99import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 100import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 101import eu.siacs.conversations.xmpp.OnStatusChanged;
 102import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 103import eu.siacs.conversations.xmpp.XmppConnection;
 104import eu.siacs.conversations.xmpp.chatstate.ChatState;
 105import eu.siacs.conversations.xmpp.forms.Data;
 106import eu.siacs.conversations.xmpp.forms.Field;
 107import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 108import eu.siacs.conversations.xmpp.jid.Jid;
 109import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 110import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 111import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 112import eu.siacs.conversations.xmpp.pep.Avatar;
 113import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 114import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 115import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 116import me.leolin.shortcutbadger.ShortcutBadger;
 117
 118public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
 119
 120	public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 121	public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
 122	public static final String ACTION_TRY_AGAIN = "try_again";
 123	public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
 124	private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
 125	private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
 126	private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
 127	private final IBinder mBinder = new XmppConnectionBinder();
 128	private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 129	private final IqGenerator mIqGenerator = new IqGenerator(this);
 130	private final List<String> mInProgressAvatarFetches = new ArrayList<>();
 131	public DatabaseBackend databaseBackend;
 132	private ContentObserver contactObserver = new ContentObserver(null) {
 133		@Override
 134		public void onChange(boolean selfChange) {
 135			super.onChange(selfChange);
 136			Intent intent = new Intent(getApplicationContext(),
 137					XmppConnectionService.class);
 138			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 139			startService(intent);
 140		}
 141	};
 142	private FileBackend fileBackend = new FileBackend(this);
 143	private MemorizingTrustManager mMemorizingTrustManager;
 144	private NotificationService mNotificationService = new NotificationService(
 145			this);
 146	private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 147	private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 148	private IqParser mIqParser = new IqParser(this);
 149	private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
 150		@Override
 151		public void onIqPacketReceived(Account account, IqPacket packet) {
 152			if (packet.getType() != IqPacket.TYPE.RESULT) {
 153				Element error = packet.findChild("error");
 154				String text = error != null ? error.findChildContent("text") : null;
 155				if (text != null) {
 156					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
 157				}
 158			}
 159		}
 160	};
 161	private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 162	private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 163	private List<Account> accounts;
 164	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 165			this);
 166	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
 167
 168		@Override
 169		public void onContactStatusChanged(Contact contact, boolean online) {
 170			Conversation conversation = find(getConversations(), contact);
 171			if (conversation != null) {
 172				if (online) {
 173					conversation.endOtrIfNeeded();
 174					if (contact.getPresences().size() == 1) {
 175						sendUnsentMessages(conversation);
 176					}
 177				} else {
 178					if (contact.getPresences().size() >= 1) {
 179						if (conversation.hasValidOtrSession()) {
 180							String otrResource = conversation.getOtrSession().getSessionID().getUserID();
 181							if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
 182								conversation.endOtrIfNeeded();
 183							}
 184						}
 185					} else {
 186						conversation.endOtrIfNeeded();
 187					}
 188				}
 189			}
 190		}
 191	};
 192	private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 193			this);
 194	private AvatarService mAvatarService = new AvatarService(this);
 195	private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 196	private OnConversationUpdate mOnConversationUpdate = null;
 197	private final FileObserver fileObserver = new FileObserver(
 198			FileBackend.getConversationsImageDirectory()) {
 199
 200		@Override
 201		public void onEvent(int event, String path) {
 202			if (event == FileObserver.DELETE) {
 203				markFileDeleted(path.split("\\.")[0]);
 204			}
 205		}
 206	};
 207	private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 208
 209		@Override
 210		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 211			mJingleConnectionManager.deliverPacket(account, packet);
 212		}
 213	};
 214	private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 215
 216		@Override
 217		public void onMessageAcknowledged(Account account, String uuid) {
 218			for (final Conversation conversation : getConversations()) {
 219				if (conversation.getAccount() == account) {
 220					Message message = conversation.findUnsentMessageWithUuid(uuid);
 221					if (message != null) {
 222						markMessage(message, Message.STATUS_SEND);
 223						if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
 224							databaseBackend.updateConversation(conversation);
 225						}
 226					}
 227				}
 228			}
 229		}
 230	};
 231	private int convChangedListenerCount = 0;
 232	private OnShowErrorToast mOnShowErrorToast = null;
 233	private int showErrorToastListenerCount = 0;
 234	private int unreadCount = -1;
 235	private OnAccountUpdate mOnAccountUpdate = null;
 236	private OnCaptchaRequested mOnCaptchaRequested = null;
 237	private int accountChangedListenerCount = 0;
 238	private int captchaRequestedListenerCount = 0;
 239	private OnRosterUpdate mOnRosterUpdate = null;
 240	private OnUpdateBlocklist mOnUpdateBlocklist = null;
 241	private int updateBlocklistListenerCount = 0;
 242	private int rosterChangedListenerCount = 0;
 243	private OnMucRosterUpdate mOnMucRosterUpdate = null;
 244	private int mucRosterChangedListenerCount = 0;
 245	private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
 246	private int keyStatusUpdatedListenerCount = 0;
 247	private SecureRandom mRandom;
 248	private final OnBindListener mOnBindListener = new OnBindListener() {
 249
 250		@Override
 251		public void onBind(final Account account) {
 252			account.getRoster().clearPresences();
 253			fetchRosterFromServer(account);
 254			fetchBookmarks(account);
 255			sendPresence(account);
 256			connectMultiModeConversations(account);
 257			mMessageArchiveService.executePendingQueries(account);
 258			mJingleConnectionManager.cancelInTransmission();
 259			syncDirtyContacts(account);
 260		}
 261	};
 262	private OnStatusChanged statusListener = new OnStatusChanged() {
 263
 264		@Override
 265		public void onStatusChanged(Account account) {
 266			XmppConnection connection = account.getXmppConnection();
 267			if (mOnAccountUpdate != null) {
 268				mOnAccountUpdate.onAccountUpdate();
 269			}
 270			if (account.getStatus() == Account.State.ONLINE) {
 271				if (connection != null && connection.getFeatures().csi()) {
 272					if (checkListeners()) {
 273						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
 274						connection.sendInactive();
 275					} else {
 276						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
 277						connection.sendActive();
 278					}
 279				}
 280				List<Conversation> conversations = getConversations();
 281				for (Conversation conversation : conversations) {
 282					if (conversation.getAccount() == account) {
 283						conversation.startOtrIfNeeded();
 284						sendUnsentMessages(conversation);
 285					}
 286				}
 287				for (Conversation conversation : account.pendingConferenceLeaves) {
 288					leaveMuc(conversation);
 289				}
 290				account.pendingConferenceLeaves.clear();
 291				for (Conversation conversation : account.pendingConferenceJoins) {
 292					joinMuc(conversation);
 293				}
 294				account.pendingConferenceJoins.clear();
 295				scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 296			} else if (account.getStatus() == Account.State.OFFLINE) {
 297				resetSendingToWaiting(account);
 298				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 299					int timeToReconnect = mRandom.nextInt(20) + 10;
 300					scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 301				}
 302			} else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 303				databaseBackend.updateAccount(account);
 304				reconnectAccount(account, true, false);
 305			} else if ((account.getStatus() != Account.State.CONNECTING)
 306					&& (account.getStatus() != Account.State.NO_INTERNET)) {
 307				if (connection != null) {
 308					int next = connection.getTimeToNextAttempt();
 309					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 310							+ ": error connecting account. try again in "
 311							+ next + "s for the "
 312							+ (connection.getAttempt() + 1) + " time");
 313					scheduleWakeUpCall(next, account.getUuid().hashCode());
 314				}
 315			}
 316			getNotificationService().updateErrorNotification();
 317		}
 318	};
 319	private OpenPgpServiceConnection pgpServiceConnection;
 320	private PgpEngine mPgpEngine = null;
 321	private WakeLock wakeLock;
 322	private PowerManager pm;
 323	private LruCache<String, Bitmap> mBitmapCache;
 324	private Thread mPhoneContactMergerThread;
 325	private EventReceiver mEventReceiver = new EventReceiver();
 326
 327	private boolean mRestoredFromDatabase = false;
 328
 329	private static String generateFetchKey(Account account, final Avatar avatar) {
 330		return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 331	}
 332
 333	public boolean areMessagesInitialized() {
 334		return this.mRestoredFromDatabase;
 335	}
 336
 337	public PgpEngine getPgpEngine() {
 338		if (pgpServiceConnection.isBound()) {
 339			if (this.mPgpEngine == null) {
 340				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 341						getApplicationContext(),
 342						pgpServiceConnection.getService()), this);
 343			}
 344			return mPgpEngine;
 345		} else {
 346			return null;
 347		}
 348
 349	}
 350
 351	public FileBackend getFileBackend() {
 352		return this.fileBackend;
 353	}
 354
 355	public AvatarService getAvatarService() {
 356		return this.mAvatarService;
 357	}
 358
 359	public void attachLocationToConversation(final Conversation conversation,
 360											 final Uri uri,
 361											 final UiCallback<Message> callback) {
 362		int encryption = conversation.getNextEncryption();
 363		if (encryption == Message.ENCRYPTION_PGP) {
 364			encryption = Message.ENCRYPTION_DECRYPTED;
 365		}
 366		Message message = new Message(conversation, uri.toString(), encryption);
 367		if (conversation.getNextCounterpart() != null) {
 368			message.setCounterpart(conversation.getNextCounterpart());
 369		}
 370		if (encryption == Message.ENCRYPTION_DECRYPTED) {
 371			getPgpEngine().encrypt(message, callback);
 372		} else {
 373			callback.success(message);
 374		}
 375	}
 376
 377	public void attachFileToConversation(final Conversation conversation,
 378										 final Uri uri,
 379										 final UiCallback<Message> callback) {
 380		final Message message;
 381		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 382			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 383		} else {
 384			message = new Message(conversation, "", conversation.getNextEncryption());
 385		}
 386		message.setCounterpart(conversation.getNextCounterpart());
 387		message.setType(Message.TYPE_FILE);
 388		String path = getFileBackend().getOriginalPath(uri);
 389		if (path != null) {
 390			message.setRelativeFilePath(path);
 391			getFileBackend().updateFileParams(message);
 392			if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 393				getPgpEngine().encrypt(message, callback);
 394			} else {
 395				callback.success(message);
 396			}
 397		} else {
 398			mFileAddingExecutor.execute(new Runnable() {
 399				@Override
 400				public void run() {
 401					try {
 402						getFileBackend().copyFileToPrivateStorage(message, uri);
 403						getFileBackend().updateFileParams(message);
 404						if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 405							getPgpEngine().encrypt(message, callback);
 406						} else {
 407							callback.success(message);
 408						}
 409					} catch (FileBackend.FileCopyException e) {
 410						callback.error(e.getResId(), message);
 411					}
 412				}
 413			});
 414		}
 415	}
 416
 417	public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 418		if (getFileBackend().useImageAsIs(uri)) {
 419			Log.d(Config.LOGTAG, "using image as is");
 420			attachFileToConversation(conversation, uri, callback);
 421			return;
 422		}
 423		final Message message;
 424		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 425			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 426		} else {
 427			message = new Message(conversation, "", conversation.getNextEncryption());
 428		}
 429		message.setCounterpart(conversation.getNextCounterpart());
 430		message.setType(Message.TYPE_IMAGE);
 431		mFileAddingExecutor.execute(new Runnable() {
 432
 433			@Override
 434			public void run() {
 435				try {
 436					getFileBackend().copyImageToPrivateStorage(message, uri);
 437					if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 438						getPgpEngine().encrypt(message, callback);
 439					} else {
 440						callback.success(message);
 441					}
 442				} catch (final FileBackend.FileCopyException e) {
 443					callback.error(e.getResId(), message);
 444				}
 445			}
 446		});
 447	}
 448
 449	public Conversation find(Bookmark bookmark) {
 450		return find(bookmark.getAccount(), bookmark.getJid());
 451	}
 452
 453	public Conversation find(final Account account, final Jid jid) {
 454		return find(getConversations(), account, jid);
 455	}
 456
 457	@Override
 458	public int onStartCommand(Intent intent, int flags, int startId) {
 459		final String action = intent == null ? null : intent.getAction();
 460		boolean interactive = false;
 461		if (action != null) {
 462			switch (action) {
 463				case ConnectivityManager.CONNECTIVITY_ACTION:
 464					if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 465						resetAllAttemptCounts(true);
 466					}
 467					break;
 468				case ACTION_MERGE_PHONE_CONTACTS:
 469					if (mRestoredFromDatabase) {
 470						PhoneHelper.loadPhoneContacts(getApplicationContext(),
 471								new CopyOnWriteArrayList<Bundle>(),
 472								this);
 473					}
 474					return START_STICKY;
 475				case Intent.ACTION_SHUTDOWN:
 476					logoutAndSave();
 477					return START_NOT_STICKY;
 478				case ACTION_CLEAR_NOTIFICATION:
 479					mNotificationService.clear();
 480					break;
 481				case ACTION_DISABLE_FOREGROUND:
 482					getPreferences().edit().putBoolean("keep_foreground_service", false).commit();
 483					toggleForegroundService();
 484					break;
 485				case ACTION_TRY_AGAIN:
 486					resetAllAttemptCounts(false);
 487					interactive = true;
 488					break;
 489				case ACTION_DISABLE_ACCOUNT:
 490					try {
 491						String jid = intent.getStringExtra("account");
 492						Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
 493						if (account != null) {
 494							account.setOption(Account.OPTION_DISABLED, true);
 495							updateAccount(account);
 496						}
 497					} catch (final InvalidJidException ignored) {
 498						break;
 499					}
 500					break;
 501				case AudioManager.RINGER_MODE_CHANGED_ACTION:
 502					if (xaOnSilentMode()) {
 503						refreshAllPresences();
 504					}
 505					break;
 506				case Intent.ACTION_SCREEN_OFF:
 507				case Intent.ACTION_SCREEN_ON:
 508					if (awayWhenScreenOff()) {
 509						refreshAllPresences();
 510					}
 511					break;
 512			}
 513		}
 514		this.wakeLock.acquire();
 515
 516		for (Account account : accounts) {
 517			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 518				if (!hasInternetConnection()) {
 519					account.setStatus(Account.State.NO_INTERNET);
 520					if (statusListener != null) {
 521						statusListener.onStatusChanged(account);
 522					}
 523				} else {
 524					if (account.getStatus() == Account.State.NO_INTERNET) {
 525						account.setStatus(Account.State.OFFLINE);
 526						if (statusListener != null) {
 527							statusListener.onStatusChanged(account);
 528						}
 529					}
 530					if (account.getStatus() == Account.State.ONLINE) {
 531						long lastReceived = account.getXmppConnection().getLastPacketReceived();
 532						long lastSent = account.getXmppConnection().getLastPingSent();
 533						long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 534						long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 535						long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
 536						if (lastSent > lastReceived) {
 537							if (pingTimeoutIn < 0) {
 538								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
 539								this.reconnectAccount(account, true, interactive);
 540							} else {
 541								int secs = (int) (pingTimeoutIn / 1000);
 542								this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
 543							}
 544						} else if (msToNextPing <= 0) {
 545							account.getXmppConnection().sendPing();
 546							Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping");
 547							this.scheduleWakeUpCall(Config.PING_TIMEOUT, account.getUuid().hashCode());
 548						} else {
 549							this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 550						}
 551					} else if (account.getStatus() == Account.State.OFFLINE) {
 552						reconnectAccount(account, true, interactive);
 553					} else if (account.getStatus() == Account.State.CONNECTING) {
 554						long timeout = Config.CONNECT_TIMEOUT - ((SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000);
 555						if (timeout < 0) {
 556							Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
 557							reconnectAccount(account, true, interactive);
 558						} else {
 559							scheduleWakeUpCall((int) timeout, account.getUuid().hashCode());
 560						}
 561					} else {
 562						if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 563							reconnectAccount(account, true, interactive);
 564						}
 565					}
 566
 567				}
 568				if (mOnAccountUpdate != null) {
 569					mOnAccountUpdate.onAccountUpdate();
 570				}
 571			}
 572		}
 573		if (wakeLock.isHeld()) {
 574			try {
 575				wakeLock.release();
 576			} catch (final RuntimeException ignored) {
 577			}
 578		}
 579		return START_STICKY;
 580	}
 581
 582	private boolean xaOnSilentMode() {
 583		return getPreferences().getBoolean("xa_on_silent_mode", false);
 584	}
 585
 586	private boolean awayWhenScreenOff() {
 587		return getPreferences().getBoolean("away_when_screen_off", false);
 588	}
 589
 590	private int getTargetPresence() {
 591		if (xaOnSilentMode() && isPhoneSilenced()) {
 592			return Presences.XA;
 593		} else if (awayWhenScreenOff() && !isInteractive()) {
 594			return Presences.AWAY;
 595		} else {
 596			return Presences.ONLINE;
 597		}
 598	}
 599
 600	@SuppressLint("NewApi")
 601	@SuppressWarnings("deprecation")
 602	public boolean isInteractive() {
 603		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 604
 605		final boolean isScreenOn;
 606		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 607			isScreenOn = pm.isScreenOn();
 608		} else {
 609			isScreenOn = pm.isInteractive();
 610		}
 611		return isScreenOn;
 612	}
 613
 614	private boolean isPhoneSilenced() {
 615		AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
 616		return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
 617	}
 618
 619	private void resetAllAttemptCounts(boolean reallyAll) {
 620		Log.d(Config.LOGTAG, "resetting all attepmt counts");
 621		for (Account account : accounts) {
 622			if (account.hasErrorStatus() || reallyAll) {
 623				final XmppConnection connection = account.getXmppConnection();
 624				if (connection != null) {
 625					connection.resetAttemptCount();
 626				}
 627			}
 628		}
 629	}
 630
 631	public boolean hasInternetConnection() {
 632		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 633				.getSystemService(Context.CONNECTIVITY_SERVICE);
 634		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 635		return activeNetwork != null && activeNetwork.isConnected();
 636	}
 637
 638	@SuppressLint("TrulyRandom")
 639	@Override
 640	public void onCreate() {
 641		ExceptionHelper.init(getApplicationContext());
 642		PRNGFixes.apply();
 643		this.mRandom = new SecureRandom();
 644		updateMemorizingTrustmanager();
 645		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 646		final int cacheSize = maxMemory / 8;
 647		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 648			@Override
 649			protected int sizeOf(final String key, final Bitmap bitmap) {
 650				return bitmap.getByteCount() / 1024;
 651			}
 652		};
 653
 654		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 655		this.accounts = databaseBackend.getAccounts();
 656
 657		restoreFromDatabase();
 658
 659		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 660		this.fileObserver.startWatching();
 661
 662		this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
 663		this.pgpServiceConnection.bindToService();
 664
 665		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 666		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
 667		toggleForegroundService();
 668		updateUnreadCountBadge();
 669		toggleScreenEventReceiver();
 670	}
 671
 672	@Override
 673	public void onTrimMemory(int level) {
 674		super.onTrimMemory(level);
 675		if (level >= TRIM_MEMORY_COMPLETE) {
 676			Log.d(Config.LOGTAG, "clear cache due to low memory");
 677			getBitmapCache().evictAll();
 678		}
 679	}
 680
 681	@Override
 682	public void onDestroy() {
 683		try {
 684			unregisterReceiver(this.mEventReceiver);
 685		} catch (IllegalArgumentException e) {
 686			//ignored
 687		}
 688		super.onDestroy();
 689	}
 690
 691	public void toggleScreenEventReceiver() {
 692		if (awayWhenScreenOff()) {
 693			final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
 694			filter.addAction(Intent.ACTION_SCREEN_OFF);
 695			registerReceiver(this.mEventReceiver, filter);
 696		} else {
 697			try {
 698				unregisterReceiver(this.mEventReceiver);
 699			} catch (IllegalArgumentException e) {
 700				//ignored
 701			}
 702		}
 703	}
 704
 705	public void toggleForegroundService() {
 706		if (getPreferences().getBoolean("keep_foreground_service", false)) {
 707			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 708		} else {
 709			stopForeground(true);
 710		}
 711	}
 712
 713	@Override
 714	public void onTaskRemoved(final Intent rootIntent) {
 715		super.onTaskRemoved(rootIntent);
 716		if (!getPreferences().getBoolean("keep_foreground_service", false)) {
 717			this.logoutAndSave();
 718		}
 719	}
 720
 721	private void logoutAndSave() {
 722		for (final Account account : accounts) {
 723			databaseBackend.writeRoster(account.getRoster());
 724			if (account.getXmppConnection() != null) {
 725				new Thread(new Runnable() {
 726					@Override
 727					public void run() {
 728						disconnect(account, false);
 729					}
 730				}).start();
 731
 732			}
 733		}
 734		Context context = getApplicationContext();
 735		AlarmManager alarmManager = (AlarmManager) context
 736				.getSystemService(Context.ALARM_SERVICE);
 737		Intent intent = new Intent(context, EventReceiver.class);
 738		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 739		Log.d(Config.LOGTAG, "good bye");
 740		stopSelf();
 741	}
 742
 743	protected void scheduleWakeUpCall(int seconds, int requestCode) {
 744		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
 745
 746		Context context = getApplicationContext();
 747		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 748
 749		Intent intent = new Intent(context, EventReceiver.class);
 750		intent.setAction("ping");
 751		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
 752		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 753	}
 754
 755	public XmppConnection createConnection(final Account account) {
 756		final SharedPreferences sharedPref = getPreferences();
 757		account.setResource(sharedPref.getString("resource", "mobile")
 758				.toLowerCase(Locale.getDefault()));
 759		final XmppConnection connection = new XmppConnection(account, this);
 760		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 761		connection.setOnStatusChangedListener(this.statusListener);
 762		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 763		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 764		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 765		connection.setOnBindListener(this.mOnBindListener);
 766		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 767		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 768		AxolotlService axolotlService = account.getAxolotlService();
 769		if (axolotlService != null) {
 770			connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
 771		}
 772		return connection;
 773	}
 774
 775	public void sendChatState(Conversation conversation) {
 776		if (sendChatStates()) {
 777			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
 778			sendMessagePacket(conversation.getAccount(), packet);
 779		}
 780	}
 781
 782	private void sendFileMessage(final Message message, final boolean delay) {
 783		Log.d(Config.LOGTAG, "send file message");
 784		final Account account = message.getConversation().getAccount();
 785		final XmppConnection connection = account.getXmppConnection();
 786		if (connection != null && connection.getFeatures().httpUpload()) {
 787			mHttpConnectionManager.createNewUploadConnection(message, delay);
 788		} else {
 789			mJingleConnectionManager.createNewConnection(message);
 790		}
 791	}
 792
 793	public void sendMessage(final Message message) {
 794		sendMessage(message, false, false);
 795	}
 796
 797	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
 798		final Account account = message.getConversation().getAccount();
 799		final Conversation conversation = message.getConversation();
 800		account.deactivateGracePeriod();
 801		MessagePacket packet = null;
 802		boolean saveInDb = true;
 803		message.setStatus(Message.STATUS_WAITING);
 804
 805		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
 806			message.getConversation().endOtrIfNeeded();
 807			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
 808					new Conversation.OnMessageFound() {
 809						@Override
 810						public void onMessageFound(Message message) {
 811							markMessage(message, Message.STATUS_SEND_FAILED);
 812						}
 813					});
 814		}
 815
 816		if (account.isOnlineAndConnected()) {
 817			switch (message.getEncryption()) {
 818				case Message.ENCRYPTION_NONE:
 819					if (message.needsUploading()) {
 820						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 821							this.sendFileMessage(message, delay);
 822						} else {
 823							break;
 824						}
 825					} else {
 826						packet = mMessageGenerator.generateChat(message);
 827					}
 828					break;
 829				case Message.ENCRYPTION_PGP:
 830				case Message.ENCRYPTION_DECRYPTED:
 831					if (message.needsUploading()) {
 832						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 833							this.sendFileMessage(message, delay);
 834						} else {
 835							break;
 836						}
 837					} else {
 838						packet = mMessageGenerator.generatePgpChat(message);
 839					}
 840					break;
 841				case Message.ENCRYPTION_OTR:
 842					SessionImpl otrSession = conversation.getOtrSession();
 843					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
 844						try {
 845							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
 846						} catch (InvalidJidException e) {
 847							break;
 848						}
 849						if (message.needsUploading()) {
 850							mJingleConnectionManager.createNewConnection(message);
 851						} else {
 852							packet = mMessageGenerator.generateOtrChat(message);
 853						}
 854					} else if (otrSession == null) {
 855						if (message.fixCounterpart()) {
 856							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
 857						} else {
 858							break;
 859						}
 860					}
 861					break;
 862				case Message.ENCRYPTION_AXOLOTL:
 863					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 864					if (message.needsUploading()) {
 865						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 866							this.sendFileMessage(message, delay);
 867						} else {
 868							break;
 869						}
 870					} else {
 871						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
 872						if (axolotlMessage == null) {
 873							account.getAxolotlService().preparePayloadMessage(message, delay);
 874						} else {
 875							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
 876						}
 877					}
 878					break;
 879
 880			}
 881			if (packet != null) {
 882				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 883					message.setStatus(Message.STATUS_UNSEND);
 884				} else {
 885					message.setStatus(Message.STATUS_SEND);
 886				}
 887			}
 888		} else {
 889			switch (message.getEncryption()) {
 890				case Message.ENCRYPTION_DECRYPTED:
 891					if (!message.needsUploading()) {
 892						String pgpBody = message.getEncryptedBody();
 893						String decryptedBody = message.getBody();
 894						message.setBody(pgpBody);
 895						message.setEncryption(Message.ENCRYPTION_PGP);
 896						databaseBackend.createMessage(message);
 897						saveInDb = false;
 898						message.setBody(decryptedBody);
 899						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 900					}
 901					break;
 902				case Message.ENCRYPTION_OTR:
 903					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
 904						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
 905					}
 906					break;
 907				case Message.ENCRYPTION_AXOLOTL:
 908					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 909					break;
 910			}
 911		}
 912
 913		if (resend) {
 914			if (packet != null) {
 915				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 916					markMessage(message, Message.STATUS_UNSEND);
 917				} else {
 918					markMessage(message, Message.STATUS_SEND);
 919				}
 920			}
 921		} else {
 922			conversation.add(message);
 923			if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
 924				databaseBackend.createMessage(message);
 925			}
 926			updateConversationUi();
 927		}
 928		if (packet != null) {
 929			if (delay) {
 930				mMessageGenerator.addDelay(packet, message.getTimeSent());
 931			}
 932			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 933				if (this.sendChatStates()) {
 934					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
 935				}
 936			}
 937			sendMessagePacket(account, packet);
 938		}
 939	}
 940
 941	private void sendUnsentMessages(final Conversation conversation) {
 942		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 943
 944			@Override
 945			public void onMessageFound(Message message) {
 946				resendMessage(message, true);
 947			}
 948		});
 949	}
 950
 951	public void resendMessage(final Message message, final boolean delay) {
 952		sendMessage(message, true, delay);
 953	}
 954
 955	public void fetchRosterFromServer(final Account account) {
 956		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 957		if (!"".equals(account.getRosterVersion())) {
 958			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 959					+ ": fetching roster version " + account.getRosterVersion());
 960		} else {
 961			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 962		}
 963		iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
 964		sendIqPacket(account, iqPacket, mIqParser);
 965	}
 966
 967	public void fetchBookmarks(final Account account) {
 968		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 969		final Element query = iqPacket.query("jabber:iq:private");
 970		query.addChild("storage", "storage:bookmarks");
 971		final OnIqPacketReceived callback = new OnIqPacketReceived() {
 972
 973			@Override
 974			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 975				if (packet.getType() == IqPacket.TYPE.RESULT) {
 976					final Element query = packet.query();
 977					final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 978					final Element storage = query.findChild("storage", "storage:bookmarks");
 979					if (storage != null) {
 980						for (final Element item : storage.getChildren()) {
 981							if (item.getName().equals("conference")) {
 982								final Bookmark bookmark = Bookmark.parse(item, account);
 983								bookmarks.add(bookmark);
 984								Conversation conversation = find(bookmark);
 985								if (conversation != null) {
 986									conversation.setBookmark(bookmark);
 987								} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 988									conversation = findOrCreateConversation(
 989											account, bookmark.getJid(), true);
 990									conversation.setBookmark(bookmark);
 991									joinMuc(conversation);
 992								}
 993							}
 994						}
 995					}
 996					account.setBookmarks(bookmarks);
 997				} else {
 998					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
 999				}
1000			}
1001		};
1002		sendIqPacket(account, iqPacket, callback);
1003	}
1004
1005	public void pushBookmarks(Account account) {
1006		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1007		Element query = iqPacket.query("jabber:iq:private");
1008		Element storage = query.addChild("storage", "storage:bookmarks");
1009		for (Bookmark bookmark : account.getBookmarks()) {
1010			storage.addChild(bookmark);
1011		}
1012		sendIqPacket(account, iqPacket, mDefaultIqHandler);
1013	}
1014
1015	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
1016		if (mPhoneContactMergerThread != null) {
1017			mPhoneContactMergerThread.interrupt();
1018		}
1019		mPhoneContactMergerThread = new Thread(new Runnable() {
1020			@Override
1021			public void run() {
1022				Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1023				for (Account account : accounts) {
1024					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1025					for (Bundle phoneContact : phoneContacts) {
1026						if (Thread.interrupted()) {
1027							Log.d(Config.LOGTAG, "interrupted merging phone contacts");
1028							return;
1029						}
1030						Jid jid;
1031						try {
1032							jid = Jid.fromString(phoneContact.getString("jid"));
1033						} catch (final InvalidJidException e) {
1034							continue;
1035						}
1036						final Contact contact = account.getRoster().getContact(jid);
1037						String systemAccount = phoneContact.getInt("phoneid")
1038								+ "#"
1039								+ phoneContact.getString("lookup");
1040						contact.setSystemAccount(systemAccount);
1041						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1042							getAvatarService().clear(contact);
1043						}
1044						contact.setSystemName(phoneContact.getString("displayname"));
1045						withSystemAccounts.remove(contact);
1046					}
1047					for (Contact contact : withSystemAccounts) {
1048						contact.setSystemAccount(null);
1049						contact.setSystemName(null);
1050						if (contact.setPhotoUri(null)) {
1051							getAvatarService().clear(contact);
1052						}
1053					}
1054				}
1055				Log.d(Config.LOGTAG, "finished merging phone contacts");
1056				updateAccountUi();
1057			}
1058		});
1059		mPhoneContactMergerThread.start();
1060	}
1061
1062	private void restoreFromDatabase() {
1063		synchronized (this.conversations) {
1064			final Map<String, Account> accountLookupTable = new Hashtable<>();
1065			for (Account account : this.accounts) {
1066				accountLookupTable.put(account.getUuid(), account);
1067			}
1068			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1069			for (Conversation conversation : this.conversations) {
1070				Account account = accountLookupTable.get(conversation.getAccountUuid());
1071				conversation.setAccount(account);
1072			}
1073			Runnable runnable = new Runnable() {
1074				@Override
1075				public void run() {
1076					Log.d(Config.LOGTAG, "restoring roster");
1077					for (Account account : accounts) {
1078						account.initAccountServices(XmppConnectionService.this);
1079						databaseBackend.readRoster(account.getRoster());
1080					}
1081					getBitmapCache().evictAll();
1082					Looper.prepare();
1083					PhoneHelper.loadPhoneContacts(getApplicationContext(),
1084							new CopyOnWriteArrayList<Bundle>(),
1085							XmppConnectionService.this);
1086					Log.d(Config.LOGTAG, "restoring messages");
1087					for (Conversation conversation : conversations) {
1088						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1089						checkDeletedFiles(conversation);
1090						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1091							@Override
1092							public void onMessageFound(Message message) {
1093								mNotificationService.pushFromBacklog(message);
1094							}
1095						});
1096					}
1097					mNotificationService.finishBacklog();
1098					mRestoredFromDatabase = true;
1099					Log.d(Config.LOGTAG, "restored all messages");
1100					updateConversationUi();
1101				}
1102			};
1103			mDatabaseExecutor.execute(runnable);
1104		}
1105	}
1106
1107	public List<Conversation> getConversations() {
1108		return this.conversations;
1109	}
1110
1111	private void checkDeletedFiles(Conversation conversation) {
1112		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1113
1114			@Override
1115			public void onMessageFound(Message message) {
1116				if (!getFileBackend().isFileAvailable(message)) {
1117					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1118					final int s = message.getStatus();
1119					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1120						markMessage(message, Message.STATUS_SEND_FAILED);
1121					}
1122				}
1123			}
1124		});
1125	}
1126
1127	private void markFileDeleted(String uuid) {
1128		for (Conversation conversation : getConversations()) {
1129			Message message = conversation.findMessageWithFileAndUuid(uuid);
1130			if (message != null) {
1131				if (!getFileBackend().isFileAvailable(message)) {
1132					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1133					final int s = message.getStatus();
1134					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1135						markMessage(message, Message.STATUS_SEND_FAILED);
1136					} else {
1137						updateConversationUi();
1138					}
1139				}
1140				return;
1141			}
1142		}
1143	}
1144
1145	public void populateWithOrderedConversations(final List<Conversation> list) {
1146		populateWithOrderedConversations(list, true);
1147	}
1148
1149	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1150		list.clear();
1151		if (includeNoFileUpload) {
1152			list.addAll(getConversations());
1153		} else {
1154			for (Conversation conversation : getConversations()) {
1155				if (conversation.getMode() == Conversation.MODE_SINGLE
1156						|| conversation.getAccount().httpUploadAvailable()) {
1157					list.add(conversation);
1158				}
1159			}
1160		}
1161		Collections.sort(list, new Comparator<Conversation>() {
1162			@Override
1163			public int compare(Conversation lhs, Conversation rhs) {
1164				Message left = lhs.getLatestMessage();
1165				Message right = rhs.getLatestMessage();
1166				if (left.getTimeSent() > right.getTimeSent()) {
1167					return -1;
1168				} else if (left.getTimeSent() < right.getTimeSent()) {
1169					return 1;
1170				} else {
1171					return 0;
1172				}
1173			}
1174		});
1175	}
1176
1177	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1178		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1179			return;
1180		}
1181		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1182		Runnable runnable = new Runnable() {
1183			@Override
1184			public void run() {
1185				final Account account = conversation.getAccount();
1186				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1187				if (messages.size() > 0) {
1188					conversation.addAll(0, messages);
1189					checkDeletedFiles(conversation);
1190					callback.onMoreMessagesLoaded(messages.size(), conversation);
1191				} else if (conversation.hasMessagesLeftOnServer()
1192						&& account.isOnlineAndConnected()) {
1193					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1194							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1195						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp - 1);
1196						if (query != null) {
1197							query.setCallback(callback);
1198						}
1199						callback.informUser(R.string.fetching_history_from_server);
1200					}
1201				}
1202			}
1203		};
1204		mDatabaseExecutor.execute(runnable);
1205	}
1206
1207	public List<Account> getAccounts() {
1208		return this.accounts;
1209	}
1210
1211	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1212		for (final Conversation conversation : haystack) {
1213			if (conversation.getContact() == contact) {
1214				return conversation;
1215			}
1216		}
1217		return null;
1218	}
1219
1220	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1221		if (jid == null) {
1222			return null;
1223		}
1224		for (final Conversation conversation : haystack) {
1225			if ((account == null || conversation.getAccount() == account)
1226					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1227				return conversation;
1228			}
1229		}
1230		return null;
1231	}
1232
1233	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1234		return this.findOrCreateConversation(account, jid, muc, null);
1235	}
1236
1237	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1238		synchronized (this.conversations) {
1239			Conversation conversation = find(account, jid);
1240			if (conversation != null) {
1241				return conversation;
1242			}
1243			conversation = databaseBackend.findConversation(account, jid);
1244			if (conversation != null) {
1245				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1246				conversation.setAccount(account);
1247				if (muc) {
1248					conversation.setMode(Conversation.MODE_MULTI);
1249					conversation.setContactJid(jid);
1250				} else {
1251					conversation.setMode(Conversation.MODE_SINGLE);
1252					conversation.setContactJid(jid.toBareJid());
1253				}
1254				conversation.setNextEncryption(-1);
1255				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1256				this.databaseBackend.updateConversation(conversation);
1257			} else {
1258				String conversationName;
1259				Contact contact = account.getRoster().getContact(jid);
1260				if (contact != null) {
1261					conversationName = contact.getDisplayName();
1262				} else {
1263					conversationName = jid.getLocalpart();
1264				}
1265				if (muc) {
1266					conversation = new Conversation(conversationName, account, jid,
1267							Conversation.MODE_MULTI);
1268				} else {
1269					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1270							Conversation.MODE_SINGLE);
1271				}
1272				this.databaseBackend.createConversation(conversation);
1273			}
1274			if (account.getXmppConnection() != null
1275					&& account.getXmppConnection().getFeatures().mam()
1276					&& !muc) {
1277				if (query == null) {
1278					this.mMessageArchiveService.query(conversation);
1279				} else {
1280					if (query.getConversation() == null) {
1281						this.mMessageArchiveService.query(conversation, query.getStart());
1282					}
1283				}
1284			}
1285			checkDeletedFiles(conversation);
1286			this.conversations.add(conversation);
1287			updateConversationUi();
1288			return conversation;
1289		}
1290	}
1291
1292	public void archiveConversation(Conversation conversation) {
1293		getNotificationService().clear(conversation);
1294		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1295		conversation.setNextEncryption(-1);
1296		synchronized (this.conversations) {
1297			if (conversation.getMode() == Conversation.MODE_MULTI) {
1298				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1299					Bookmark bookmark = conversation.getBookmark();
1300					if (bookmark != null && bookmark.autojoin()) {
1301						bookmark.setAutojoin(false);
1302						pushBookmarks(bookmark.getAccount());
1303					}
1304				}
1305				leaveMuc(conversation);
1306			} else {
1307				conversation.endOtrIfNeeded();
1308			}
1309			this.databaseBackend.updateConversation(conversation);
1310			this.conversations.remove(conversation);
1311			updateConversationUi();
1312		}
1313	}
1314
1315	public void createAccount(final Account account) {
1316		account.initAccountServices(this);
1317		databaseBackend.createAccount(account);
1318		this.accounts.add(account);
1319		this.reconnectAccountInBackground(account);
1320		updateAccountUi();
1321	}
1322
1323	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1324		new Thread(new Runnable() {
1325			@Override
1326			public void run() {
1327				try {
1328					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1329					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1330					if (findAccountByJid(info.first) == null) {
1331						Account account = new Account(info.first, "");
1332						account.setPrivateKeyAlias(alias);
1333						account.setOption(Account.OPTION_DISABLED, true);
1334						createAccount(account);
1335						callback.onAccountCreated(account);
1336						if (Config.X509_VERIFICATION) {
1337							try {
1338								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1339							} catch (CertificateException e) {
1340								callback.informUser(R.string.certificate_chain_is_not_trusted);
1341							}
1342						}
1343					} else {
1344						callback.informUser(R.string.account_already_exists);
1345					}
1346				} catch (Exception e) {
1347					e.printStackTrace();
1348					callback.informUser(R.string.unable_to_parse_certificate);
1349				}
1350			}
1351		}).start();
1352
1353	}
1354
1355	public void updateKeyInAccount(final Account account, final String alias) {
1356		Log.d(Config.LOGTAG, "update key in account " + alias);
1357		try {
1358			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1359			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1360			if (account.getJid().toBareJid().equals(info.first)) {
1361				account.setPrivateKeyAlias(alias);
1362				databaseBackend.updateAccount(account);
1363				if (Config.X509_VERIFICATION) {
1364					try {
1365						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1366					} catch (CertificateException e) {
1367						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1368					}
1369					account.getAxolotlService().regenerateKeys(true);
1370				}
1371			} else {
1372				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1373			}
1374		} catch (Exception e) {
1375			e.printStackTrace();
1376		}
1377	}
1378
1379	public void updateAccount(final Account account) {
1380		this.statusListener.onStatusChanged(account);
1381		databaseBackend.updateAccount(account);
1382		reconnectAccountInBackground(account);
1383		updateAccountUi();
1384		getNotificationService().updateErrorNotification();
1385	}
1386
1387	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1388		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1389		sendIqPacket(account, iq, new OnIqPacketReceived() {
1390			@Override
1391			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1392				if (packet.getType() == IqPacket.TYPE.RESULT) {
1393					account.setPassword(newPassword);
1394					databaseBackend.updateAccount(account);
1395					callback.onPasswordChangeSucceeded();
1396				} else {
1397					callback.onPasswordChangeFailed();
1398				}
1399			}
1400		});
1401	}
1402
1403	public void deleteAccount(final Account account) {
1404		synchronized (this.conversations) {
1405			for (final Conversation conversation : conversations) {
1406				if (conversation.getAccount() == account) {
1407					if (conversation.getMode() == Conversation.MODE_MULTI) {
1408						leaveMuc(conversation);
1409					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1410						conversation.endOtrIfNeeded();
1411					}
1412					conversations.remove(conversation);
1413				}
1414			}
1415			if (account.getXmppConnection() != null) {
1416				this.disconnect(account, true);
1417			}
1418			databaseBackend.deleteAccount(account);
1419			this.accounts.remove(account);
1420			updateAccountUi();
1421			getNotificationService().updateErrorNotification();
1422		}
1423	}
1424
1425	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1426		synchronized (this) {
1427			if (checkListeners()) {
1428				switchToForeground();
1429			}
1430			this.mOnConversationUpdate = listener;
1431			this.mNotificationService.setIsInForeground(true);
1432			if (this.convChangedListenerCount < 2) {
1433				this.convChangedListenerCount++;
1434			}
1435		}
1436	}
1437
1438	public void removeOnConversationListChangedListener() {
1439		synchronized (this) {
1440			this.convChangedListenerCount--;
1441			if (this.convChangedListenerCount <= 0) {
1442				this.convChangedListenerCount = 0;
1443				this.mOnConversationUpdate = null;
1444				this.mNotificationService.setIsInForeground(false);
1445				if (checkListeners()) {
1446					switchToBackground();
1447				}
1448			}
1449		}
1450	}
1451
1452	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1453		synchronized (this) {
1454			if (checkListeners()) {
1455				switchToForeground();
1456			}
1457			this.mOnShowErrorToast = onShowErrorToast;
1458			if (this.showErrorToastListenerCount < 2) {
1459				this.showErrorToastListenerCount++;
1460			}
1461		}
1462		this.mOnShowErrorToast = onShowErrorToast;
1463	}
1464
1465	public void removeOnShowErrorToastListener() {
1466		synchronized (this) {
1467			this.showErrorToastListenerCount--;
1468			if (this.showErrorToastListenerCount <= 0) {
1469				this.showErrorToastListenerCount = 0;
1470				this.mOnShowErrorToast = null;
1471				if (checkListeners()) {
1472					switchToBackground();
1473				}
1474			}
1475		}
1476	}
1477
1478	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1479		synchronized (this) {
1480			if (checkListeners()) {
1481				switchToForeground();
1482			}
1483			this.mOnAccountUpdate = listener;
1484			if (this.accountChangedListenerCount < 2) {
1485				this.accountChangedListenerCount++;
1486			}
1487		}
1488	}
1489
1490	public void removeOnAccountListChangedListener() {
1491		synchronized (this) {
1492			this.accountChangedListenerCount--;
1493			if (this.accountChangedListenerCount <= 0) {
1494				this.mOnAccountUpdate = null;
1495				this.accountChangedListenerCount = 0;
1496				if (checkListeners()) {
1497					switchToBackground();
1498				}
1499			}
1500		}
1501	}
1502
1503	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1504		synchronized (this) {
1505			if (checkListeners()) {
1506				switchToForeground();
1507			}
1508			this.mOnCaptchaRequested = listener;
1509			if (this.captchaRequestedListenerCount < 2) {
1510				this.captchaRequestedListenerCount++;
1511			}
1512		}
1513	}
1514
1515	public void removeOnCaptchaRequestedListener() {
1516		synchronized (this) {
1517			this.captchaRequestedListenerCount--;
1518			if (this.captchaRequestedListenerCount <= 0) {
1519				this.mOnCaptchaRequested = null;
1520				this.captchaRequestedListenerCount = 0;
1521				if (checkListeners()) {
1522					switchToBackground();
1523				}
1524			}
1525		}
1526	}
1527
1528	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1529		synchronized (this) {
1530			if (checkListeners()) {
1531				switchToForeground();
1532			}
1533			this.mOnRosterUpdate = listener;
1534			if (this.rosterChangedListenerCount < 2) {
1535				this.rosterChangedListenerCount++;
1536			}
1537		}
1538	}
1539
1540	public void removeOnRosterUpdateListener() {
1541		synchronized (this) {
1542			this.rosterChangedListenerCount--;
1543			if (this.rosterChangedListenerCount <= 0) {
1544				this.rosterChangedListenerCount = 0;
1545				this.mOnRosterUpdate = null;
1546				if (checkListeners()) {
1547					switchToBackground();
1548				}
1549			}
1550		}
1551	}
1552
1553	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1554		synchronized (this) {
1555			if (checkListeners()) {
1556				switchToForeground();
1557			}
1558			this.mOnUpdateBlocklist = listener;
1559			if (this.updateBlocklistListenerCount < 2) {
1560				this.updateBlocklistListenerCount++;
1561			}
1562		}
1563	}
1564
1565	public void removeOnUpdateBlocklistListener() {
1566		synchronized (this) {
1567			this.updateBlocklistListenerCount--;
1568			if (this.updateBlocklistListenerCount <= 0) {
1569				this.updateBlocklistListenerCount = 0;
1570				this.mOnUpdateBlocklist = null;
1571				if (checkListeners()) {
1572					switchToBackground();
1573				}
1574			}
1575		}
1576	}
1577
1578	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1579		synchronized (this) {
1580			if (checkListeners()) {
1581				switchToForeground();
1582			}
1583			this.mOnKeyStatusUpdated = listener;
1584			if (this.keyStatusUpdatedListenerCount < 2) {
1585				this.keyStatusUpdatedListenerCount++;
1586			}
1587		}
1588	}
1589
1590	public void removeOnNewKeysAvailableListener() {
1591		synchronized (this) {
1592			this.keyStatusUpdatedListenerCount--;
1593			if (this.keyStatusUpdatedListenerCount <= 0) {
1594				this.keyStatusUpdatedListenerCount = 0;
1595				this.mOnKeyStatusUpdated = null;
1596				if (checkListeners()) {
1597					switchToBackground();
1598				}
1599			}
1600		}
1601	}
1602
1603	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1604		synchronized (this) {
1605			if (checkListeners()) {
1606				switchToForeground();
1607			}
1608			this.mOnMucRosterUpdate = listener;
1609			if (this.mucRosterChangedListenerCount < 2) {
1610				this.mucRosterChangedListenerCount++;
1611			}
1612		}
1613	}
1614
1615	public void removeOnMucRosterUpdateListener() {
1616		synchronized (this) {
1617			this.mucRosterChangedListenerCount--;
1618			if (this.mucRosterChangedListenerCount <= 0) {
1619				this.mucRosterChangedListenerCount = 0;
1620				this.mOnMucRosterUpdate = null;
1621				if (checkListeners()) {
1622					switchToBackground();
1623				}
1624			}
1625		}
1626	}
1627
1628	private boolean checkListeners() {
1629		return (this.mOnAccountUpdate == null
1630				&& this.mOnConversationUpdate == null
1631				&& this.mOnRosterUpdate == null
1632				&& this.mOnCaptchaRequested == null
1633				&& this.mOnUpdateBlocklist == null
1634				&& this.mOnShowErrorToast == null
1635				&& this.mOnKeyStatusUpdated == null);
1636	}
1637
1638	private void switchToForeground() {
1639		for (Conversation conversation : getConversations()) {
1640			conversation.setIncomingChatState(ChatState.ACTIVE);
1641		}
1642		for (Account account : getAccounts()) {
1643			if (account.getStatus() == Account.State.ONLINE) {
1644				XmppConnection connection = account.getXmppConnection();
1645				if (connection != null && connection.getFeatures().csi()) {
1646					connection.sendActive();
1647				}
1648			}
1649		}
1650		Log.d(Config.LOGTAG, "app switched into foreground");
1651	}
1652
1653	private void switchToBackground() {
1654		for (Account account : getAccounts()) {
1655			if (account.getStatus() == Account.State.ONLINE) {
1656				XmppConnection connection = account.getXmppConnection();
1657				if (connection != null && connection.getFeatures().csi()) {
1658					connection.sendInactive();
1659				}
1660			}
1661		}
1662		this.mNotificationService.setIsInForeground(false);
1663		Log.d(Config.LOGTAG, "app switched into background");
1664	}
1665
1666	private void connectMultiModeConversations(Account account) {
1667		List<Conversation> conversations = getConversations();
1668		for (Conversation conversation : conversations) {
1669			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1670				joinMuc(conversation, true);
1671			}
1672		}
1673	}
1674
1675	public void joinMuc(Conversation conversation) {
1676		joinMuc(conversation, false);
1677	}
1678
1679	private void joinMuc(Conversation conversation, boolean now) {
1680		Account account = conversation.getAccount();
1681		account.pendingConferenceJoins.remove(conversation);
1682		account.pendingConferenceLeaves.remove(conversation);
1683		if (account.getStatus() == Account.State.ONLINE || now) {
1684			conversation.resetMucOptions();
1685			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1686				@Override
1687				public void onConferenceConfigurationFetched(Conversation conversation) {
1688					Account account = conversation.getAccount();
1689					final String nick = conversation.getMucOptions().getProposedNick();
1690					final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1691					if (joinJid == null) {
1692						return; //safety net
1693					}
1694					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1695					PresencePacket packet = new PresencePacket();
1696					packet.setFrom(conversation.getAccount().getJid());
1697					packet.setTo(joinJid);
1698					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1699					if (conversation.getMucOptions().getPassword() != null) {
1700						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1701					}
1702
1703					if (conversation.getMucOptions().mamSupport()) {
1704						// Use MAM instead of the limited muc history to get history
1705						x.addChild("history").setAttribute("maxchars", "0");
1706					} else {
1707						// Fallback to muc history
1708						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1709					}
1710					String sig = account.getPgpSignature();
1711					if (sig != null) {
1712						packet.addChild("status").setContent("online");
1713						packet.addChild("x", "jabber:x:signed").setContent(sig);
1714					}
1715					sendPresencePacket(account, packet);
1716					fetchConferenceConfiguration(conversation);
1717					if (!joinJid.equals(conversation.getJid())) {
1718						conversation.setContactJid(joinJid);
1719						databaseBackend.updateConversation(conversation);
1720					}
1721					conversation.setHasMessagesLeftOnServer(false);
1722					if (conversation.getMucOptions().mamSupport()) {
1723						getMessageArchiveService().catchupMUC(conversation);
1724					}
1725				}
1726			});
1727
1728		} else {
1729			account.pendingConferenceJoins.add(conversation);
1730		}
1731	}
1732
1733	public void providePasswordForMuc(Conversation conversation, String password) {
1734		if (conversation.getMode() == Conversation.MODE_MULTI) {
1735			conversation.getMucOptions().setPassword(password);
1736			if (conversation.getBookmark() != null) {
1737				conversation.getBookmark().setAutojoin(true);
1738				pushBookmarks(conversation.getAccount());
1739			}
1740			databaseBackend.updateConversation(conversation);
1741			joinMuc(conversation);
1742		}
1743	}
1744
1745	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1746		final MucOptions options = conversation.getMucOptions();
1747		final Jid joinJid = options.createJoinJid(nick);
1748		if (options.online()) {
1749			Account account = conversation.getAccount();
1750			options.setOnRenameListener(new OnRenameListener() {
1751
1752				@Override
1753				public void onSuccess() {
1754					conversation.setContactJid(joinJid);
1755					databaseBackend.updateConversation(conversation);
1756					Bookmark bookmark = conversation.getBookmark();
1757					if (bookmark != null) {
1758						bookmark.setNick(nick);
1759						pushBookmarks(bookmark.getAccount());
1760					}
1761					callback.success(conversation);
1762				}
1763
1764				@Override
1765				public void onFailure() {
1766					callback.error(R.string.nick_in_use, conversation);
1767				}
1768			});
1769
1770			PresencePacket packet = new PresencePacket();
1771			packet.setTo(joinJid);
1772			packet.setFrom(conversation.getAccount().getJid());
1773
1774			String sig = account.getPgpSignature();
1775			if (sig != null) {
1776				packet.addChild("status").setContent("online");
1777				packet.addChild("x", "jabber:x:signed").setContent(sig);
1778			}
1779			sendPresencePacket(account, packet);
1780		} else {
1781			conversation.setContactJid(joinJid);
1782			databaseBackend.updateConversation(conversation);
1783			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1784				Bookmark bookmark = conversation.getBookmark();
1785				if (bookmark != null) {
1786					bookmark.setNick(nick);
1787					pushBookmarks(bookmark.getAccount());
1788				}
1789				joinMuc(conversation);
1790			}
1791		}
1792	}
1793
1794	public void leaveMuc(Conversation conversation) {
1795		leaveMuc(conversation, false);
1796	}
1797
1798	private void leaveMuc(Conversation conversation, boolean now) {
1799		Account account = conversation.getAccount();
1800		account.pendingConferenceJoins.remove(conversation);
1801		account.pendingConferenceLeaves.remove(conversation);
1802		if (account.getStatus() == Account.State.ONLINE || now) {
1803			PresencePacket packet = new PresencePacket();
1804			packet.setTo(conversation.getJid());
1805			packet.setFrom(conversation.getAccount().getJid());
1806			packet.setAttribute("type", "unavailable");
1807			sendPresencePacket(conversation.getAccount(), packet);
1808			conversation.getMucOptions().setOffline();
1809			conversation.deregisterWithBookmark();
1810			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1811					+ ": leaving muc " + conversation.getJid());
1812		} else {
1813			account.pendingConferenceLeaves.add(conversation);
1814		}
1815	}
1816
1817	private String findConferenceServer(final Account account) {
1818		String server;
1819		if (account.getXmppConnection() != null) {
1820			server = account.getXmppConnection().getMucServer();
1821			if (server != null) {
1822				return server;
1823			}
1824		}
1825		for (Account other : getAccounts()) {
1826			if (other != account && other.getXmppConnection() != null) {
1827				server = other.getXmppConnection().getMucServer();
1828				if (server != null) {
1829					return server;
1830				}
1831			}
1832		}
1833		return null;
1834	}
1835
1836	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1837		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1838		if (account.getStatus() == Account.State.ONLINE) {
1839			try {
1840				String server = findConferenceServer(account);
1841				if (server == null) {
1842					if (callback != null) {
1843						callback.error(R.string.no_conference_server_found, null);
1844					}
1845					return;
1846				}
1847				String name = new BigInteger(75, getRNG()).toString(32);
1848				Jid jid = Jid.fromParts(name, server, null);
1849				final Conversation conversation = findOrCreateConversation(account, jid, true);
1850				joinMuc(conversation);
1851				Bundle options = new Bundle();
1852				options.putString("muc#roomconfig_persistentroom", "1");
1853				options.putString("muc#roomconfig_membersonly", "1");
1854				options.putString("muc#roomconfig_publicroom", "0");
1855				options.putString("muc#roomconfig_whois", "anyone");
1856				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1857					@Override
1858					public void onPushSucceeded() {
1859						for (Jid invite : jids) {
1860							invite(conversation, invite);
1861						}
1862						if (account.countPresences() > 1) {
1863							directInvite(conversation, account.getJid().toBareJid());
1864						}
1865						if (callback != null) {
1866							callback.success(conversation);
1867						}
1868					}
1869
1870					@Override
1871					public void onPushFailed() {
1872						if (callback != null) {
1873							callback.error(R.string.conference_creation_failed, conversation);
1874						}
1875					}
1876				});
1877
1878			} catch (InvalidJidException e) {
1879				if (callback != null) {
1880					callback.error(R.string.conference_creation_failed, null);
1881				}
1882			}
1883		} else {
1884			if (callback != null) {
1885				callback.error(R.string.not_connected_try_again, null);
1886			}
1887		}
1888	}
1889
1890	public void fetchConferenceConfiguration(final Conversation conversation) {
1891		fetchConferenceConfiguration(conversation, null);
1892	}
1893
1894	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1895		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1896		request.setTo(conversation.getJid().toBareJid());
1897		request.query("http://jabber.org/protocol/disco#info");
1898		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1899			@Override
1900			public void onIqPacketReceived(Account account, IqPacket packet) {
1901				if (packet.getType() == IqPacket.TYPE.RESULT) {
1902					ArrayList<String> features = new ArrayList<>();
1903					for (Element child : packet.query().getChildren()) {
1904						if (child != null && child.getName().equals("feature")) {
1905							String var = child.getAttribute("var");
1906							if (var != null) {
1907								features.add(var);
1908							}
1909						}
1910					}
1911					conversation.getMucOptions().updateFeatures(features);
1912					if (callback != null) {
1913						callback.onConferenceConfigurationFetched(conversation);
1914					}
1915					updateConversationUi();
1916				}
1917			}
1918		});
1919	}
1920
1921	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1922		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1923		request.setTo(conversation.getJid().toBareJid());
1924		request.query("http://jabber.org/protocol/muc#owner");
1925		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1926			@Override
1927			public void onIqPacketReceived(Account account, IqPacket packet) {
1928				if (packet.getType() == IqPacket.TYPE.RESULT) {
1929					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1930					for (Field field : data.getFields()) {
1931						if (options.containsKey(field.getFieldName())) {
1932							field.setValue(options.getString(field.getFieldName()));
1933						}
1934					}
1935					data.submit();
1936					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1937					set.setTo(conversation.getJid().toBareJid());
1938					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1939					sendIqPacket(account, set, new OnIqPacketReceived() {
1940						@Override
1941						public void onIqPacketReceived(Account account, IqPacket packet) {
1942							if (callback != null) {
1943								if (packet.getType() == IqPacket.TYPE.RESULT) {
1944									callback.onPushSucceeded();
1945								} else {
1946									callback.onPushFailed();
1947								}
1948							}
1949						}
1950					});
1951				} else {
1952					if (callback != null) {
1953						callback.onPushFailed();
1954					}
1955				}
1956			}
1957		});
1958	}
1959
1960	public void pushSubjectToConference(final Conversation conference, final String subject) {
1961		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1962		this.sendMessagePacket(conference.getAccount(), packet);
1963		final MucOptions mucOptions = conference.getMucOptions();
1964		final MucOptions.User self = mucOptions.getSelf();
1965		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1966			Bundle options = new Bundle();
1967			options.putString("muc#roomconfig_persistentroom", "1");
1968			this.pushConferenceConfiguration(conference, options, null);
1969		}
1970	}
1971
1972	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1973		final Jid jid = user.toBareJid();
1974		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1975		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1976			@Override
1977			public void onIqPacketReceived(Account account, IqPacket packet) {
1978				if (packet.getType() == IqPacket.TYPE.RESULT) {
1979					callback.onAffiliationChangedSuccessful(jid);
1980				} else {
1981					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1982				}
1983			}
1984		});
1985	}
1986
1987	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1988		List<Jid> jids = new ArrayList<>();
1989		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1990			if (user.getAffiliation() == before && user.getJid() != null) {
1991				jids.add(user.getJid());
1992			}
1993		}
1994		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1995		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1996	}
1997
1998	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1999		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2000		Log.d(Config.LOGTAG, request.toString());
2001		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2002			@Override
2003			public void onIqPacketReceived(Account account, IqPacket packet) {
2004				Log.d(Config.LOGTAG, packet.toString());
2005				if (packet.getType() == IqPacket.TYPE.RESULT) {
2006					callback.onRoleChangedSuccessful(nick);
2007				} else {
2008					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2009				}
2010			}
2011		});
2012	}
2013
2014	private void disconnect(Account account, boolean force) {
2015		if ((account.getStatus() == Account.State.ONLINE)
2016				|| (account.getStatus() == Account.State.DISABLED)) {
2017			if (!force) {
2018				List<Conversation> conversations = getConversations();
2019				for (Conversation conversation : conversations) {
2020					if (conversation.getAccount() == account) {
2021						if (conversation.getMode() == Conversation.MODE_MULTI) {
2022							leaveMuc(conversation, true);
2023						} else {
2024							if (conversation.endOtrIfNeeded()) {
2025								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2026										+ ": ended otr session with "
2027										+ conversation.getJid());
2028							}
2029						}
2030					}
2031				}
2032				sendOfflinePresence(account);
2033			}
2034			account.getXmppConnection().disconnect(force);
2035		}
2036	}
2037
2038	@Override
2039	public IBinder onBind(Intent intent) {
2040		return mBinder;
2041	}
2042
2043	public void updateMessage(Message message) {
2044		databaseBackend.updateMessage(message);
2045		updateConversationUi();
2046	}
2047
2048	protected void syncDirtyContacts(Account account) {
2049		for (Contact contact : account.getRoster().getContacts()) {
2050			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2051				pushContactToServer(contact);
2052			}
2053			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2054				deleteContactOnServer(contact);
2055			}
2056		}
2057	}
2058
2059	public void createContact(Contact contact) {
2060		SharedPreferences sharedPref = getPreferences();
2061		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
2062		if (autoGrant) {
2063			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2064			contact.setOption(Contact.Options.ASKING);
2065		}
2066		pushContactToServer(contact);
2067	}
2068
2069	public void onOtrSessionEstablished(Conversation conversation) {
2070		final Account account = conversation.getAccount();
2071		final Session otrSession = conversation.getOtrSession();
2072		Log.d(Config.LOGTAG,
2073				account.getJid().toBareJid() + " otr session established with "
2074						+ conversation.getJid() + "/"
2075						+ otrSession.getSessionID().getUserID());
2076		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2077
2078			@Override
2079			public void onMessageFound(Message message) {
2080				SessionID id = otrSession.getSessionID();
2081				try {
2082					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2083				} catch (InvalidJidException e) {
2084					return;
2085				}
2086				if (message.needsUploading()) {
2087					mJingleConnectionManager.createNewConnection(message);
2088				} else {
2089					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2090					if (outPacket != null) {
2091						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2092						message.setStatus(Message.STATUS_SEND);
2093						databaseBackend.updateMessage(message);
2094						sendMessagePacket(account, outPacket);
2095					}
2096				}
2097				updateConversationUi();
2098			}
2099		});
2100	}
2101
2102	public boolean renewSymmetricKey(Conversation conversation) {
2103		Account account = conversation.getAccount();
2104		byte[] symmetricKey = new byte[32];
2105		this.mRandom.nextBytes(symmetricKey);
2106		Session otrSession = conversation.getOtrSession();
2107		if (otrSession != null) {
2108			MessagePacket packet = new MessagePacket();
2109			packet.setType(MessagePacket.TYPE_CHAT);
2110			packet.setFrom(account.getJid());
2111			MessageGenerator.addMessageHints(packet);
2112			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2113					+ otrSession.getSessionID().getUserID());
2114			try {
2115				packet.setBody(otrSession
2116						.transformSending(CryptoHelper.FILETRANSFER
2117								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2118				sendMessagePacket(account, packet);
2119				conversation.setSymmetricKey(symmetricKey);
2120				return true;
2121			} catch (OtrException e) {
2122				return false;
2123			}
2124		}
2125		return false;
2126	}
2127
2128	public void pushContactToServer(final Contact contact) {
2129		contact.resetOption(Contact.Options.DIRTY_DELETE);
2130		contact.setOption(Contact.Options.DIRTY_PUSH);
2131		final Account account = contact.getAccount();
2132		if (account.getStatus() == Account.State.ONLINE) {
2133			final boolean ask = contact.getOption(Contact.Options.ASKING);
2134			final boolean sendUpdates = contact
2135					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2136					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2137			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2138			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2139			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2140			if (sendUpdates) {
2141				sendPresencePacket(account,
2142						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2143			}
2144			if (ask) {
2145				sendPresencePacket(account,
2146						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2147			}
2148		}
2149	}
2150
2151	public void publishAvatar(final Account account,
2152							  final Uri image,
2153							  final UiCallback<Avatar> callback) {
2154		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2155		final int size = Config.AVATAR_SIZE;
2156		final Avatar avatar = getFileBackend()
2157				.getPepAvatar(image, size, format);
2158		if (avatar != null) {
2159			avatar.height = size;
2160			avatar.width = size;
2161			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2162				avatar.type = "image/webp";
2163			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2164				avatar.type = "image/jpeg";
2165			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2166				avatar.type = "image/png";
2167			}
2168			if (!getFileBackend().save(avatar)) {
2169				callback.error(R.string.error_saving_avatar, avatar);
2170				return;
2171			}
2172			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2173			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2174
2175				@Override
2176				public void onIqPacketReceived(Account account, IqPacket result) {
2177					if (result.getType() == IqPacket.TYPE.RESULT) {
2178						final IqPacket packet = XmppConnectionService.this.mIqGenerator
2179								.publishAvatarMetadata(avatar);
2180						sendIqPacket(account, packet, new OnIqPacketReceived() {
2181							@Override
2182							public void onIqPacketReceived(Account account, IqPacket result) {
2183								if (result.getType() == IqPacket.TYPE.RESULT) {
2184									if (account.setAvatar(avatar.getFilename())) {
2185										getAvatarService().clear(account);
2186										databaseBackend.updateAccount(account);
2187									}
2188									callback.success(avatar);
2189								} else {
2190									callback.error(
2191											R.string.error_publish_avatar_server_reject,
2192											avatar);
2193								}
2194							}
2195						});
2196					} else {
2197						callback.error(
2198								R.string.error_publish_avatar_server_reject,
2199								avatar);
2200					}
2201				}
2202			});
2203		} else {
2204			callback.error(R.string.error_publish_avatar_converting, null);
2205		}
2206	}
2207
2208	public void fetchAvatar(Account account, Avatar avatar) {
2209		fetchAvatar(account, avatar, null);
2210	}
2211
2212	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2213		final String KEY = generateFetchKey(account, avatar);
2214		synchronized (this.mInProgressAvatarFetches) {
2215			if (this.mInProgressAvatarFetches.contains(KEY)) {
2216				return;
2217			} else {
2218				switch (avatar.origin) {
2219					case PEP:
2220						this.mInProgressAvatarFetches.add(KEY);
2221						fetchAvatarPep(account, avatar, callback);
2222						break;
2223					case VCARD:
2224						this.mInProgressAvatarFetches.add(KEY);
2225						fetchAvatarVcard(account, avatar, callback);
2226						break;
2227				}
2228			}
2229		}
2230	}
2231
2232	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2233		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2234		sendIqPacket(account, packet, new OnIqPacketReceived() {
2235
2236			@Override
2237			public void onIqPacketReceived(Account account, IqPacket result) {
2238				synchronized (mInProgressAvatarFetches) {
2239					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2240				}
2241				final String ERROR = account.getJid().toBareJid()
2242						+ ": fetching avatar for " + avatar.owner + " failed ";
2243				if (result.getType() == IqPacket.TYPE.RESULT) {
2244					avatar.image = mIqParser.avatarData(result);
2245					if (avatar.image != null) {
2246						if (getFileBackend().save(avatar)) {
2247							if (account.getJid().toBareJid().equals(avatar.owner)) {
2248								if (account.setAvatar(avatar.getFilename())) {
2249									databaseBackend.updateAccount(account);
2250								}
2251								getAvatarService().clear(account);
2252								updateConversationUi();
2253								updateAccountUi();
2254							} else {
2255								Contact contact = account.getRoster()
2256										.getContact(avatar.owner);
2257								contact.setAvatar(avatar);
2258								getAvatarService().clear(contact);
2259								updateConversationUi();
2260								updateRosterUi();
2261							}
2262							if (callback != null) {
2263								callback.success(avatar);
2264							}
2265							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2266									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2267							return;
2268						}
2269					} else {
2270
2271						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2272					}
2273				} else {
2274					Element error = result.findChild("error");
2275					if (error == null) {
2276						Log.d(Config.LOGTAG, ERROR + "(server error)");
2277					} else {
2278						Log.d(Config.LOGTAG, ERROR + error.toString());
2279					}
2280				}
2281				if (callback != null) {
2282					callback.error(0, null);
2283				}
2284
2285			}
2286		});
2287	}
2288
2289	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2290		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2291		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2292			@Override
2293			public void onIqPacketReceived(Account account, IqPacket packet) {
2294				synchronized (mInProgressAvatarFetches) {
2295					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2296				}
2297				if (packet.getType() == IqPacket.TYPE.RESULT) {
2298					Element vCard = packet.findChild("vCard", "vcard-temp");
2299					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2300					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2301					if (image != null) {
2302						avatar.image = image;
2303						if (getFileBackend().save(avatar)) {
2304							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2305									+ ": successfully fetched vCard avatar for " + avatar.owner);
2306							Contact contact = account.getRoster()
2307									.getContact(avatar.owner);
2308							contact.setAvatar(avatar);
2309							getAvatarService().clear(contact);
2310							updateConversationUi();
2311							updateRosterUi();
2312						}
2313					}
2314				}
2315			}
2316		});
2317	}
2318
2319	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2320		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2321		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2322
2323			@Override
2324			public void onIqPacketReceived(Account account, IqPacket packet) {
2325				if (packet.getType() == IqPacket.TYPE.RESULT) {
2326					Element pubsub = packet.findChild("pubsub",
2327							"http://jabber.org/protocol/pubsub");
2328					if (pubsub != null) {
2329						Element items = pubsub.findChild("items");
2330						if (items != null) {
2331							Avatar avatar = Avatar.parseMetadata(items);
2332							if (avatar != null) {
2333								avatar.owner = account.getJid().toBareJid();
2334								if (fileBackend.isAvatarCached(avatar)) {
2335									if (account.setAvatar(avatar.getFilename())) {
2336										databaseBackend.updateAccount(account);
2337									}
2338									getAvatarService().clear(account);
2339									callback.success(avatar);
2340								} else {
2341									fetchAvatarPep(account, avatar, callback);
2342								}
2343								return;
2344							}
2345						}
2346					}
2347				}
2348				callback.error(0, null);
2349			}
2350		});
2351	}
2352
2353	public void deleteContactOnServer(Contact contact) {
2354		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2355		contact.resetOption(Contact.Options.DIRTY_PUSH);
2356		contact.setOption(Contact.Options.DIRTY_DELETE);
2357		Account account = contact.getAccount();
2358		if (account.getStatus() == Account.State.ONLINE) {
2359			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2360			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2361			item.setAttribute("jid", contact.getJid().toString());
2362			item.setAttribute("subscription", "remove");
2363			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2364		}
2365	}
2366
2367	public void updateConversation(Conversation conversation) {
2368		this.databaseBackend.updateConversation(conversation);
2369	}
2370
2371	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2372		synchronized (account) {
2373			if (account.getXmppConnection() != null) {
2374				disconnect(account, force);
2375			}
2376			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2377
2378				synchronized (this.mInProgressAvatarFetches) {
2379					for (Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
2380						final String KEY = iterator.next();
2381						if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
2382							iterator.remove();
2383						}
2384					}
2385				}
2386
2387				if (account.getXmppConnection() == null) {
2388					account.setXmppConnection(createConnection(account));
2389				} else if (!force) {
2390					try {
2391						Log.d(Config.LOGTAG, "wait for disconnect");
2392						Thread.sleep(500); //sleep  wait for disconnect
2393					} catch (InterruptedException e) {
2394						//ignored
2395					}
2396				}
2397				Thread thread = new Thread(account.getXmppConnection());
2398				account.getXmppConnection().setInteractive(interactive);
2399				thread.start();
2400				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2401			} else {
2402				account.getRoster().clearPresences();
2403				account.setXmppConnection(null);
2404			}
2405		}
2406	}
2407
2408	public void reconnectAccountInBackground(final Account account) {
2409		new Thread(new Runnable() {
2410			@Override
2411			public void run() {
2412				reconnectAccount(account, false, true);
2413			}
2414		}).start();
2415	}
2416
2417	public void invite(Conversation conversation, Jid contact) {
2418		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2419		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2420		sendMessagePacket(conversation.getAccount(), packet);
2421	}
2422
2423	public void directInvite(Conversation conversation, Jid jid) {
2424		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2425		sendMessagePacket(conversation.getAccount(), packet);
2426	}
2427
2428	public void resetSendingToWaiting(Account account) {
2429		for (Conversation conversation : getConversations()) {
2430			if (conversation.getAccount() == account) {
2431				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2432
2433					@Override
2434					public void onMessageFound(Message message) {
2435						markMessage(message, Message.STATUS_WAITING);
2436					}
2437				});
2438			}
2439		}
2440	}
2441
2442	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2443		if (uuid == null) {
2444			return null;
2445		}
2446		for (Conversation conversation : getConversations()) {
2447			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2448				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2449				if (message != null) {
2450					markMessage(message, status);
2451				}
2452				return message;
2453			}
2454		}
2455		return null;
2456	}
2457
2458	public boolean markMessage(Conversation conversation, String uuid, int status) {
2459		if (uuid == null) {
2460			return false;
2461		} else {
2462			Message message = conversation.findSentMessageWithUuid(uuid);
2463			if (message != null) {
2464				markMessage(message, status);
2465				return true;
2466			} else {
2467				return false;
2468			}
2469		}
2470	}
2471
2472	public void markMessage(Message message, int status) {
2473		if (status == Message.STATUS_SEND_FAILED
2474				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2475				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2476			return;
2477		}
2478		message.setStatus(status);
2479		databaseBackend.updateMessage(message);
2480		updateConversationUi();
2481	}
2482
2483	public SharedPreferences getPreferences() {
2484		return PreferenceManager
2485				.getDefaultSharedPreferences(getApplicationContext());
2486	}
2487
2488	public boolean forceEncryption() {
2489		return getPreferences().getBoolean("force_encryption", false);
2490	}
2491
2492	public boolean confirmMessages() {
2493		return getPreferences().getBoolean("confirm_messages", true);
2494	}
2495
2496	public boolean sendChatStates() {
2497		return getPreferences().getBoolean("chat_states", false);
2498	}
2499
2500	public boolean saveEncryptedMessages() {
2501		return !getPreferences().getBoolean("dont_save_encrypted", false);
2502	}
2503
2504	public boolean indicateReceived() {
2505		return getPreferences().getBoolean("indicate_received", false);
2506	}
2507
2508	public int unreadCount() {
2509		int count = 0;
2510		for (Conversation conversation : getConversations()) {
2511			count += conversation.unreadCount();
2512		}
2513		return count;
2514	}
2515
2516
2517	public void showErrorToastInUi(int resId) {
2518		if (mOnShowErrorToast != null) {
2519			mOnShowErrorToast.onShowErrorToast(resId);
2520		}
2521	}
2522
2523	public void updateConversationUi() {
2524		if (mOnConversationUpdate != null) {
2525			mOnConversationUpdate.onConversationUpdate();
2526		}
2527	}
2528
2529	public void updateAccountUi() {
2530		if (mOnAccountUpdate != null) {
2531			mOnAccountUpdate.onAccountUpdate();
2532		}
2533	}
2534
2535	public void updateRosterUi() {
2536		if (mOnRosterUpdate != null) {
2537			mOnRosterUpdate.onRosterUpdate();
2538		}
2539	}
2540
2541	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2542		boolean rc = false;
2543		if (mOnCaptchaRequested != null) {
2544			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2545			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2546					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2547
2548			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2549			rc = true;
2550		}
2551
2552		return rc;
2553	}
2554
2555	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2556		if (mOnUpdateBlocklist != null) {
2557			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2558		}
2559	}
2560
2561	public void updateMucRosterUi() {
2562		if (mOnMucRosterUpdate != null) {
2563			mOnMucRosterUpdate.onMucRosterUpdate();
2564		}
2565	}
2566
2567	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2568		if (mOnKeyStatusUpdated != null) {
2569			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2570		}
2571	}
2572
2573	public Account findAccountByJid(final Jid accountJid) {
2574		for (Account account : this.accounts) {
2575			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2576				return account;
2577			}
2578		}
2579		return null;
2580	}
2581
2582	public Conversation findConversationByUuid(String uuid) {
2583		for (Conversation conversation : getConversations()) {
2584			if (conversation.getUuid().equals(uuid)) {
2585				return conversation;
2586			}
2587		}
2588		return null;
2589	}
2590
2591	public void markRead(final Conversation conversation) {
2592		mNotificationService.clear(conversation);
2593		for (Message message : conversation.markRead()) {
2594			databaseBackend.updateMessage(message);
2595		}
2596		updateUnreadCountBadge();
2597	}
2598
2599	public synchronized void updateUnreadCountBadge() {
2600		int count = unreadCount();
2601		if (unreadCount != count) {
2602			Log.d(Config.LOGTAG, "update unread count to " + count);
2603			if (count > 0) {
2604				ShortcutBadger.with(getApplicationContext()).count(count);
2605			} else {
2606				ShortcutBadger.with(getApplicationContext()).remove();
2607			}
2608			unreadCount = count;
2609		}
2610	}
2611
2612	public void sendReadMarker(final Conversation conversation) {
2613		final Message markable = conversation.getLatestMarkableMessage();
2614		this.markRead(conversation);
2615		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2616			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2617			Account account = conversation.getAccount();
2618			final Jid to = markable.getCounterpart();
2619			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2620			this.sendMessagePacket(conversation.getAccount(), packet);
2621		}
2622		updateConversationUi();
2623	}
2624
2625	public SecureRandom getRNG() {
2626		return this.mRandom;
2627	}
2628
2629	public MemorizingTrustManager getMemorizingTrustManager() {
2630		return this.mMemorizingTrustManager;
2631	}
2632
2633	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2634		this.mMemorizingTrustManager = trustManager;
2635	}
2636
2637	public void updateMemorizingTrustmanager() {
2638		final MemorizingTrustManager tm;
2639		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2640		if (dontTrustSystemCAs) {
2641			tm = new MemorizingTrustManager(getApplicationContext(), null);
2642		} else {
2643			tm = new MemorizingTrustManager(getApplicationContext());
2644		}
2645		setMemorizingTrustManager(tm);
2646	}
2647
2648	public PowerManager getPowerManager() {
2649		return this.pm;
2650	}
2651
2652	public LruCache<String, Bitmap> getBitmapCache() {
2653		return this.mBitmapCache;
2654	}
2655
2656	public void syncRosterToDisk(final Account account) {
2657		Runnable runnable = new Runnable() {
2658
2659			@Override
2660			public void run() {
2661				databaseBackend.writeRoster(account.getRoster());
2662			}
2663		};
2664		mDatabaseExecutor.execute(runnable);
2665
2666	}
2667
2668	public List<String> getKnownHosts() {
2669		final List<String> hosts = new ArrayList<>();
2670		for (final Account account : getAccounts()) {
2671			if (!hosts.contains(account.getServer().toString())) {
2672				hosts.add(account.getServer().toString());
2673			}
2674			for (final Contact contact : account.getRoster().getContacts()) {
2675				if (contact.showInRoster()) {
2676					final String server = contact.getServer().toString();
2677					if (server != null && !hosts.contains(server)) {
2678						hosts.add(server);
2679					}
2680				}
2681			}
2682		}
2683		return hosts;
2684	}
2685
2686	public List<String> getKnownConferenceHosts() {
2687		final ArrayList<String> mucServers = new ArrayList<>();
2688		for (final Account account : accounts) {
2689			if (account.getXmppConnection() != null) {
2690				final String server = account.getXmppConnection().getMucServer();
2691				if (server != null && !mucServers.contains(server)) {
2692					mucServers.add(server);
2693				}
2694			}
2695		}
2696		return mucServers;
2697	}
2698
2699	public void sendMessagePacket(Account account, MessagePacket packet) {
2700		XmppConnection connection = account.getXmppConnection();
2701		if (connection != null) {
2702			connection.sendMessagePacket(packet);
2703		}
2704	}
2705
2706	public void sendPresencePacket(Account account, PresencePacket packet) {
2707		XmppConnection connection = account.getXmppConnection();
2708		if (connection != null) {
2709			connection.sendPresencePacket(packet);
2710		}
2711	}
2712
2713	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2714		XmppConnection connection = account.getXmppConnection();
2715		if (connection != null) {
2716			connection.sendCaptchaRegistryRequest(id, data);
2717		}
2718	}
2719
2720	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2721		final XmppConnection connection = account.getXmppConnection();
2722		if (connection != null) {
2723			connection.sendIqPacket(packet, callback);
2724		}
2725	}
2726
2727	public void sendPresence(final Account account) {
2728		sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2729	}
2730
2731	public void refreshAllPresences() {
2732		for (Account account : getAccounts()) {
2733			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2734				sendPresence(account);
2735			}
2736		}
2737	}
2738
2739	public void sendOfflinePresence(final Account account) {
2740		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2741	}
2742
2743	public MessageGenerator getMessageGenerator() {
2744		return this.mMessageGenerator;
2745	}
2746
2747	public PresenceGenerator getPresenceGenerator() {
2748		return this.mPresenceGenerator;
2749	}
2750
2751	public IqGenerator getIqGenerator() {
2752		return this.mIqGenerator;
2753	}
2754
2755	public IqParser getIqParser() {
2756		return this.mIqParser;
2757	}
2758
2759	public JingleConnectionManager getJingleConnectionManager() {
2760		return this.mJingleConnectionManager;
2761	}
2762
2763	public MessageArchiveService getMessageArchiveService() {
2764		return this.mMessageArchiveService;
2765	}
2766
2767	public List<Contact> findContacts(Jid jid) {
2768		ArrayList<Contact> contacts = new ArrayList<>();
2769		for (Account account : getAccounts()) {
2770			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2771				Contact contact = account.getRoster().getContactFromRoster(jid);
2772				if (contact != null) {
2773					contacts.add(contact);
2774				}
2775			}
2776		}
2777		return contacts;
2778	}
2779
2780	public NotificationService getNotificationService() {
2781		return this.mNotificationService;
2782	}
2783
2784	public HttpConnectionManager getHttpConnectionManager() {
2785		return this.mHttpConnectionManager;
2786	}
2787
2788	public void resendFailedMessages(final Message message) {
2789		final Collection<Message> messages = new ArrayList<>();
2790		Message current = message;
2791		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2792			messages.add(current);
2793			if (current.mergeable(current.next())) {
2794				current = current.next();
2795			} else {
2796				break;
2797			}
2798		}
2799		for (final Message msg : messages) {
2800			msg.setTime(System.currentTimeMillis());
2801			markMessage(msg, Message.STATUS_WAITING);
2802			this.resendMessage(msg, false);
2803		}
2804	}
2805
2806	public void clearConversationHistory(final Conversation conversation) {
2807		conversation.clearMessages();
2808		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2809		conversation.resetLastMessageTransmitted();
2810		new Thread(new Runnable() {
2811			@Override
2812			public void run() {
2813				databaseBackend.deleteMessagesInConversation(conversation);
2814			}
2815		}).start();
2816	}
2817
2818	public void sendBlockRequest(final Blockable blockable) {
2819		if (blockable != null && blockable.getBlockedJid() != null) {
2820			final Jid jid = blockable.getBlockedJid();
2821			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2822
2823				@Override
2824				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2825					if (packet.getType() == IqPacket.TYPE.RESULT) {
2826						account.getBlocklist().add(jid);
2827						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2828					}
2829				}
2830			});
2831		}
2832	}
2833
2834	public void sendUnblockRequest(final Blockable blockable) {
2835		if (blockable != null && blockable.getJid() != null) {
2836			final Jid jid = blockable.getBlockedJid();
2837			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2838				@Override
2839				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2840					if (packet.getType() == IqPacket.TYPE.RESULT) {
2841						account.getBlocklist().remove(jid);
2842						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2843					}
2844				}
2845			});
2846		}
2847	}
2848
2849	public interface OnAccountCreated {
2850		void onAccountCreated(Account account);
2851
2852		void informUser(int r);
2853	}
2854
2855	public interface OnMoreMessagesLoaded {
2856		void onMoreMessagesLoaded(int count, Conversation conversation);
2857
2858		void informUser(int r);
2859	}
2860
2861	public interface OnAccountPasswordChanged {
2862		void onPasswordChangeSucceeded();
2863
2864		void onPasswordChangeFailed();
2865	}
2866
2867	public interface OnAffiliationChanged {
2868		void onAffiliationChangedSuccessful(Jid jid);
2869
2870		void onAffiliationChangeFailed(Jid jid, int resId);
2871	}
2872
2873	public interface OnRoleChanged {
2874		void onRoleChangedSuccessful(String nick);
2875
2876		void onRoleChangeFailed(String nick, int resid);
2877	}
2878
2879	public interface OnConversationUpdate {
2880		void onConversationUpdate();
2881	}
2882
2883	public interface OnAccountUpdate {
2884		void onAccountUpdate();
2885	}
2886
2887	public interface OnCaptchaRequested {
2888		void onCaptchaRequested(Account account,
2889								String id,
2890								Data data,
2891								Bitmap captcha);
2892	}
2893
2894	public interface OnRosterUpdate {
2895		void onRosterUpdate();
2896	}
2897
2898	public interface OnMucRosterUpdate {
2899		void onMucRosterUpdate();
2900	}
2901
2902	public interface OnConferenceConfigurationFetched {
2903		void onConferenceConfigurationFetched(Conversation conversation);
2904	}
2905
2906	public interface OnConferenceOptionsPushed {
2907		void onPushSucceeded();
2908
2909		void onPushFailed();
2910	}
2911
2912	public interface OnShowErrorToast {
2913		void onShowErrorToast(int resId);
2914	}
2915
2916	public class XmppConnectionBinder extends Binder {
2917		public XmppConnectionService getService() {
2918			return XmppConnectionService.this;
2919		}
2920	}
2921}