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