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.IOpenPgpService;
  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(IOpenPgpService 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						account.initAccountServices(XmppConnectionService.this);
1092						databaseBackend.readRoster(account.getRoster());
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						createAccount(account);
1348						callback.onAccountCreated(account);
1349						if (Config.X509_VERIFICATION) {
1350							try {
1351								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1352							} catch (CertificateException e) {
1353								callback.informUser(R.string.certificate_chain_is_not_trusted);
1354							}
1355						}
1356					} else {
1357						callback.informUser(R.string.account_already_exists);
1358					}
1359				} catch (Exception e) {
1360					e.printStackTrace();
1361					callback.informUser(R.string.unable_to_parse_certificate);
1362				}
1363			}
1364		}).start();
1365
1366	}
1367
1368	public void updateKeyInAccount(final Account account, final String alias) {
1369		Log.d(Config.LOGTAG, "update key in account " + alias);
1370		try {
1371			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1372			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1373			if (account.getJid().toBareJid().equals(info.first)) {
1374				account.setPrivateKeyAlias(alias);
1375				databaseBackend.updateAccount(account);
1376				if (Config.X509_VERIFICATION) {
1377					try {
1378						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1379					} catch (CertificateException e) {
1380						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1381					}
1382					account.getAxolotlService().regenerateKeys(true);
1383				}
1384			} else {
1385				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1386			}
1387		} catch (Exception e) {
1388			e.printStackTrace();
1389		}
1390	}
1391
1392	public void updateAccount(final Account account) {
1393		this.statusListener.onStatusChanged(account);
1394		databaseBackend.updateAccount(account);
1395		reconnectAccountInBackground(account);
1396		updateAccountUi();
1397		getNotificationService().updateErrorNotification();
1398	}
1399
1400	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1401		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1402		sendIqPacket(account, iq, new OnIqPacketReceived() {
1403			@Override
1404			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1405				if (packet.getType() == IqPacket.TYPE.RESULT) {
1406					account.setPassword(newPassword);
1407					databaseBackend.updateAccount(account);
1408					callback.onPasswordChangeSucceeded();
1409				} else {
1410					callback.onPasswordChangeFailed();
1411				}
1412			}
1413		});
1414	}
1415
1416	public void deleteAccount(final Account account) {
1417		synchronized (this.conversations) {
1418			for (final Conversation conversation : conversations) {
1419				if (conversation.getAccount() == account) {
1420					if (conversation.getMode() == Conversation.MODE_MULTI) {
1421						leaveMuc(conversation);
1422					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1423						conversation.endOtrIfNeeded();
1424					}
1425					conversations.remove(conversation);
1426				}
1427			}
1428			if (account.getXmppConnection() != null) {
1429				this.disconnect(account, true);
1430			}
1431			databaseBackend.deleteAccount(account);
1432			this.accounts.remove(account);
1433			updateAccountUi();
1434			getNotificationService().updateErrorNotification();
1435		}
1436	}
1437
1438	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1439		synchronized (this) {
1440			if (checkListeners()) {
1441				switchToForeground();
1442			}
1443			this.mOnConversationUpdate = listener;
1444			this.mNotificationService.setIsInForeground(true);
1445			if (this.convChangedListenerCount < 2) {
1446				this.convChangedListenerCount++;
1447			}
1448		}
1449	}
1450
1451	public void removeOnConversationListChangedListener() {
1452		synchronized (this) {
1453			this.convChangedListenerCount--;
1454			if (this.convChangedListenerCount <= 0) {
1455				this.convChangedListenerCount = 0;
1456				this.mOnConversationUpdate = null;
1457				this.mNotificationService.setIsInForeground(false);
1458				if (checkListeners()) {
1459					switchToBackground();
1460				}
1461			}
1462		}
1463	}
1464
1465	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1466		synchronized (this) {
1467			if (checkListeners()) {
1468				switchToForeground();
1469			}
1470			this.mOnShowErrorToast = onShowErrorToast;
1471			if (this.showErrorToastListenerCount < 2) {
1472				this.showErrorToastListenerCount++;
1473			}
1474		}
1475		this.mOnShowErrorToast = onShowErrorToast;
1476	}
1477
1478	public void removeOnShowErrorToastListener() {
1479		synchronized (this) {
1480			this.showErrorToastListenerCount--;
1481			if (this.showErrorToastListenerCount <= 0) {
1482				this.showErrorToastListenerCount = 0;
1483				this.mOnShowErrorToast = null;
1484				if (checkListeners()) {
1485					switchToBackground();
1486				}
1487			}
1488		}
1489	}
1490
1491	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1492		synchronized (this) {
1493			if (checkListeners()) {
1494				switchToForeground();
1495			}
1496			this.mOnAccountUpdate = listener;
1497			if (this.accountChangedListenerCount < 2) {
1498				this.accountChangedListenerCount++;
1499			}
1500		}
1501	}
1502
1503	public void removeOnAccountListChangedListener() {
1504		synchronized (this) {
1505			this.accountChangedListenerCount--;
1506			if (this.accountChangedListenerCount <= 0) {
1507				this.mOnAccountUpdate = null;
1508				this.accountChangedListenerCount = 0;
1509				if (checkListeners()) {
1510					switchToBackground();
1511				}
1512			}
1513		}
1514	}
1515
1516	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1517		synchronized (this) {
1518			if (checkListeners()) {
1519				switchToForeground();
1520			}
1521			this.mOnCaptchaRequested = listener;
1522			if (this.captchaRequestedListenerCount < 2) {
1523				this.captchaRequestedListenerCount++;
1524			}
1525		}
1526	}
1527
1528	public void removeOnCaptchaRequestedListener() {
1529		synchronized (this) {
1530			this.captchaRequestedListenerCount--;
1531			if (this.captchaRequestedListenerCount <= 0) {
1532				this.mOnCaptchaRequested = null;
1533				this.captchaRequestedListenerCount = 0;
1534				if (checkListeners()) {
1535					switchToBackground();
1536				}
1537			}
1538		}
1539	}
1540
1541	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1542		synchronized (this) {
1543			if (checkListeners()) {
1544				switchToForeground();
1545			}
1546			this.mOnRosterUpdate = listener;
1547			if (this.rosterChangedListenerCount < 2) {
1548				this.rosterChangedListenerCount++;
1549			}
1550		}
1551	}
1552
1553	public void removeOnRosterUpdateListener() {
1554		synchronized (this) {
1555			this.rosterChangedListenerCount--;
1556			if (this.rosterChangedListenerCount <= 0) {
1557				this.rosterChangedListenerCount = 0;
1558				this.mOnRosterUpdate = null;
1559				if (checkListeners()) {
1560					switchToBackground();
1561				}
1562			}
1563		}
1564	}
1565
1566	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1567		synchronized (this) {
1568			if (checkListeners()) {
1569				switchToForeground();
1570			}
1571			this.mOnUpdateBlocklist = listener;
1572			if (this.updateBlocklistListenerCount < 2) {
1573				this.updateBlocklistListenerCount++;
1574			}
1575		}
1576	}
1577
1578	public void removeOnUpdateBlocklistListener() {
1579		synchronized (this) {
1580			this.updateBlocklistListenerCount--;
1581			if (this.updateBlocklistListenerCount <= 0) {
1582				this.updateBlocklistListenerCount = 0;
1583				this.mOnUpdateBlocklist = null;
1584				if (checkListeners()) {
1585					switchToBackground();
1586				}
1587			}
1588		}
1589	}
1590
1591	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1592		synchronized (this) {
1593			if (checkListeners()) {
1594				switchToForeground();
1595			}
1596			this.mOnKeyStatusUpdated = listener;
1597			if (this.keyStatusUpdatedListenerCount < 2) {
1598				this.keyStatusUpdatedListenerCount++;
1599			}
1600		}
1601	}
1602
1603	public void removeOnNewKeysAvailableListener() {
1604		synchronized (this) {
1605			this.keyStatusUpdatedListenerCount--;
1606			if (this.keyStatusUpdatedListenerCount <= 0) {
1607				this.keyStatusUpdatedListenerCount = 0;
1608				this.mOnKeyStatusUpdated = null;
1609				if (checkListeners()) {
1610					switchToBackground();
1611				}
1612			}
1613		}
1614	}
1615
1616	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1617		synchronized (this) {
1618			if (checkListeners()) {
1619				switchToForeground();
1620			}
1621			this.mOnMucRosterUpdate = listener;
1622			if (this.mucRosterChangedListenerCount < 2) {
1623				this.mucRosterChangedListenerCount++;
1624			}
1625		}
1626	}
1627
1628	public void removeOnMucRosterUpdateListener() {
1629		synchronized (this) {
1630			this.mucRosterChangedListenerCount--;
1631			if (this.mucRosterChangedListenerCount <= 0) {
1632				this.mucRosterChangedListenerCount = 0;
1633				this.mOnMucRosterUpdate = null;
1634				if (checkListeners()) {
1635					switchToBackground();
1636				}
1637			}
1638		}
1639	}
1640
1641	private boolean checkListeners() {
1642		return (this.mOnAccountUpdate == null
1643				&& this.mOnConversationUpdate == null
1644				&& this.mOnRosterUpdate == null
1645				&& this.mOnCaptchaRequested == null
1646				&& this.mOnUpdateBlocklist == null
1647				&& this.mOnShowErrorToast == null
1648				&& this.mOnKeyStatusUpdated == null);
1649	}
1650
1651	private void switchToForeground() {
1652		for (Conversation conversation : getConversations()) {
1653			conversation.setIncomingChatState(ChatState.ACTIVE);
1654		}
1655		for (Account account : getAccounts()) {
1656			if (account.getStatus() == Account.State.ONLINE) {
1657				XmppConnection connection = account.getXmppConnection();
1658				if (connection != null && connection.getFeatures().csi()) {
1659					connection.sendActive();
1660				}
1661			}
1662		}
1663		Log.d(Config.LOGTAG, "app switched into foreground");
1664	}
1665
1666	private void switchToBackground() {
1667		for (Account account : getAccounts()) {
1668			if (account.getStatus() == Account.State.ONLINE) {
1669				XmppConnection connection = account.getXmppConnection();
1670				if (connection != null && connection.getFeatures().csi()) {
1671					connection.sendInactive();
1672				}
1673			}
1674		}
1675		this.mNotificationService.setIsInForeground(false);
1676		Log.d(Config.LOGTAG, "app switched into background");
1677	}
1678
1679	private void connectMultiModeConversations(Account account) {
1680		List<Conversation> conversations = getConversations();
1681		for (Conversation conversation : conversations) {
1682			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1683				joinMuc(conversation, true);
1684			}
1685		}
1686	}
1687
1688	public void joinMuc(Conversation conversation) {
1689		joinMuc(conversation, false);
1690	}
1691
1692	private void joinMuc(Conversation conversation, boolean now) {
1693		Account account = conversation.getAccount();
1694		account.pendingConferenceJoins.remove(conversation);
1695		account.pendingConferenceLeaves.remove(conversation);
1696		if (account.getStatus() == Account.State.ONLINE || now) {
1697			conversation.resetMucOptions();
1698			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1699
1700				private void join(Conversation conversation) {
1701					Account account = conversation.getAccount();
1702					final String nick = conversation.getMucOptions().getProposedNick();
1703					final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1704					if (joinJid == null) {
1705						return; //safety net
1706					}
1707					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1708					PresencePacket packet = new PresencePacket();
1709					packet.setFrom(conversation.getAccount().getJid());
1710					packet.setTo(joinJid);
1711					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1712					if (conversation.getMucOptions().getPassword() != null) {
1713						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1714					}
1715
1716					if (conversation.getMucOptions().mamSupport()) {
1717						// Use MAM instead of the limited muc history to get history
1718						x.addChild("history").setAttribute("maxchars", "0");
1719					} else {
1720						// Fallback to muc history
1721						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1722					}
1723					String sig = account.getPgpSignature();
1724					if (sig != null) {
1725						packet.addChild("status").setContent("online");
1726						packet.addChild("x", "jabber:x:signed").setContent(sig);
1727					}
1728					sendPresencePacket(account, packet);
1729					fetchConferenceConfiguration(conversation);
1730					if (!joinJid.equals(conversation.getJid())) {
1731						conversation.setContactJid(joinJid);
1732						databaseBackend.updateConversation(conversation);
1733					}
1734					conversation.setHasMessagesLeftOnServer(false);
1735					if (conversation.getMucOptions().mamSupport()) {
1736						getMessageArchiveService().catchupMUC(conversation);
1737					}
1738				}
1739
1740				@Override
1741				public void onConferenceConfigurationFetched(Conversation conversation) {
1742					join(conversation);
1743				}
1744
1745				@Override
1746				public void onFetchFailed(final Conversation conversation, Element error) {
1747					conversation.getMucOptions().setOnJoinListener(new MucOptions.OnJoinListener() {
1748						@Override
1749						public void onSuccess() {
1750							fetchConferenceConfiguration(conversation);
1751						}
1752
1753						@Override
1754						public void onFailure() {
1755
1756						}
1757					});
1758					join(conversation);
1759				}
1760			});
1761
1762		} else {
1763			account.pendingConferenceJoins.add(conversation);
1764		}
1765	}
1766
1767	public void providePasswordForMuc(Conversation conversation, String password) {
1768		if (conversation.getMode() == Conversation.MODE_MULTI) {
1769			conversation.getMucOptions().setPassword(password);
1770			if (conversation.getBookmark() != null) {
1771				conversation.getBookmark().setAutojoin(true);
1772				pushBookmarks(conversation.getAccount());
1773			}
1774			databaseBackend.updateConversation(conversation);
1775			joinMuc(conversation);
1776		}
1777	}
1778
1779	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1780		final MucOptions options = conversation.getMucOptions();
1781		final Jid joinJid = options.createJoinJid(nick);
1782		if (options.online()) {
1783			Account account = conversation.getAccount();
1784			options.setOnRenameListener(new OnRenameListener() {
1785
1786				@Override
1787				public void onSuccess() {
1788					conversation.setContactJid(joinJid);
1789					databaseBackend.updateConversation(conversation);
1790					Bookmark bookmark = conversation.getBookmark();
1791					if (bookmark != null) {
1792						bookmark.setNick(nick);
1793						pushBookmarks(bookmark.getAccount());
1794					}
1795					callback.success(conversation);
1796				}
1797
1798				@Override
1799				public void onFailure() {
1800					callback.error(R.string.nick_in_use, conversation);
1801				}
1802			});
1803
1804			PresencePacket packet = new PresencePacket();
1805			packet.setTo(joinJid);
1806			packet.setFrom(conversation.getAccount().getJid());
1807
1808			String sig = account.getPgpSignature();
1809			if (sig != null) {
1810				packet.addChild("status").setContent("online");
1811				packet.addChild("x", "jabber:x:signed").setContent(sig);
1812			}
1813			sendPresencePacket(account, packet);
1814		} else {
1815			conversation.setContactJid(joinJid);
1816			databaseBackend.updateConversation(conversation);
1817			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1818				Bookmark bookmark = conversation.getBookmark();
1819				if (bookmark != null) {
1820					bookmark.setNick(nick);
1821					pushBookmarks(bookmark.getAccount());
1822				}
1823				joinMuc(conversation);
1824			}
1825		}
1826	}
1827
1828	public void leaveMuc(Conversation conversation) {
1829		leaveMuc(conversation, false);
1830	}
1831
1832	private void leaveMuc(Conversation conversation, boolean now) {
1833		Account account = conversation.getAccount();
1834		account.pendingConferenceJoins.remove(conversation);
1835		account.pendingConferenceLeaves.remove(conversation);
1836		if (account.getStatus() == Account.State.ONLINE || now) {
1837			PresencePacket packet = new PresencePacket();
1838			packet.setTo(conversation.getJid());
1839			packet.setFrom(conversation.getAccount().getJid());
1840			packet.setAttribute("type", "unavailable");
1841			sendPresencePacket(conversation.getAccount(), packet);
1842			conversation.getMucOptions().setOffline();
1843			conversation.deregisterWithBookmark();
1844			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1845					+ ": leaving muc " + conversation.getJid());
1846		} else {
1847			account.pendingConferenceLeaves.add(conversation);
1848		}
1849	}
1850
1851	private String findConferenceServer(final Account account) {
1852		String server;
1853		if (account.getXmppConnection() != null) {
1854			server = account.getXmppConnection().getMucServer();
1855			if (server != null) {
1856				return server;
1857			}
1858		}
1859		for (Account other : getAccounts()) {
1860			if (other != account && other.getXmppConnection() != null) {
1861				server = other.getXmppConnection().getMucServer();
1862				if (server != null) {
1863					return server;
1864				}
1865			}
1866		}
1867		return null;
1868	}
1869
1870	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1871		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1872		if (account.getStatus() == Account.State.ONLINE) {
1873			try {
1874				String server = findConferenceServer(account);
1875				if (server == null) {
1876					if (callback != null) {
1877						callback.error(R.string.no_conference_server_found, null);
1878					}
1879					return;
1880				}
1881				String name = new BigInteger(75, getRNG()).toString(32);
1882				Jid jid = Jid.fromParts(name, server, null);
1883				final Conversation conversation = findOrCreateConversation(account, jid, true);
1884				joinMuc(conversation);
1885				Bundle options = new Bundle();
1886				options.putString("muc#roomconfig_persistentroom", "1");
1887				options.putString("muc#roomconfig_membersonly", "1");
1888				options.putString("muc#roomconfig_publicroom", "0");
1889				options.putString("muc#roomconfig_whois", "anyone");
1890				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1891					@Override
1892					public void onPushSucceeded() {
1893						for (Jid invite : jids) {
1894							invite(conversation, invite);
1895						}
1896						if (account.countPresences() > 1) {
1897							directInvite(conversation, account.getJid().toBareJid());
1898						}
1899						if (callback != null) {
1900							callback.success(conversation);
1901						}
1902					}
1903
1904					@Override
1905					public void onPushFailed() {
1906						if (callback != null) {
1907							callback.error(R.string.conference_creation_failed, conversation);
1908						}
1909					}
1910				});
1911
1912			} catch (InvalidJidException e) {
1913				if (callback != null) {
1914					callback.error(R.string.conference_creation_failed, null);
1915				}
1916			}
1917		} else {
1918			if (callback != null) {
1919				callback.error(R.string.not_connected_try_again, null);
1920			}
1921		}
1922	}
1923
1924	public void fetchConferenceConfiguration(final Conversation conversation) {
1925		fetchConferenceConfiguration(conversation, null);
1926	}
1927
1928	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1929		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1930		request.setTo(conversation.getJid().toBareJid());
1931		request.query("http://jabber.org/protocol/disco#info");
1932		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1933			@Override
1934			public void onIqPacketReceived(Account account, IqPacket packet) {
1935				if (packet.getType() == IqPacket.TYPE.RESULT) {
1936					ArrayList<String> features = new ArrayList<>();
1937					for (Element child : packet.query().getChildren()) {
1938						if (child != null && child.getName().equals("feature")) {
1939							String var = child.getAttribute("var");
1940							if (var != null) {
1941								features.add(var);
1942							}
1943						}
1944					}
1945					conversation.getMucOptions().updateFeatures(features);
1946					if (callback != null) {
1947						callback.onConferenceConfigurationFetched(conversation);
1948					}
1949					updateConversationUi();
1950				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
1951					if (callback != null) {
1952						callback.onFetchFailed(conversation, packet.getError());
1953					}
1954				}
1955			}
1956		});
1957	}
1958
1959	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1960		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1961		request.setTo(conversation.getJid().toBareJid());
1962		request.query("http://jabber.org/protocol/muc#owner");
1963		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1964			@Override
1965			public void onIqPacketReceived(Account account, IqPacket packet) {
1966				if (packet.getType() == IqPacket.TYPE.RESULT) {
1967					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1968					for (Field field : data.getFields()) {
1969						if (options.containsKey(field.getFieldName())) {
1970							field.setValue(options.getString(field.getFieldName()));
1971						}
1972					}
1973					data.submit();
1974					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1975					set.setTo(conversation.getJid().toBareJid());
1976					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1977					sendIqPacket(account, set, new OnIqPacketReceived() {
1978						@Override
1979						public void onIqPacketReceived(Account account, IqPacket packet) {
1980							if (callback != null) {
1981								if (packet.getType() == IqPacket.TYPE.RESULT) {
1982									callback.onPushSucceeded();
1983								} else {
1984									callback.onPushFailed();
1985								}
1986							}
1987						}
1988					});
1989				} else {
1990					if (callback != null) {
1991						callback.onPushFailed();
1992					}
1993				}
1994			}
1995		});
1996	}
1997
1998	public void pushSubjectToConference(final Conversation conference, final String subject) {
1999		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2000		this.sendMessagePacket(conference.getAccount(), packet);
2001		final MucOptions mucOptions = conference.getMucOptions();
2002		final MucOptions.User self = mucOptions.getSelf();
2003		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2004			Bundle options = new Bundle();
2005			options.putString("muc#roomconfig_persistentroom", "1");
2006			this.pushConferenceConfiguration(conference, options, null);
2007		}
2008	}
2009
2010	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2011		final Jid jid = user.toBareJid();
2012		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2013		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2014			@Override
2015			public void onIqPacketReceived(Account account, IqPacket packet) {
2016				if (packet.getType() == IqPacket.TYPE.RESULT) {
2017					callback.onAffiliationChangedSuccessful(jid);
2018				} else {
2019					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2020				}
2021			}
2022		});
2023	}
2024
2025	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2026		List<Jid> jids = new ArrayList<>();
2027		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2028			if (user.getAffiliation() == before && user.getJid() != null) {
2029				jids.add(user.getJid());
2030			}
2031		}
2032		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2033		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2034	}
2035
2036	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2037		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2038		Log.d(Config.LOGTAG, request.toString());
2039		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2040			@Override
2041			public void onIqPacketReceived(Account account, IqPacket packet) {
2042				Log.d(Config.LOGTAG, packet.toString());
2043				if (packet.getType() == IqPacket.TYPE.RESULT) {
2044					callback.onRoleChangedSuccessful(nick);
2045				} else {
2046					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2047				}
2048			}
2049		});
2050	}
2051
2052	private void disconnect(Account account, boolean force) {
2053		if ((account.getStatus() == Account.State.ONLINE)
2054				|| (account.getStatus() == Account.State.DISABLED)) {
2055			if (!force) {
2056				List<Conversation> conversations = getConversations();
2057				for (Conversation conversation : conversations) {
2058					if (conversation.getAccount() == account) {
2059						if (conversation.getMode() == Conversation.MODE_MULTI) {
2060							leaveMuc(conversation, true);
2061						} else {
2062							if (conversation.endOtrIfNeeded()) {
2063								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2064										+ ": ended otr session with "
2065										+ conversation.getJid());
2066							}
2067						}
2068					}
2069				}
2070				sendOfflinePresence(account);
2071			}
2072			account.getXmppConnection().disconnect(force);
2073		}
2074	}
2075
2076	@Override
2077	public IBinder onBind(Intent intent) {
2078		return mBinder;
2079	}
2080
2081	public void updateMessage(Message message) {
2082		databaseBackend.updateMessage(message);
2083		updateConversationUi();
2084	}
2085
2086	protected void syncDirtyContacts(Account account) {
2087		for (Contact contact : account.getRoster().getContacts()) {
2088			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2089				pushContactToServer(contact);
2090			}
2091			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2092				deleteContactOnServer(contact);
2093			}
2094		}
2095	}
2096
2097	public void createContact(Contact contact) {
2098		SharedPreferences sharedPref = getPreferences();
2099		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
2100		if (autoGrant) {
2101			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2102			contact.setOption(Contact.Options.ASKING);
2103		}
2104		pushContactToServer(contact);
2105	}
2106
2107	public void onOtrSessionEstablished(Conversation conversation) {
2108		final Account account = conversation.getAccount();
2109		final Session otrSession = conversation.getOtrSession();
2110		Log.d(Config.LOGTAG,
2111				account.getJid().toBareJid() + " otr session established with "
2112						+ conversation.getJid() + "/"
2113						+ otrSession.getSessionID().getUserID());
2114		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2115
2116			@Override
2117			public void onMessageFound(Message message) {
2118				SessionID id = otrSession.getSessionID();
2119				try {
2120					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2121				} catch (InvalidJidException e) {
2122					return;
2123				}
2124				if (message.needsUploading()) {
2125					mJingleConnectionManager.createNewConnection(message);
2126				} else {
2127					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2128					if (outPacket != null) {
2129						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2130						message.setStatus(Message.STATUS_SEND);
2131						databaseBackend.updateMessage(message);
2132						sendMessagePacket(account, outPacket);
2133					}
2134				}
2135				updateConversationUi();
2136			}
2137		});
2138	}
2139
2140	public boolean renewSymmetricKey(Conversation conversation) {
2141		Account account = conversation.getAccount();
2142		byte[] symmetricKey = new byte[32];
2143		this.mRandom.nextBytes(symmetricKey);
2144		Session otrSession = conversation.getOtrSession();
2145		if (otrSession != null) {
2146			MessagePacket packet = new MessagePacket();
2147			packet.setType(MessagePacket.TYPE_CHAT);
2148			packet.setFrom(account.getJid());
2149			MessageGenerator.addMessageHints(packet);
2150			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2151					+ otrSession.getSessionID().getUserID());
2152			try {
2153				packet.setBody(otrSession
2154						.transformSending(CryptoHelper.FILETRANSFER
2155								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2156				sendMessagePacket(account, packet);
2157				conversation.setSymmetricKey(symmetricKey);
2158				return true;
2159			} catch (OtrException e) {
2160				return false;
2161			}
2162		}
2163		return false;
2164	}
2165
2166	public void pushContactToServer(final Contact contact) {
2167		contact.resetOption(Contact.Options.DIRTY_DELETE);
2168		contact.setOption(Contact.Options.DIRTY_PUSH);
2169		final Account account = contact.getAccount();
2170		if (account.getStatus() == Account.State.ONLINE) {
2171			final boolean ask = contact.getOption(Contact.Options.ASKING);
2172			final boolean sendUpdates = contact
2173					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2174					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2175			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2176			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2177			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2178			if (sendUpdates) {
2179				sendPresencePacket(account,
2180						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2181			}
2182			if (ask) {
2183				sendPresencePacket(account,
2184						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2185			}
2186		}
2187	}
2188
2189	public void publishAvatar(final Account account,
2190							  final Uri image,
2191							  final UiCallback<Avatar> callback) {
2192		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2193		final int size = Config.AVATAR_SIZE;
2194		final Avatar avatar = getFileBackend()
2195				.getPepAvatar(image, size, format);
2196		if (avatar != null) {
2197			avatar.height = size;
2198			avatar.width = size;
2199			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2200				avatar.type = "image/webp";
2201			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2202				avatar.type = "image/jpeg";
2203			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2204				avatar.type = "image/png";
2205			}
2206			if (!getFileBackend().save(avatar)) {
2207				callback.error(R.string.error_saving_avatar, avatar);
2208				return;
2209			}
2210			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2211			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2212
2213				@Override
2214				public void onIqPacketReceived(Account account, IqPacket result) {
2215					if (result.getType() == IqPacket.TYPE.RESULT) {
2216						final IqPacket packet = XmppConnectionService.this.mIqGenerator
2217								.publishAvatarMetadata(avatar);
2218						sendIqPacket(account, packet, new OnIqPacketReceived() {
2219							@Override
2220							public void onIqPacketReceived(Account account, IqPacket result) {
2221								if (result.getType() == IqPacket.TYPE.RESULT) {
2222									if (account.setAvatar(avatar.getFilename())) {
2223										getAvatarService().clear(account);
2224										databaseBackend.updateAccount(account);
2225									}
2226									callback.success(avatar);
2227								} else {
2228									callback.error(
2229											R.string.error_publish_avatar_server_reject,
2230											avatar);
2231								}
2232							}
2233						});
2234					} else {
2235						callback.error(
2236								R.string.error_publish_avatar_server_reject,
2237								avatar);
2238					}
2239				}
2240			});
2241		} else {
2242			callback.error(R.string.error_publish_avatar_converting, null);
2243		}
2244	}
2245
2246	public void fetchAvatar(Account account, Avatar avatar) {
2247		fetchAvatar(account, avatar, null);
2248	}
2249
2250	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2251		final String KEY = generateFetchKey(account, avatar);
2252		synchronized (this.mInProgressAvatarFetches) {
2253			if (this.mInProgressAvatarFetches.contains(KEY)) {
2254				return;
2255			} else {
2256				switch (avatar.origin) {
2257					case PEP:
2258						this.mInProgressAvatarFetches.add(KEY);
2259						fetchAvatarPep(account, avatar, callback);
2260						break;
2261					case VCARD:
2262						this.mInProgressAvatarFetches.add(KEY);
2263						fetchAvatarVcard(account, avatar, callback);
2264						break;
2265				}
2266			}
2267		}
2268	}
2269
2270	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2271		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2272		sendIqPacket(account, packet, new OnIqPacketReceived() {
2273
2274			@Override
2275			public void onIqPacketReceived(Account account, IqPacket result) {
2276				synchronized (mInProgressAvatarFetches) {
2277					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2278				}
2279				final String ERROR = account.getJid().toBareJid()
2280						+ ": fetching avatar for " + avatar.owner + " failed ";
2281				if (result.getType() == IqPacket.TYPE.RESULT) {
2282					avatar.image = mIqParser.avatarData(result);
2283					if (avatar.image != null) {
2284						if (getFileBackend().save(avatar)) {
2285							if (account.getJid().toBareJid().equals(avatar.owner)) {
2286								if (account.setAvatar(avatar.getFilename())) {
2287									databaseBackend.updateAccount(account);
2288								}
2289								getAvatarService().clear(account);
2290								updateConversationUi();
2291								updateAccountUi();
2292							} else {
2293								Contact contact = account.getRoster()
2294										.getContact(avatar.owner);
2295								contact.setAvatar(avatar);
2296								getAvatarService().clear(contact);
2297								updateConversationUi();
2298								updateRosterUi();
2299							}
2300							if (callback != null) {
2301								callback.success(avatar);
2302							}
2303							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2304									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2305							return;
2306						}
2307					} else {
2308
2309						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2310					}
2311				} else {
2312					Element error = result.findChild("error");
2313					if (error == null) {
2314						Log.d(Config.LOGTAG, ERROR + "(server error)");
2315					} else {
2316						Log.d(Config.LOGTAG, ERROR + error.toString());
2317					}
2318				}
2319				if (callback != null) {
2320					callback.error(0, null);
2321				}
2322
2323			}
2324		});
2325	}
2326
2327	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2328		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2329		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2330			@Override
2331			public void onIqPacketReceived(Account account, IqPacket packet) {
2332				synchronized (mInProgressAvatarFetches) {
2333					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2334				}
2335				if (packet.getType() == IqPacket.TYPE.RESULT) {
2336					Element vCard = packet.findChild("vCard", "vcard-temp");
2337					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2338					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2339					if (image != null) {
2340						avatar.image = image;
2341						if (getFileBackend().save(avatar)) {
2342							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2343									+ ": successfully fetched vCard avatar for " + avatar.owner);
2344							Contact contact = account.getRoster()
2345									.getContact(avatar.owner);
2346							contact.setAvatar(avatar);
2347							getAvatarService().clear(contact);
2348							updateConversationUi();
2349							updateRosterUi();
2350						}
2351					}
2352				}
2353			}
2354		});
2355	}
2356
2357	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2358		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2359		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2360
2361			@Override
2362			public void onIqPacketReceived(Account account, IqPacket packet) {
2363				if (packet.getType() == IqPacket.TYPE.RESULT) {
2364					Element pubsub = packet.findChild("pubsub",
2365							"http://jabber.org/protocol/pubsub");
2366					if (pubsub != null) {
2367						Element items = pubsub.findChild("items");
2368						if (items != null) {
2369							Avatar avatar = Avatar.parseMetadata(items);
2370							if (avatar != null) {
2371								avatar.owner = account.getJid().toBareJid();
2372								if (fileBackend.isAvatarCached(avatar)) {
2373									if (account.setAvatar(avatar.getFilename())) {
2374										databaseBackend.updateAccount(account);
2375									}
2376									getAvatarService().clear(account);
2377									callback.success(avatar);
2378								} else {
2379									fetchAvatarPep(account, avatar, callback);
2380								}
2381								return;
2382							}
2383						}
2384					}
2385				}
2386				callback.error(0, null);
2387			}
2388		});
2389	}
2390
2391	public void deleteContactOnServer(Contact contact) {
2392		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2393		contact.resetOption(Contact.Options.DIRTY_PUSH);
2394		contact.setOption(Contact.Options.DIRTY_DELETE);
2395		Account account = contact.getAccount();
2396		if (account.getStatus() == Account.State.ONLINE) {
2397			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2398			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2399			item.setAttribute("jid", contact.getJid().toString());
2400			item.setAttribute("subscription", "remove");
2401			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2402		}
2403	}
2404
2405	public void updateConversation(Conversation conversation) {
2406		this.databaseBackend.updateConversation(conversation);
2407	}
2408
2409	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2410		synchronized (account) {
2411			if (account.getXmppConnection() != null) {
2412				disconnect(account, force);
2413			}
2414			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2415
2416				synchronized (this.mInProgressAvatarFetches) {
2417					for (Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
2418						final String KEY = iterator.next();
2419						if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
2420							iterator.remove();
2421						}
2422					}
2423				}
2424
2425				if (account.getXmppConnection() == null) {
2426					account.setXmppConnection(createConnection(account));
2427				} else if (!force) {
2428					try {
2429						Log.d(Config.LOGTAG, "wait for disconnect");
2430						Thread.sleep(500); //sleep  wait for disconnect
2431					} catch (InterruptedException e) {
2432						//ignored
2433					}
2434				}
2435				Thread thread = new Thread(account.getXmppConnection());
2436				account.getXmppConnection().setInteractive(interactive);
2437				thread.start();
2438				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2439			} else {
2440				account.getRoster().clearPresences();
2441				account.setXmppConnection(null);
2442			}
2443		}
2444	}
2445
2446	public void reconnectAccountInBackground(final Account account) {
2447		new Thread(new Runnable() {
2448			@Override
2449			public void run() {
2450				reconnectAccount(account, false, true);
2451			}
2452		}).start();
2453	}
2454
2455	public void invite(Conversation conversation, Jid contact) {
2456		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2457		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2458		sendMessagePacket(conversation.getAccount(), packet);
2459	}
2460
2461	public void directInvite(Conversation conversation, Jid jid) {
2462		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2463		sendMessagePacket(conversation.getAccount(), packet);
2464	}
2465
2466	public void resetSendingToWaiting(Account account) {
2467		for (Conversation conversation : getConversations()) {
2468			if (conversation.getAccount() == account) {
2469				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2470
2471					@Override
2472					public void onMessageFound(Message message) {
2473						markMessage(message, Message.STATUS_WAITING);
2474					}
2475				});
2476			}
2477		}
2478	}
2479
2480	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2481		if (uuid == null) {
2482			return null;
2483		}
2484		for (Conversation conversation : getConversations()) {
2485			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2486				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2487				if (message != null) {
2488					markMessage(message, status);
2489				}
2490				return message;
2491			}
2492		}
2493		return null;
2494	}
2495
2496	public boolean markMessage(Conversation conversation, String uuid, int status) {
2497		if (uuid == null) {
2498			return false;
2499		} else {
2500			Message message = conversation.findSentMessageWithUuid(uuid);
2501			if (message != null) {
2502				markMessage(message, status);
2503				return true;
2504			} else {
2505				return false;
2506			}
2507		}
2508	}
2509
2510	public void markMessage(Message message, int status) {
2511		if (status == Message.STATUS_SEND_FAILED
2512				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2513				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2514			return;
2515		}
2516		message.setStatus(status);
2517		databaseBackend.updateMessage(message);
2518		updateConversationUi();
2519	}
2520
2521	public SharedPreferences getPreferences() {
2522		return PreferenceManager
2523				.getDefaultSharedPreferences(getApplicationContext());
2524	}
2525
2526	public boolean forceEncryption() {
2527		return getPreferences().getBoolean("force_encryption", false);
2528	}
2529
2530	public boolean confirmMessages() {
2531		return getPreferences().getBoolean("confirm_messages", true);
2532	}
2533
2534	public boolean sendChatStates() {
2535		return getPreferences().getBoolean("chat_states", false);
2536	}
2537
2538	public boolean saveEncryptedMessages() {
2539		return !getPreferences().getBoolean("dont_save_encrypted", false);
2540	}
2541
2542	public boolean indicateReceived() {
2543		return getPreferences().getBoolean("indicate_received", false);
2544	}
2545
2546	public int unreadCount() {
2547		int count = 0;
2548		for (Conversation conversation : getConversations()) {
2549			count += conversation.unreadCount();
2550		}
2551		return count;
2552	}
2553
2554
2555	public void showErrorToastInUi(int resId) {
2556		if (mOnShowErrorToast != null) {
2557			mOnShowErrorToast.onShowErrorToast(resId);
2558		}
2559	}
2560
2561	public void updateConversationUi() {
2562		if (mOnConversationUpdate != null) {
2563			mOnConversationUpdate.onConversationUpdate();
2564		}
2565	}
2566
2567	public void updateAccountUi() {
2568		if (mOnAccountUpdate != null) {
2569			mOnAccountUpdate.onAccountUpdate();
2570		}
2571	}
2572
2573	public void updateRosterUi() {
2574		if (mOnRosterUpdate != null) {
2575			mOnRosterUpdate.onRosterUpdate();
2576		}
2577	}
2578
2579	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2580		boolean rc = false;
2581		if (mOnCaptchaRequested != null) {
2582			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2583			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2584					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2585
2586			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2587			rc = true;
2588		}
2589
2590		return rc;
2591	}
2592
2593	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2594		if (mOnUpdateBlocklist != null) {
2595			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2596		}
2597	}
2598
2599	public void updateMucRosterUi() {
2600		if (mOnMucRosterUpdate != null) {
2601			mOnMucRosterUpdate.onMucRosterUpdate();
2602		}
2603	}
2604
2605	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2606		if (mOnKeyStatusUpdated != null) {
2607			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2608		}
2609	}
2610
2611	public Account findAccountByJid(final Jid accountJid) {
2612		for (Account account : this.accounts) {
2613			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2614				return account;
2615			}
2616		}
2617		return null;
2618	}
2619
2620	public Conversation findConversationByUuid(String uuid) {
2621		for (Conversation conversation : getConversations()) {
2622			if (conversation.getUuid().equals(uuid)) {
2623				return conversation;
2624			}
2625		}
2626		return null;
2627	}
2628
2629	public void markRead(final Conversation conversation) {
2630		mNotificationService.clear(conversation);
2631		for (Message message : conversation.markRead()) {
2632			databaseBackend.updateMessage(message);
2633		}
2634		updateUnreadCountBadge();
2635	}
2636
2637	public synchronized void updateUnreadCountBadge() {
2638		int count = unreadCount();
2639		if (unreadCount != count) {
2640			Log.d(Config.LOGTAG, "update unread count to " + count);
2641			if (count > 0) {
2642				ShortcutBadger.with(getApplicationContext()).count(count);
2643			} else {
2644				ShortcutBadger.with(getApplicationContext()).remove();
2645			}
2646			unreadCount = count;
2647		}
2648	}
2649
2650	public void sendReadMarker(final Conversation conversation) {
2651		final Message markable = conversation.getLatestMarkableMessage();
2652		this.markRead(conversation);
2653		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2654			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2655			Account account = conversation.getAccount();
2656			final Jid to = markable.getCounterpart();
2657			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2658			this.sendMessagePacket(conversation.getAccount(), packet);
2659		}
2660		updateConversationUi();
2661	}
2662
2663	public SecureRandom getRNG() {
2664		return this.mRandom;
2665	}
2666
2667	public MemorizingTrustManager getMemorizingTrustManager() {
2668		return this.mMemorizingTrustManager;
2669	}
2670
2671	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2672		this.mMemorizingTrustManager = trustManager;
2673	}
2674
2675	public void updateMemorizingTrustmanager() {
2676		final MemorizingTrustManager tm;
2677		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2678		if (dontTrustSystemCAs) {
2679			tm = new MemorizingTrustManager(getApplicationContext(), null);
2680		} else {
2681			tm = new MemorizingTrustManager(getApplicationContext());
2682		}
2683		setMemorizingTrustManager(tm);
2684	}
2685
2686	public PowerManager getPowerManager() {
2687		return this.pm;
2688	}
2689
2690	public LruCache<String, Bitmap> getBitmapCache() {
2691		return this.mBitmapCache;
2692	}
2693
2694	public void syncRosterToDisk(final Account account) {
2695		Runnable runnable = new Runnable() {
2696
2697			@Override
2698			public void run() {
2699				databaseBackend.writeRoster(account.getRoster());
2700			}
2701		};
2702		mDatabaseExecutor.execute(runnable);
2703
2704	}
2705
2706	public List<String> getKnownHosts() {
2707		final List<String> hosts = new ArrayList<>();
2708		for (final Account account : getAccounts()) {
2709			if (!hosts.contains(account.getServer().toString())) {
2710				hosts.add(account.getServer().toString());
2711			}
2712			for (final Contact contact : account.getRoster().getContacts()) {
2713				if (contact.showInRoster()) {
2714					final String server = contact.getServer().toString();
2715					if (server != null && !hosts.contains(server)) {
2716						hosts.add(server);
2717					}
2718				}
2719			}
2720		}
2721		return hosts;
2722	}
2723
2724	public List<String> getKnownConferenceHosts() {
2725		final ArrayList<String> mucServers = new ArrayList<>();
2726		for (final Account account : accounts) {
2727			if (account.getXmppConnection() != null) {
2728				final String server = account.getXmppConnection().getMucServer();
2729				if (server != null && !mucServers.contains(server)) {
2730					mucServers.add(server);
2731				}
2732			}
2733		}
2734		return mucServers;
2735	}
2736
2737	public void sendMessagePacket(Account account, MessagePacket packet) {
2738		XmppConnection connection = account.getXmppConnection();
2739		if (connection != null) {
2740			connection.sendMessagePacket(packet);
2741		}
2742	}
2743
2744	public void sendPresencePacket(Account account, PresencePacket packet) {
2745		XmppConnection connection = account.getXmppConnection();
2746		if (connection != null) {
2747			connection.sendPresencePacket(packet);
2748		}
2749	}
2750
2751	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2752		XmppConnection connection = account.getXmppConnection();
2753		if (connection != null) {
2754			connection.sendCaptchaRegistryRequest(id, data);
2755		}
2756	}
2757
2758	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2759		final XmppConnection connection = account.getXmppConnection();
2760		if (connection != null) {
2761			connection.sendIqPacket(packet, callback);
2762		}
2763	}
2764
2765	public void sendPresence(final Account account) {
2766		sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2767	}
2768
2769	public void refreshAllPresences() {
2770		for (Account account : getAccounts()) {
2771			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2772				sendPresence(account);
2773			}
2774		}
2775	}
2776
2777	public void sendOfflinePresence(final Account account) {
2778		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2779	}
2780
2781	public MessageGenerator getMessageGenerator() {
2782		return this.mMessageGenerator;
2783	}
2784
2785	public PresenceGenerator getPresenceGenerator() {
2786		return this.mPresenceGenerator;
2787	}
2788
2789	public IqGenerator getIqGenerator() {
2790		return this.mIqGenerator;
2791	}
2792
2793	public IqParser getIqParser() {
2794		return this.mIqParser;
2795	}
2796
2797	public JingleConnectionManager getJingleConnectionManager() {
2798		return this.mJingleConnectionManager;
2799	}
2800
2801	public MessageArchiveService getMessageArchiveService() {
2802		return this.mMessageArchiveService;
2803	}
2804
2805	public List<Contact> findContacts(Jid jid) {
2806		ArrayList<Contact> contacts = new ArrayList<>();
2807		for (Account account : getAccounts()) {
2808			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2809				Contact contact = account.getRoster().getContactFromRoster(jid);
2810				if (contact != null) {
2811					contacts.add(contact);
2812				}
2813			}
2814		}
2815		return contacts;
2816	}
2817
2818	public NotificationService getNotificationService() {
2819		return this.mNotificationService;
2820	}
2821
2822	public HttpConnectionManager getHttpConnectionManager() {
2823		return this.mHttpConnectionManager;
2824	}
2825
2826	public void resendFailedMessages(final Message message) {
2827		final Collection<Message> messages = new ArrayList<>();
2828		Message current = message;
2829		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2830			messages.add(current);
2831			if (current.mergeable(current.next())) {
2832				current = current.next();
2833			} else {
2834				break;
2835			}
2836		}
2837		for (final Message msg : messages) {
2838			msg.setTime(System.currentTimeMillis());
2839			markMessage(msg, Message.STATUS_WAITING);
2840			this.resendMessage(msg, false);
2841		}
2842	}
2843
2844	public void clearConversationHistory(final Conversation conversation) {
2845		conversation.clearMessages();
2846		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2847		conversation.resetLastMessageTransmitted();
2848		new Thread(new Runnable() {
2849			@Override
2850			public void run() {
2851				databaseBackend.deleteMessagesInConversation(conversation);
2852			}
2853		}).start();
2854	}
2855
2856	public void sendBlockRequest(final Blockable blockable) {
2857		if (blockable != null && blockable.getBlockedJid() != null) {
2858			final Jid jid = blockable.getBlockedJid();
2859			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2860
2861				@Override
2862				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2863					if (packet.getType() == IqPacket.TYPE.RESULT) {
2864						account.getBlocklist().add(jid);
2865						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2866					}
2867				}
2868			});
2869		}
2870	}
2871
2872	public void sendUnblockRequest(final Blockable blockable) {
2873		if (blockable != null && blockable.getJid() != null) {
2874			final Jid jid = blockable.getBlockedJid();
2875			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2876				@Override
2877				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2878					if (packet.getType() == IqPacket.TYPE.RESULT) {
2879						account.getBlocklist().remove(jid);
2880						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2881					}
2882				}
2883			});
2884		}
2885	}
2886
2887	public interface OnAccountCreated {
2888		void onAccountCreated(Account account);
2889
2890		void informUser(int r);
2891	}
2892
2893	public interface OnMoreMessagesLoaded {
2894		void onMoreMessagesLoaded(int count, Conversation conversation);
2895
2896		void informUser(int r);
2897	}
2898
2899	public interface OnAccountPasswordChanged {
2900		void onPasswordChangeSucceeded();
2901
2902		void onPasswordChangeFailed();
2903	}
2904
2905	public interface OnAffiliationChanged {
2906		void onAffiliationChangedSuccessful(Jid jid);
2907
2908		void onAffiliationChangeFailed(Jid jid, int resId);
2909	}
2910
2911	public interface OnRoleChanged {
2912		void onRoleChangedSuccessful(String nick);
2913
2914		void onRoleChangeFailed(String nick, int resid);
2915	}
2916
2917	public interface OnConversationUpdate {
2918		void onConversationUpdate();
2919	}
2920
2921	public interface OnAccountUpdate {
2922		void onAccountUpdate();
2923	}
2924
2925	public interface OnCaptchaRequested {
2926		void onCaptchaRequested(Account account,
2927								String id,
2928								Data data,
2929								Bitmap captcha);
2930	}
2931
2932	public interface OnRosterUpdate {
2933		void onRosterUpdate();
2934	}
2935
2936	public interface OnMucRosterUpdate {
2937		void onMucRosterUpdate();
2938	}
2939
2940	public interface OnConferenceConfigurationFetched {
2941		void onConferenceConfigurationFetched(Conversation conversation);
2942
2943		void onFetchFailed(Conversation conversation, Element error);
2944	}
2945
2946	public interface OnConferenceOptionsPushed {
2947		void onPushSucceeded();
2948
2949		void onPushFailed();
2950	}
2951
2952	public interface OnShowErrorToast {
2953		void onShowErrorToast(int resId);
2954	}
2955
2956	public class XmppConnectionBinder extends Binder {
2957		public XmppConnectionService getService() {
2958			return XmppConnectionService.this;
2959		}
2960	}
2961}