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