XmppConnectionService.java

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