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