XmppConnectionService.java

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