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	private void sendFileMessage(final Message message) {
 676		Log.d(Config.LOGTAG, "send file message");
 677		final Account account = message.getConversation().getAccount();
 678		final XmppConnection connection = account.getXmppConnection();
 679		if (connection != null && connection.getFeatures().httpUpload()) {
 680			mHttpConnectionManager.createNewUploadConnection(message);
 681		} else {
 682			mJingleConnectionManager.createNewConnection(message);
 683		}
 684	}
 685
 686	public void sendMessage(final Message message) {
 687		final Account account = message.getConversation().getAccount();
 688		account.deactivateGracePeriod();
 689		final Conversation conv = message.getConversation();
 690		MessagePacket packet = null;
 691		boolean saveInDb = true;
 692		boolean send = false;
 693		if (account.getStatus() == Account.State.ONLINE
 694				&& account.getXmppConnection() != null) {
 695			if (message.needsUploading()) {
 696				if (message.getCounterpart() != null || account.httpUploadAvailable()) {
 697					if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 698						if (!conv.hasValidOtrSession()) {
 699							conv.startOtrSession(message.getCounterpart().getResourcepart(),true);
 700							message.setStatus(Message.STATUS_WAITING);
 701						} else if (conv.hasValidOtrSession()
 702								&& conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 703							mJingleConnectionManager.createNewConnection(message);
 704						}
 705					} else {
 706						this.sendFileMessage(message);
 707
 708					}
 709				} else {
 710					if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 711						conv.startOtrIfNeeded();
 712					}
 713					message.setStatus(Message.STATUS_WAITING);
 714				}
 715			} else {
 716				if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 717					if (!conv.hasValidOtrSession() && (message.getCounterpart() != null)) {
 718						conv.startOtrSession(message.getCounterpart().getResourcepart(), true);
 719						message.setStatus(Message.STATUS_WAITING);
 720					} else if (conv.hasValidOtrSession()) {
 721						if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 722							packet = mMessageGenerator.generateOtrChat(message);
 723							send = true;
 724						} else {
 725							message.setStatus(Message.STATUS_WAITING);
 726							conv.startOtrIfNeeded();
 727						}
 728					} else {
 729						message.setStatus(Message.STATUS_WAITING);
 730					}
 731				} else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 732					message.getConversation().endOtrIfNeeded();
 733					message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
 734						@Override
 735						public void onMessageFound(Message message) {
 736							markMessage(message,Message.STATUS_SEND_FAILED);
 737						}
 738					});
 739					packet = mMessageGenerator.generatePgpChat(message);
 740					send = true;
 741				} else {
 742					message.getConversation().endOtrIfNeeded();
 743					message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
 744						@Override
 745						public void onMessageFound(Message message) {
 746							markMessage(message,Message.STATUS_SEND_FAILED);
 747						}
 748					});
 749					packet = mMessageGenerator.generateChat(message);
 750					send = true;
 751				}
 752			}
 753			if (!account.getXmppConnection().getFeatures().sm()
 754					&& conv.getMode() != Conversation.MODE_MULTI) {
 755				message.setStatus(Message.STATUS_SEND);
 756					}
 757		} else {
 758			message.setStatus(Message.STATUS_WAITING);
 759			if (message.getType() == Message.TYPE_TEXT) {
 760				if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 761					String pgpBody = message.getEncryptedBody();
 762					String decryptedBody = message.getBody();
 763					message.setBody(pgpBody);
 764					message.setEncryption(Message.ENCRYPTION_PGP);
 765					databaseBackend.createMessage(message);
 766					saveInDb = false;
 767					message.setBody(decryptedBody);
 768					message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 769				} else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 770					if (!conv.hasValidOtrSession()
 771							&& message.getCounterpart() != null) {
 772						conv.startOtrSession(message.getCounterpart().getResourcepart(), false);
 773							}
 774				}
 775			}
 776
 777		}
 778		conv.add(message);
 779		if (saveInDb) {
 780			if (message.getEncryption() == Message.ENCRYPTION_NONE
 781					|| saveEncryptedMessages()) {
 782				databaseBackend.createMessage(message);
 783					}
 784		}
 785		if ((send) && (packet != null)) {
 786			if (conv.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 787				if (this.sendChatStates()) {
 788					packet.addChild(ChatState.toElement(conv.getOutgoingChatState()));
 789				}
 790			}
 791			sendMessagePacket(account, packet);
 792		}
 793		updateConversationUi();
 794	}
 795
 796	private void sendUnsentMessages(final Conversation conversation) {
 797		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 798
 799			@Override
 800			public void onMessageFound(Message message) {
 801				resendMessage(message);
 802			}
 803		});
 804	}
 805
 806	public void resendMessage(final Message message) {
 807		Account account = message.getConversation().getAccount();
 808		MessagePacket packet = null;
 809		if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 810			Presences presences = message.getConversation().getContact().getPresences();
 811			if (!message.getConversation().hasValidOtrSession()) {
 812				if ((message.getCounterpart() != null)
 813						&& (presences.has(message.getCounterpart().getResourcepart()))) {
 814					message.getConversation().startOtrSession(message.getCounterpart().getResourcepart(), true);
 815				} else {
 816					if (presences.size() == 1) {
 817						String presence = presences.asStringArray()[0];
 818						message.getConversation().startOtrSession(presence, true);
 819					}
 820				}
 821			} else {
 822				if (message.getConversation().getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 823					try {
 824						message.setCounterpart(Jid.fromSessionID(message.getConversation().getOtrSession().getSessionID()));
 825						if (message.needsUploading()) {
 826							mJingleConnectionManager.createNewConnection(message);
 827						} else {
 828							packet = mMessageGenerator.generateOtrChat(message, true);
 829						}
 830					} catch (final InvalidJidException ignored) {
 831
 832					}
 833				}
 834			}
 835		} else if (message.needsUploading()) {
 836			Contact contact = message.getConversation().getContact();
 837			Presences presences = contact.getPresences();
 838			if (account.httpUploadAvailable() || (message.getCounterpart() != null && presences.has(message.getCounterpart().getResourcepart()))) {
 839				this.sendFileMessage(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					this.sendFileMessage(message);
 849				}
 850			}
 851		} else {
 852			if (message.getEncryption() == Message.ENCRYPTION_NONE) {
 853				packet = mMessageGenerator.generateChat(message, true);
 854			} else if ((message.getEncryption() == Message.ENCRYPTION_DECRYPTED)
 855					|| (message.getEncryption() == Message.ENCRYPTION_PGP)) {
 856				packet = mMessageGenerator.generatePgpChat(message, true);
 857			}
 858		}
 859		if (packet != null) {
 860			if (!account.getXmppConnection().getFeatures().sm()
 861					&& message.getConversation().getMode() != Conversation.MODE_MULTI) {
 862				markMessage(message, Message.STATUS_SEND);
 863			} else {
 864				markMessage(message, Message.STATUS_UNSEND);
 865			}
 866			if (message.getConversation().setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 867				if (this.sendChatStates()) {
 868					packet.addChild(ChatState.toElement(message.getConversation().getOutgoingChatState()));
 869				}
 870			}
 871			sendMessagePacket(account, packet);
 872		}
 873	}
 874
 875	public void fetchRosterFromServer(final Account account) {
 876		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 877		if (!"".equals(account.getRosterVersion())) {
 878			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 879					+ ": fetching roster version " + account.getRosterVersion());
 880		} else {
 881			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 882		}
 883		iqPacket.query(Xmlns.ROSTER).setAttribute("ver",
 884				account.getRosterVersion());
 885		account.getXmppConnection().sendIqPacket(iqPacket, mIqParser);
 886	}
 887
 888	public void fetchBookmarks(final Account account) {
 889		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 890		final Element query = iqPacket.query("jabber:iq:private");
 891		query.addChild("storage", "storage:bookmarks");
 892		final OnIqPacketReceived callback = new OnIqPacketReceived() {
 893
 894			@Override
 895			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 896				final Element query = packet.query();
 897				final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 898				final Element storage = query.findChild("storage",
 899						"storage:bookmarks");
 900				if (storage != null) {
 901					for (final Element item : storage.getChildren()) {
 902						if (item.getName().equals("conference")) {
 903							final Bookmark bookmark = Bookmark.parse(item, account);
 904							bookmarks.add(bookmark);
 905							Conversation conversation = find(bookmark);
 906							if (conversation != null) {
 907								conversation.setBookmark(bookmark);
 908							} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 909								conversation = findOrCreateConversation(
 910										account, bookmark.getJid(), true);
 911								conversation.setBookmark(bookmark);
 912								joinMuc(conversation);
 913							}
 914						}
 915					}
 916				}
 917				account.setBookmarks(bookmarks);
 918			}
 919		};
 920		sendIqPacket(account, iqPacket, callback);
 921	}
 922
 923	public void pushBookmarks(Account account) {
 924		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
 925		Element query = iqPacket.query("jabber:iq:private");
 926		Element storage = query.addChild("storage", "storage:bookmarks");
 927		for (Bookmark bookmark : account.getBookmarks()) {
 928			storage.addChild(bookmark);
 929		}
 930		sendIqPacket(account, iqPacket, mDefaultIqHandler);
 931	}
 932
 933	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
 934		if (mPhoneContactMergerThread != null) {
 935			mPhoneContactMergerThread.interrupt();
 936		}
 937		mPhoneContactMergerThread = new Thread(new Runnable() {
 938			@Override
 939			public void run() {
 940				Log.d(Config.LOGTAG,"start merging phone contacts with roster");
 941				for (Account account : accounts) {
 942					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
 943					for (Bundle phoneContact : phoneContacts) {
 944						if (Thread.interrupted()) {
 945							Log.d(Config.LOGTAG,"interrupted merging phone contacts");
 946							return;
 947						}
 948						Jid jid;
 949						try {
 950							jid = Jid.fromString(phoneContact.getString("jid"));
 951						} catch (final InvalidJidException e) {
 952							continue;
 953						}
 954						final Contact contact = account.getRoster().getContact(jid);
 955						String systemAccount = phoneContact.getInt("phoneid")
 956							+ "#"
 957							+ phoneContact.getString("lookup");
 958						contact.setSystemAccount(systemAccount);
 959						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
 960							getAvatarService().clear(contact);
 961						}
 962						contact.setSystemName(phoneContact.getString("displayname"));
 963						withSystemAccounts.remove(contact);
 964					}
 965					for(Contact contact : withSystemAccounts) {
 966						contact.setSystemAccount(null);
 967						contact.setSystemName(null);
 968						if (contact.setPhotoUri(null)) {
 969							getAvatarService().clear(contact);
 970						}
 971					}
 972				}
 973				Log.d(Config.LOGTAG,"finished merging phone contacts");
 974				updateAccountUi();
 975			}
 976		});
 977		mPhoneContactMergerThread.start();
 978	}
 979
 980	private void restoreFromDatabase() {
 981		synchronized (this.conversations) {
 982			final Map<String, Account> accountLookupTable = new Hashtable<>();
 983			for (Account account : this.accounts) {
 984				accountLookupTable.put(account.getUuid(), account);
 985			}
 986			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
 987			for (Conversation conversation : this.conversations) {
 988				Account account = accountLookupTable.get(conversation.getAccountUuid());
 989				conversation.setAccount(account);
 990			}
 991			Runnable runnable =new Runnable() {
 992				@Override
 993				public void run() {
 994					Log.d(Config.LOGTAG,"restoring roster");
 995					for(Account account : accounts) {
 996						databaseBackend.readRoster(account.getRoster());
 997					}
 998					getBitmapCache().evictAll();
 999					Looper.prepare();
1000					PhoneHelper.loadPhoneContacts(getApplicationContext(),
1001							new CopyOnWriteArrayList<Bundle>(),
1002							XmppConnectionService.this);
1003					Log.d(Config.LOGTAG,"restoring messages");
1004					for (Conversation conversation : conversations) {
1005						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1006						checkDeletedFiles(conversation);
1007					}
1008					mRestoredFromDatabase = true;
1009					Log.d(Config.LOGTAG,"restored all messages");
1010					updateConversationUi();
1011				}
1012			};
1013			mDatabaseExecutor.execute(runnable);
1014		}
1015	}
1016
1017	public List<Conversation> getConversations() {
1018		return this.conversations;
1019	}
1020
1021	private void checkDeletedFiles(Conversation conversation) {
1022		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1023
1024			@Override
1025			public void onMessageFound(Message message) {
1026				if (!getFileBackend().isFileAvailable(message)) {
1027					message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
1028				}
1029			}
1030		});
1031	}
1032
1033	private void markFileDeleted(String uuid) {
1034		for (Conversation conversation : getConversations()) {
1035			Message message = conversation.findMessageWithFileAndUuid(uuid);
1036			if (message != null) {
1037				if (!getFileBackend().isFileAvailable(message)) {
1038					message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
1039					updateConversationUi();
1040				}
1041				return;
1042			}
1043		}
1044	}
1045
1046	public void populateWithOrderedConversations(final List<Conversation> list) {
1047		populateWithOrderedConversations(list, true);
1048	}
1049
1050	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1051		list.clear();
1052		if (includeNoFileUpload) {
1053			list.addAll(getConversations());
1054		} else {
1055			for (Conversation conversation : getConversations()) {
1056				if (conversation.getMode() == Conversation.MODE_SINGLE
1057						|| conversation.getAccount().httpUploadAvailable()) {
1058					list.add(conversation);
1059				}
1060			}
1061		}
1062		Collections.sort(list, new Comparator<Conversation>() {
1063			@Override
1064			public int compare(Conversation lhs, Conversation rhs) {
1065				Message left = lhs.getLatestMessage();
1066				Message right = rhs.getLatestMessage();
1067				if (left.getTimeSent() > right.getTimeSent()) {
1068					return -1;
1069				} else if (left.getTimeSent() < right.getTimeSent()) {
1070					return 1;
1071				} else {
1072					return 0;
1073				}
1074			}
1075		});
1076	}
1077
1078	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1079		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1080		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1081			return;
1082		}
1083		Runnable runnable = new Runnable() {
1084			@Override
1085			public void run() {
1086				final Account account = conversation.getAccount();
1087				List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1088				if (messages.size() > 0) {
1089					conversation.addAll(0, messages);
1090					checkDeletedFiles(conversation);
1091					callback.onMoreMessagesLoaded(messages.size(), conversation);
1092				} else if (conversation.hasMessagesLeftOnServer()
1093						&& account.isOnlineAndConnected()
1094						&& account.getXmppConnection().getFeatures().mam()) {
1095					MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1096					if (query != null) {
1097						query.setCallback(callback);
1098					}
1099					callback.informUser(R.string.fetching_history_from_server);
1100				}
1101			}
1102		};
1103		mDatabaseExecutor.execute(runnable);
1104	}
1105
1106	public List<Account> getAccounts() {
1107		return this.accounts;
1108	}
1109
1110	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1111		for (final Conversation conversation : haystack) {
1112			if (conversation.getContact() == contact) {
1113				return conversation;
1114			}
1115		}
1116		return null;
1117	}
1118
1119	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1120		if (jid == null) {
1121			return null;
1122		}
1123		for (final Conversation conversation : haystack) {
1124			if ((account == null || conversation.getAccount() == account)
1125					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1126				return conversation;
1127			}
1128		}
1129		return null;
1130	}
1131
1132	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1133		return this.findOrCreateConversation(account, jid, muc, null);
1134	}
1135
1136	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1137		synchronized (this.conversations) {
1138			Conversation conversation = find(account, jid);
1139			if (conversation != null) {
1140				return conversation;
1141			}
1142			conversation = databaseBackend.findConversation(account, jid);
1143			if (conversation != null) {
1144				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1145				conversation.setAccount(account);
1146				if (muc) {
1147					conversation.setMode(Conversation.MODE_MULTI);
1148					conversation.setContactJid(jid);
1149				} else {
1150					conversation.setMode(Conversation.MODE_SINGLE);
1151					conversation.setContactJid(jid.toBareJid());
1152				}
1153				conversation.setNextEncryption(-1);
1154				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1155				this.databaseBackend.updateConversation(conversation);
1156			} else {
1157				String conversationName;
1158				Contact contact = account.getRoster().getContact(jid);
1159				if (contact != null) {
1160					conversationName = contact.getDisplayName();
1161				} else {
1162					conversationName = jid.getLocalpart();
1163				}
1164				if (muc) {
1165					conversation = new Conversation(conversationName, account, jid,
1166							Conversation.MODE_MULTI);
1167				} else {
1168					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1169							Conversation.MODE_SINGLE);
1170				}
1171				this.databaseBackend.createConversation(conversation);
1172			}
1173			if (account.getXmppConnection() != null
1174					&& account.getXmppConnection().getFeatures().mam()
1175					&& !muc) {
1176				if (query == null) {
1177					this.mMessageArchiveService.query(conversation);
1178				} else {
1179					if (query.getConversation() == null) {
1180						this.mMessageArchiveService.query(conversation, query.getStart());
1181					}
1182				}
1183			}
1184			checkDeletedFiles(conversation);
1185			this.conversations.add(conversation);
1186			updateConversationUi();
1187			return conversation;
1188		}
1189	}
1190
1191	public void archiveConversation(Conversation conversation) {
1192		getNotificationService().clear(conversation);
1193		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1194		conversation.setNextEncryption(-1);
1195		synchronized (this.conversations) {
1196			if (conversation.getMode() == Conversation.MODE_MULTI) {
1197				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1198					Bookmark bookmark = conversation.getBookmark();
1199					if (bookmark != null && bookmark.autojoin()) {
1200						bookmark.setAutojoin(false);
1201						pushBookmarks(bookmark.getAccount());
1202					}
1203				}
1204				leaveMuc(conversation);
1205			} else {
1206				conversation.endOtrIfNeeded();
1207			}
1208			this.databaseBackend.updateConversation(conversation);
1209			this.conversations.remove(conversation);
1210			updateConversationUi();
1211		}
1212	}
1213
1214	public void createAccount(final Account account) {
1215		account.initAccountServices(this);
1216		databaseBackend.createAccount(account);
1217		this.accounts.add(account);
1218		this.reconnectAccountInBackground(account);
1219		updateAccountUi();
1220	}
1221
1222	public void updateAccount(final Account account) {
1223		this.statusListener.onStatusChanged(account);
1224		databaseBackend.updateAccount(account);
1225		reconnectAccount(account, false);
1226		updateAccountUi();
1227		getNotificationService().updateErrorNotification();
1228	}
1229
1230	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1231		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1232		sendIqPacket(account, iq, new OnIqPacketReceived() {
1233			@Override
1234			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1235				if (packet.getType() == IqPacket.TYPE.RESULT) {
1236					account.setPassword(newPassword);
1237					databaseBackend.updateAccount(account);
1238					callback.onPasswordChangeSucceeded();
1239				} else {
1240					callback.onPasswordChangeFailed();
1241				}
1242			}
1243		});
1244	}
1245
1246	public void deleteAccount(final Account account) {
1247		synchronized (this.conversations) {
1248			for (final Conversation conversation : conversations) {
1249				if (conversation.getAccount() == account) {
1250					if (conversation.getMode() == Conversation.MODE_MULTI) {
1251						leaveMuc(conversation);
1252					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1253						conversation.endOtrIfNeeded();
1254					}
1255					conversations.remove(conversation);
1256				}
1257			}
1258			if (account.getXmppConnection() != null) {
1259				this.disconnect(account, true);
1260			}
1261			databaseBackend.deleteAccount(account);
1262			this.accounts.remove(account);
1263			updateAccountUi();
1264			getNotificationService().updateErrorNotification();
1265		}
1266	}
1267
1268	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1269		synchronized (this) {
1270			if (checkListeners()) {
1271				switchToForeground();
1272			}
1273			this.mOnConversationUpdate = listener;
1274			this.mNotificationService.setIsInForeground(true);
1275			if (this.convChangedListenerCount < 2) {
1276				this.convChangedListenerCount++;
1277			}
1278		}
1279	}
1280
1281	public void removeOnConversationListChangedListener() {
1282		synchronized (this) {
1283			this.convChangedListenerCount--;
1284			if (this.convChangedListenerCount <= 0) {
1285				this.convChangedListenerCount = 0;
1286				this.mOnConversationUpdate = null;
1287				this.mNotificationService.setIsInForeground(false);
1288				if (checkListeners()) {
1289					switchToBackground();
1290				}
1291			}
1292		}
1293	}
1294
1295	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1296		synchronized (this) {
1297			if (checkListeners()) {
1298				switchToForeground();
1299			}
1300			this.mOnAccountUpdate = listener;
1301			if (this.accountChangedListenerCount < 2) {
1302				this.accountChangedListenerCount++;
1303			}
1304		}
1305	}
1306
1307	public void removeOnAccountListChangedListener() {
1308		synchronized (this) {
1309			this.accountChangedListenerCount--;
1310			if (this.accountChangedListenerCount <= 0) {
1311				this.mOnAccountUpdate = null;
1312				this.accountChangedListenerCount = 0;
1313				if (checkListeners()) {
1314					switchToBackground();
1315				}
1316			}
1317		}
1318	}
1319
1320	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1321		synchronized (this) {
1322			if (checkListeners()) {
1323				switchToForeground();
1324			}
1325			this.mOnRosterUpdate = listener;
1326			if (this.rosterChangedListenerCount < 2) {
1327				this.rosterChangedListenerCount++;
1328			}
1329		}
1330	}
1331
1332	public void removeOnRosterUpdateListener() {
1333		synchronized (this) {
1334			this.rosterChangedListenerCount--;
1335			if (this.rosterChangedListenerCount <= 0) {
1336				this.rosterChangedListenerCount = 0;
1337				this.mOnRosterUpdate = null;
1338				if (checkListeners()) {
1339					switchToBackground();
1340				}
1341			}
1342		}
1343	}
1344
1345	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1346		synchronized (this) {
1347			if (checkListeners()) {
1348				switchToForeground();
1349			}
1350			this.mOnUpdateBlocklist = listener;
1351			if (this.updateBlocklistListenerCount < 2) {
1352				this.updateBlocklistListenerCount++;
1353			}
1354		}
1355	}
1356
1357	public void removeOnUpdateBlocklistListener() {
1358		synchronized (this) {
1359			this.updateBlocklistListenerCount--;
1360			if (this.updateBlocklistListenerCount <= 0) {
1361				this.updateBlocklistListenerCount = 0;
1362				this.mOnUpdateBlocklist = null;
1363				if (checkListeners()) {
1364					switchToBackground();
1365				}
1366			}
1367		}
1368	}
1369
1370	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1371		synchronized (this) {
1372			if (checkListeners()) {
1373				switchToForeground();
1374			}
1375			this.mOnMucRosterUpdate = listener;
1376			if (this.mucRosterChangedListenerCount < 2) {
1377				this.mucRosterChangedListenerCount++;
1378			}
1379		}
1380	}
1381
1382	public void removeOnMucRosterUpdateListener() {
1383		synchronized (this) {
1384			this.mucRosterChangedListenerCount--;
1385			if (this.mucRosterChangedListenerCount <= 0) {
1386				this.mucRosterChangedListenerCount = 0;
1387				this.mOnMucRosterUpdate = null;
1388				if (checkListeners()) {
1389					switchToBackground();
1390				}
1391			}
1392		}
1393	}
1394
1395	private boolean checkListeners() {
1396		return (this.mOnAccountUpdate == null
1397				&& this.mOnConversationUpdate == null
1398				&& this.mOnRosterUpdate == null
1399				&& this.mOnUpdateBlocklist == null);
1400	}
1401
1402	private void switchToForeground() {
1403		for (Account account : getAccounts()) {
1404			if (account.getStatus() == Account.State.ONLINE) {
1405				XmppConnection connection = account.getXmppConnection();
1406				if (connection != null && connection.getFeatures().csi()) {
1407					connection.sendActive();
1408				}
1409			}
1410		}
1411		Log.d(Config.LOGTAG, "app switched into foreground");
1412	}
1413
1414	private void switchToBackground() {
1415		for (Account account : getAccounts()) {
1416			if (account.getStatus() == Account.State.ONLINE) {
1417				XmppConnection connection = account.getXmppConnection();
1418				if (connection != null && connection.getFeatures().csi()) {
1419					connection.sendInactive();
1420				}
1421			}
1422		}
1423		for(Conversation conversation : getConversations()) {
1424			conversation.setIncomingChatState(ChatState.ACTIVE);
1425		}
1426		this.mNotificationService.setIsInForeground(false);
1427		Log.d(Config.LOGTAG, "app switched into background");
1428	}
1429
1430	private void connectMultiModeConversations(Account account) {
1431		List<Conversation> conversations = getConversations();
1432		for (Conversation conversation : conversations) {
1433			if ((conversation.getMode() == Conversation.MODE_MULTI)
1434					&& (conversation.getAccount() == account)) {
1435				conversation.resetMucOptions();
1436				joinMuc(conversation);
1437			}
1438		}
1439	}
1440
1441	public void joinMuc(Conversation conversation) {
1442		Account account = conversation.getAccount();
1443		account.pendingConferenceJoins.remove(conversation);
1444		account.pendingConferenceLeaves.remove(conversation);
1445		if (account.getStatus() == Account.State.ONLINE) {
1446			final String nick = conversation.getMucOptions().getProposedNick();
1447			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1448			if (joinJid == null) {
1449				return; //safety net
1450			}
1451			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1452			PresencePacket packet = new PresencePacket();
1453			packet.setFrom(conversation.getAccount().getJid());
1454			packet.setTo(joinJid);
1455			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1456			if (conversation.getMucOptions().getPassword() != null) {
1457				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1458			}
1459			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1460			String sig = account.getPgpSignature();
1461			if (sig != null) {
1462				packet.addChild("status").setContent("online");
1463				packet.addChild("x", "jabber:x:signed").setContent(sig);
1464			}
1465			sendPresencePacket(account, packet);
1466			fetchConferenceConfiguration(conversation);
1467			if (!joinJid.equals(conversation.getJid())) {
1468				conversation.setContactJid(joinJid);
1469				databaseBackend.updateConversation(conversation);
1470			}
1471			conversation.setHasMessagesLeftOnServer(false);
1472		} else {
1473			account.pendingConferenceJoins.add(conversation);
1474		}
1475	}
1476
1477	public void providePasswordForMuc(Conversation conversation, String password) {
1478		if (conversation.getMode() == Conversation.MODE_MULTI) {
1479			conversation.getMucOptions().setPassword(password);
1480			if (conversation.getBookmark() != null) {
1481				conversation.getBookmark().setAutojoin(true);
1482				pushBookmarks(conversation.getAccount());
1483			}
1484			databaseBackend.updateConversation(conversation);
1485			joinMuc(conversation);
1486		}
1487	}
1488
1489	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1490		final MucOptions options = conversation.getMucOptions();
1491		final Jid joinJid = options.createJoinJid(nick);
1492		if (options.online()) {
1493			Account account = conversation.getAccount();
1494			options.setOnRenameListener(new OnRenameListener() {
1495
1496				@Override
1497				public void onSuccess() {
1498					conversation.setContactJid(joinJid);
1499					databaseBackend.updateConversation(conversation);
1500					Bookmark bookmark = conversation.getBookmark();
1501					if (bookmark != null) {
1502						bookmark.setNick(nick);
1503						pushBookmarks(bookmark.getAccount());
1504					}
1505					callback.success(conversation);
1506				}
1507
1508				@Override
1509				public void onFailure() {
1510					callback.error(R.string.nick_in_use, conversation);
1511				}
1512			});
1513
1514			PresencePacket packet = new PresencePacket();
1515			packet.setTo(joinJid);
1516			packet.setFrom(conversation.getAccount().getJid());
1517
1518			String sig = account.getPgpSignature();
1519			if (sig != null) {
1520				packet.addChild("status").setContent("online");
1521				packet.addChild("x", "jabber:x:signed").setContent(sig);
1522			}
1523			sendPresencePacket(account, packet);
1524		} else {
1525			conversation.setContactJid(joinJid);
1526			databaseBackend.updateConversation(conversation);
1527			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1528				Bookmark bookmark = conversation.getBookmark();
1529				if (bookmark != null) {
1530					bookmark.setNick(nick);
1531					pushBookmarks(bookmark.getAccount());
1532				}
1533				joinMuc(conversation);
1534			}
1535		}
1536	}
1537
1538	public void leaveMuc(Conversation conversation) {
1539		Account account = conversation.getAccount();
1540		account.pendingConferenceJoins.remove(conversation);
1541		account.pendingConferenceLeaves.remove(conversation);
1542		if (account.getStatus() == Account.State.ONLINE) {
1543			PresencePacket packet = new PresencePacket();
1544			packet.setTo(conversation.getJid());
1545			packet.setFrom(conversation.getAccount().getJid());
1546			packet.setAttribute("type", "unavailable");
1547			sendPresencePacket(conversation.getAccount(), packet);
1548			conversation.getMucOptions().setOffline();
1549			conversation.deregisterWithBookmark();
1550			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1551					+ ": leaving muc " + conversation.getJid());
1552		} else {
1553			account.pendingConferenceLeaves.add(conversation);
1554		}
1555	}
1556
1557	private String findConferenceServer(final Account account) {
1558		String server;
1559		if (account.getXmppConnection() != null) {
1560			server = account.getXmppConnection().getMucServer();
1561			if (server != null) {
1562				return server;
1563			}
1564		}
1565		for (Account other : getAccounts()) {
1566			if (other != account && other.getXmppConnection() != null) {
1567				server = other.getXmppConnection().getMucServer();
1568				if (server != null) {
1569					return server;
1570				}
1571			}
1572		}
1573		return null;
1574	}
1575
1576	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1577		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1578		if (account.getStatus() == Account.State.ONLINE) {
1579			try {
1580				String server = findConferenceServer(account);
1581				if (server == null) {
1582					if (callback != null) {
1583						callback.error(R.string.no_conference_server_found, null);
1584					}
1585					return;
1586				}
1587				String name = new BigInteger(75, getRNG()).toString(32);
1588				Jid jid = Jid.fromParts(name, server, null);
1589				final Conversation conversation = findOrCreateConversation(account, jid, true);
1590				joinMuc(conversation);
1591				Bundle options = new Bundle();
1592				options.putString("muc#roomconfig_persistentroom", "1");
1593				options.putString("muc#roomconfig_membersonly", "1");
1594				options.putString("muc#roomconfig_publicroom", "0");
1595				options.putString("muc#roomconfig_whois", "anyone");
1596				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1597					@Override
1598					public void onPushSucceeded() {
1599						for (Jid invite : jids) {
1600							invite(conversation, invite);
1601						}
1602						if (account.countPresences() > 1) {
1603							directInvite(conversation, account.getJid().toBareJid());
1604						}
1605						if (callback != null) {
1606							callback.success(conversation);
1607						}
1608					}
1609
1610					@Override
1611					public void onPushFailed() {
1612						if (callback != null) {
1613							callback.error(R.string.conference_creation_failed, conversation);
1614						}
1615					}
1616				});
1617
1618			} catch (InvalidJidException e) {
1619				if (callback != null) {
1620					callback.error(R.string.conference_creation_failed, null);
1621				}
1622			}
1623		} else {
1624			if (callback != null) {
1625				callback.error(R.string.not_connected_try_again, null);
1626			}
1627		}
1628	}
1629
1630	public void fetchConferenceConfiguration(final Conversation conversation) {
1631		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1632		request.setTo(conversation.getJid().toBareJid());
1633		request.query("http://jabber.org/protocol/disco#info");
1634		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1635			@Override
1636			public void onIqPacketReceived(Account account, IqPacket packet) {
1637				if (packet.getType() != IqPacket.TYPE.ERROR) {
1638					ArrayList<String> features = new ArrayList<>();
1639					for (Element child : packet.query().getChildren()) {
1640						if (child != null && child.getName().equals("feature")) {
1641							String var = child.getAttribute("var");
1642							if (var != null) {
1643								features.add(var);
1644							}
1645						}
1646					}
1647					conversation.getMucOptions().updateFeatures(features);
1648					updateConversationUi();
1649				}
1650			}
1651		});
1652	}
1653
1654	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1655		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1656		request.setTo(conversation.getJid().toBareJid());
1657		request.query("http://jabber.org/protocol/muc#owner");
1658		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1659			@Override
1660			public void onIqPacketReceived(Account account, IqPacket packet) {
1661				if (packet.getType() != IqPacket.TYPE.ERROR) {
1662					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1663					for (Field field : data.getFields()) {
1664						if (options.containsKey(field.getName())) {
1665							field.setValue(options.getString(field.getName()));
1666						}
1667					}
1668					data.submit();
1669					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1670					set.setTo(conversation.getJid().toBareJid());
1671					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1672					sendIqPacket(account, set, new OnIqPacketReceived() {
1673						@Override
1674						public void onIqPacketReceived(Account account, IqPacket packet) {
1675							if (packet.getType() == IqPacket.TYPE.RESULT) {
1676								if (callback != null) {
1677									callback.onPushSucceeded();
1678								}
1679							} else {
1680								if (callback != null) {
1681									callback.onPushFailed();
1682								}
1683							}
1684						}
1685					});
1686				} else {
1687					if (callback != null) {
1688						callback.onPushFailed();
1689					}
1690				}
1691			}
1692		});
1693	}
1694
1695	public void pushSubjectToConference(final Conversation conference, final String subject) {
1696		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1697		this.sendMessagePacket(conference.getAccount(), packet);
1698		final MucOptions mucOptions = conference.getMucOptions();
1699		final MucOptions.User self = mucOptions.getSelf();
1700		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1701			Bundle options = new Bundle();
1702			options.putString("muc#roomconfig_persistentroom", "1");
1703			this.pushConferenceConfiguration(conference, options, null);
1704		}
1705	}
1706
1707	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1708		final Jid jid = user.toBareJid();
1709		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1710		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1711			@Override
1712			public void onIqPacketReceived(Account account, IqPacket packet) {
1713				if (packet.getType() == IqPacket.TYPE.RESULT) {
1714					callback.onAffiliationChangedSuccessful(jid);
1715				} else {
1716					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1717				}
1718			}
1719		});
1720	}
1721
1722	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1723		List<Jid> jids = new ArrayList<>();
1724		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1725			if (user.getAffiliation() == before) {
1726				jids.add(user.getJid());
1727			}
1728		}
1729		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1730		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1731	}
1732
1733	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1734		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1735		Log.d(Config.LOGTAG, request.toString());
1736		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1737			@Override
1738			public void onIqPacketReceived(Account account, IqPacket packet) {
1739				Log.d(Config.LOGTAG, packet.toString());
1740				if (packet.getType() == IqPacket.TYPE.RESULT) {
1741					callback.onRoleChangedSuccessful(nick);
1742				} else {
1743					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1744				}
1745			}
1746		});
1747	}
1748
1749	public void disconnect(Account account, boolean force) {
1750		if ((account.getStatus() == Account.State.ONLINE)
1751				|| (account.getStatus() == Account.State.DISABLED)) {
1752			if (!force) {
1753				List<Conversation> conversations = getConversations();
1754				for (Conversation conversation : conversations) {
1755					if (conversation.getAccount() == account) {
1756						if (conversation.getMode() == Conversation.MODE_MULTI) {
1757							leaveMuc(conversation);
1758						} else {
1759							if (conversation.endOtrIfNeeded()) {
1760								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1761										+ ": ended otr session with "
1762										+ conversation.getJid());
1763							}
1764						}
1765					}
1766				}
1767				sendOfflinePresence(account);
1768			}
1769			account.getXmppConnection().disconnect(force);
1770		}
1771	}
1772
1773	@Override
1774	public IBinder onBind(Intent intent) {
1775		return mBinder;
1776	}
1777
1778	public void updateMessage(Message message) {
1779		databaseBackend.updateMessage(message);
1780		updateConversationUi();
1781	}
1782
1783	protected void syncDirtyContacts(Account account) {
1784		for (Contact contact : account.getRoster().getContacts()) {
1785			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1786				pushContactToServer(contact);
1787			}
1788			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1789				deleteContactOnServer(contact);
1790			}
1791		}
1792	}
1793
1794	public void createContact(Contact contact) {
1795		SharedPreferences sharedPref = getPreferences();
1796		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1797		if (autoGrant) {
1798			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1799			contact.setOption(Contact.Options.ASKING);
1800		}
1801		pushContactToServer(contact);
1802	}
1803
1804	public void onOtrSessionEstablished(Conversation conversation) {
1805		final Account account = conversation.getAccount();
1806		final Session otrSession = conversation.getOtrSession();
1807		Log.d(Config.LOGTAG,
1808				account.getJid().toBareJid() + " otr session established with "
1809						+ conversation.getJid() + "/"
1810						+ otrSession.getSessionID().getUserID());
1811		conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1812
1813			@Override
1814			public void onMessageFound(Message message) {
1815				SessionID id = otrSession.getSessionID();
1816				try {
1817					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1818				} catch (InvalidJidException e) {
1819					return;
1820				}
1821				if (message.needsUploading()) {
1822					mJingleConnectionManager.createNewConnection(message);
1823				} else {
1824					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1825					if (outPacket != null) {
1826						message.setStatus(Message.STATUS_SEND);
1827						databaseBackend.updateMessage(message);
1828						sendMessagePacket(account, outPacket);
1829					}
1830				}
1831				updateConversationUi();
1832			}
1833		});
1834	}
1835
1836	public boolean renewSymmetricKey(Conversation conversation) {
1837		Account account = conversation.getAccount();
1838		byte[] symmetricKey = new byte[32];
1839		this.mRandom.nextBytes(symmetricKey);
1840		Session otrSession = conversation.getOtrSession();
1841		if (otrSession != null) {
1842			MessagePacket packet = new MessagePacket();
1843			packet.setType(MessagePacket.TYPE_CHAT);
1844			packet.setFrom(account.getJid());
1845			packet.addChild("private", "urn:xmpp:carbons:2");
1846			packet.addChild("no-copy", "urn:xmpp:hints");
1847			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1848					+ otrSession.getSessionID().getUserID());
1849			try {
1850				packet.setBody(otrSession
1851						.transformSending(CryptoHelper.FILETRANSFER
1852								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1853				sendMessagePacket(account, packet);
1854				conversation.setSymmetricKey(symmetricKey);
1855				return true;
1856			} catch (OtrException e) {
1857				return false;
1858			}
1859		}
1860		return false;
1861	}
1862
1863	public void pushContactToServer(final Contact contact) {
1864		contact.resetOption(Contact.Options.DIRTY_DELETE);
1865		contact.setOption(Contact.Options.DIRTY_PUSH);
1866		final Account account = contact.getAccount();
1867		if (account.getStatus() == Account.State.ONLINE) {
1868			final boolean ask = contact.getOption(Contact.Options.ASKING);
1869			final boolean sendUpdates = contact
1870					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1871					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1872			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1873			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1874			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1875			if (sendUpdates) {
1876				sendPresencePacket(account,
1877						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1878			}
1879			if (ask) {
1880				sendPresencePacket(account,
1881						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1882			}
1883		}
1884	}
1885
1886	public void publishAvatar(final Account account,
1887							  final Uri image,
1888							  final UiCallback<Avatar> callback) {
1889		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1890		final int size = Config.AVATAR_SIZE;
1891		final Avatar avatar = getFileBackend()
1892				.getPepAvatar(image, size, format);
1893		if (avatar != null) {
1894			avatar.height = size;
1895			avatar.width = size;
1896			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1897				avatar.type = "image/webp";
1898			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1899				avatar.type = "image/jpeg";
1900			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1901				avatar.type = "image/png";
1902			}
1903			if (!getFileBackend().save(avatar)) {
1904				callback.error(R.string.error_saving_avatar, avatar);
1905				return;
1906			}
1907			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1908			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1909
1910				@Override
1911				public void onIqPacketReceived(Account account, IqPacket result) {
1912					if (result.getType() == IqPacket.TYPE.RESULT) {
1913						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1914								.publishAvatarMetadata(avatar);
1915						sendIqPacket(account, packet, new OnIqPacketReceived() {
1916
1917							@Override
1918							public void onIqPacketReceived(Account account,
1919														   IqPacket result) {
1920								if (result.getType() == IqPacket.TYPE.RESULT) {
1921									if (account.setAvatar(avatar.getFilename())) {
1922										getAvatarService().clear(account);
1923										databaseBackend.updateAccount(account);
1924									}
1925									callback.success(avatar);
1926								} else {
1927									callback.error(
1928											R.string.error_publish_avatar_server_reject,
1929											avatar);
1930								}
1931							}
1932						});
1933					} else {
1934						callback.error(
1935								R.string.error_publish_avatar_server_reject,
1936								avatar);
1937					}
1938				}
1939			});
1940		} else {
1941			callback.error(R.string.error_publish_avatar_converting, null);
1942		}
1943	}
1944
1945	public void fetchAvatar(Account account, Avatar avatar) {
1946		fetchAvatar(account, avatar, null);
1947	}
1948
1949	private static String generateFetchKey(Account account, final Avatar avatar) {
1950		return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1951	}
1952
1953	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1954		final String KEY = generateFetchKey(account, avatar);
1955		synchronized(this.mInProgressAvatarFetches) {
1956			if (this.mInProgressAvatarFetches.contains(KEY)) {
1957				return;
1958			} else {
1959				switch (avatar.origin) {
1960					case PEP:
1961						this.mInProgressAvatarFetches.add(KEY);
1962						fetchAvatarPep(account, avatar, callback);
1963						break;
1964					case VCARD:
1965						this.mInProgressAvatarFetches.add(KEY);
1966						fetchAvatarVcard(account, avatar, callback);
1967						break;
1968				}
1969			}
1970		}
1971	}
1972
1973	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1974		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
1975		sendIqPacket(account, packet, new OnIqPacketReceived() {
1976
1977			@Override
1978			public void onIqPacketReceived(Account account, IqPacket result) {
1979				synchronized (mInProgressAvatarFetches) {
1980					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
1981				}
1982				final String ERROR = account.getJid().toBareJid()
1983						+ ": fetching avatar for " + avatar.owner + " failed ";
1984				if (result.getType() == IqPacket.TYPE.RESULT) {
1985					avatar.image = mIqParser.avatarData(result);
1986					if (avatar.image != null) {
1987						if (getFileBackend().save(avatar)) {
1988							if (account.getJid().toBareJid().equals(avatar.owner)) {
1989								if (account.setAvatar(avatar.getFilename())) {
1990									databaseBackend.updateAccount(account);
1991								}
1992								getAvatarService().clear(account);
1993								updateConversationUi();
1994								updateAccountUi();
1995							} else {
1996								Contact contact = account.getRoster()
1997										.getContact(avatar.owner);
1998								contact.setAvatar(avatar);
1999								getAvatarService().clear(contact);
2000								updateConversationUi();
2001								updateRosterUi();
2002							}
2003							if (callback != null) {
2004								callback.success(avatar);
2005							}
2006							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2007									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2008							return;
2009						}
2010					} else {
2011
2012						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2013					}
2014				} else {
2015					Element error = result.findChild("error");
2016					if (error == null) {
2017						Log.d(Config.LOGTAG, ERROR + "(server error)");
2018					} else {
2019						Log.d(Config.LOGTAG, ERROR + error.toString());
2020					}
2021				}
2022				if (callback != null) {
2023					callback.error(0, null);
2024				}
2025
2026			}
2027		});
2028	}
2029
2030	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2031		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2032		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2033			@Override
2034			public void onIqPacketReceived(Account account, IqPacket packet) {
2035				synchronized (mInProgressAvatarFetches) {
2036					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2037				}
2038				if (packet.getType() == IqPacket.TYPE.RESULT) {
2039					Element vCard = packet.findChild("vCard", "vcard-temp");
2040					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2041					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2042					if (image != null) {
2043						avatar.image = image;
2044						if (getFileBackend().save(avatar)) {
2045							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2046									+ ": successfully fetched vCard avatar for " + avatar.owner);
2047							Contact contact = account.getRoster()
2048									.getContact(avatar.owner);
2049							contact.setAvatar(avatar);
2050							getAvatarService().clear(contact);
2051							updateConversationUi();
2052							updateRosterUi();
2053						}
2054					}
2055				}
2056			}
2057		});
2058	}
2059
2060	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2061		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2062		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2063
2064			@Override
2065			public void onIqPacketReceived(Account account, IqPacket packet) {
2066				if (packet.getType() == IqPacket.TYPE.RESULT) {
2067					Element pubsub = packet.findChild("pubsub",
2068							"http://jabber.org/protocol/pubsub");
2069					if (pubsub != null) {
2070						Element items = pubsub.findChild("items");
2071						if (items != null) {
2072							Avatar avatar = Avatar.parseMetadata(items);
2073							if (avatar != null) {
2074								avatar.owner = account.getJid().toBareJid();
2075								if (fileBackend.isAvatarCached(avatar)) {
2076									if (account.setAvatar(avatar.getFilename())) {
2077										databaseBackend.updateAccount(account);
2078									}
2079									getAvatarService().clear(account);
2080									callback.success(avatar);
2081								} else {
2082									fetchAvatarPep(account, avatar, callback);
2083								}
2084								return;
2085							}
2086						}
2087					}
2088				}
2089				callback.error(0, null);
2090			}
2091		});
2092	}
2093
2094	public void deleteContactOnServer(Contact contact) {
2095		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2096		contact.resetOption(Contact.Options.DIRTY_PUSH);
2097		contact.setOption(Contact.Options.DIRTY_DELETE);
2098		Account account = contact.getAccount();
2099		if (account.getStatus() == Account.State.ONLINE) {
2100			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2101			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2102			item.setAttribute("jid", contact.getJid().toString());
2103			item.setAttribute("subscription", "remove");
2104			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2105		}
2106	}
2107
2108	public void updateConversation(Conversation conversation) {
2109		this.databaseBackend.updateConversation(conversation);
2110	}
2111
2112	public void reconnectAccount(final Account account, final boolean force) {
2113		synchronized (account) {
2114			if (account.getXmppConnection() != null) {
2115				disconnect(account, force);
2116			}
2117			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2118
2119				synchronized (this.mInProgressAvatarFetches) {
2120					for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2121						final String KEY = iterator.next();
2122						if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2123							iterator.remove();
2124						}
2125					}
2126				}
2127
2128				if (account.getXmppConnection() == null) {
2129					account.setXmppConnection(createConnection(account));
2130				}
2131				Thread thread = new Thread(account.getXmppConnection());
2132				thread.start();
2133				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2134			} else {
2135				account.getRoster().clearPresences();
2136				account.setXmppConnection(null);
2137			}
2138		}
2139	}
2140
2141	public void reconnectAccountInBackground(final Account account) {
2142		new Thread(new Runnable() {
2143			@Override
2144			public void run() {
2145				reconnectAccount(account,false);
2146			}
2147		}).start();
2148	}
2149
2150	public void invite(Conversation conversation, Jid contact) {
2151		Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2152		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2153		sendMessagePacket(conversation.getAccount(), packet);
2154	}
2155
2156	public void directInvite(Conversation conversation, Jid jid) {
2157		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2158		sendMessagePacket(conversation.getAccount(),packet);
2159	}
2160
2161	public void resetSendingToWaiting(Account account) {
2162		for (Conversation conversation : getConversations()) {
2163			if (conversation.getAccount() == account) {
2164				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2165
2166					@Override
2167					public void onMessageFound(Message message) {
2168						markMessage(message, Message.STATUS_WAITING);
2169					}
2170				});
2171			}
2172		}
2173	}
2174
2175	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2176		if (uuid == null) {
2177			return null;
2178		}
2179		for (Conversation conversation : getConversations()) {
2180			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2181				final Message message = conversation.findSentMessageWithUuid(uuid);
2182				if (message != null) {
2183					markMessage(message, status);
2184				}
2185				return message;
2186			}
2187		}
2188		return null;
2189	}
2190
2191	public boolean markMessage(Conversation conversation, String uuid,
2192							   int status) {
2193		if (uuid == null) {
2194			return false;
2195		} else {
2196			Message message = conversation.findSentMessageWithUuid(uuid);
2197			if (message != null) {
2198				markMessage(message, status);
2199				return true;
2200			} else {
2201				return false;
2202			}
2203		}
2204	}
2205
2206	public void markMessage(Message message, int status) {
2207		if (status == Message.STATUS_SEND_FAILED
2208				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2209				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2210			return;
2211		}
2212		message.setStatus(status);
2213		databaseBackend.updateMessage(message);
2214		updateConversationUi();
2215	}
2216
2217	public SharedPreferences getPreferences() {
2218		return PreferenceManager
2219				.getDefaultSharedPreferences(getApplicationContext());
2220	}
2221
2222	public boolean forceEncryption() {
2223		return getPreferences().getBoolean("force_encryption", false);
2224	}
2225
2226	public boolean confirmMessages() {
2227		return getPreferences().getBoolean("confirm_messages", true);
2228	}
2229
2230	public boolean sendChatStates() {
2231		return getPreferences().getBoolean("chat_states", false);
2232	}
2233
2234	public boolean saveEncryptedMessages() {
2235		return !getPreferences().getBoolean("dont_save_encrypted", false);
2236	}
2237
2238	public boolean indicateReceived() {
2239		return getPreferences().getBoolean("indicate_received", false);
2240	}
2241
2242	public int unreadCount() {
2243		int count = 0;
2244		for(Conversation conversation : getConversations()) {
2245			count += conversation.unreadCount();
2246		}
2247		return count;
2248	}
2249
2250	public void updateConversationUi() {
2251		if (mOnConversationUpdate != null) {
2252			mOnConversationUpdate.onConversationUpdate();
2253		}
2254	}
2255
2256	public void updateAccountUi() {
2257		if (mOnAccountUpdate != null) {
2258			mOnAccountUpdate.onAccountUpdate();
2259		}
2260	}
2261
2262	public void updateRosterUi() {
2263		if (mOnRosterUpdate != null) {
2264			mOnRosterUpdate.onRosterUpdate();
2265		}
2266	}
2267
2268	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2269		if (mOnUpdateBlocklist != null) {
2270			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2271		}
2272	}
2273
2274	public void updateMucRosterUi() {
2275		if (mOnMucRosterUpdate != null) {
2276			mOnMucRosterUpdate.onMucRosterUpdate();
2277		}
2278	}
2279
2280	public Account findAccountByJid(final Jid accountJid) {
2281		for (Account account : this.accounts) {
2282			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2283				return account;
2284			}
2285		}
2286		return null;
2287	}
2288
2289	public Conversation findConversationByUuid(String uuid) {
2290		for (Conversation conversation : getConversations()) {
2291			if (conversation.getUuid().equals(uuid)) {
2292				return conversation;
2293			}
2294		}
2295		return null;
2296	}
2297
2298	public void markRead(final Conversation conversation) {
2299		mNotificationService.clear(conversation);
2300		conversation.markRead();
2301		updateUnreadCountBadge();
2302	}
2303
2304	public synchronized void updateUnreadCountBadge() {
2305		int count = unreadCount();
2306		if (unreadCount != count) {
2307			Log.d(Config.LOGTAG, "update unread count to " + count);
2308			if (count > 0) {
2309				ShortcutBadger.with(getApplicationContext()).count(count);
2310			} else {
2311				ShortcutBadger.with(getApplicationContext()).remove();
2312			}
2313			unreadCount = count;
2314		}
2315	}
2316
2317	public void sendReadMarker(final Conversation conversation) {
2318		final Message markable = conversation.getLatestMarkableMessage();
2319		this.markRead(conversation);
2320		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2321			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2322			Account account = conversation.getAccount();
2323			final Jid to = markable.getCounterpart();
2324			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2325			this.sendMessagePacket(conversation.getAccount(), packet);
2326		}
2327		updateConversationUi();
2328	}
2329
2330	public SecureRandom getRNG() {
2331		return this.mRandom;
2332	}
2333
2334	public MemorizingTrustManager getMemorizingTrustManager() {
2335		return this.mMemorizingTrustManager;
2336	}
2337
2338	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2339		this.mMemorizingTrustManager = trustManager;
2340	}
2341
2342	public void updateMemorizingTrustmanager() {
2343		final MemorizingTrustManager tm;
2344		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2345		if (dontTrustSystemCAs) {
2346			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2347		} else {
2348			tm = new MemorizingTrustManager(getApplicationContext());
2349		}
2350		setMemorizingTrustManager(tm);
2351	}
2352
2353	public PowerManager getPowerManager() {
2354		return this.pm;
2355	}
2356
2357	public LruCache<String, Bitmap> getBitmapCache() {
2358		return this.mBitmapCache;
2359	}
2360
2361	public void syncRosterToDisk(final Account account) {
2362		Runnable runnable = new Runnable() {
2363
2364			@Override
2365			public void run() {
2366				databaseBackend.writeRoster(account.getRoster());
2367			}
2368		};
2369		mDatabaseExecutor.execute(runnable);
2370
2371	}
2372
2373	public List<String> getKnownHosts() {
2374		final List<String> hosts = new ArrayList<>();
2375		for (final Account account : getAccounts()) {
2376			if (!hosts.contains(account.getServer().toString())) {
2377				hosts.add(account.getServer().toString());
2378			}
2379			for (final Contact contact : account.getRoster().getContacts()) {
2380				if (contact.showInRoster()) {
2381					final String server = contact.getServer().toString();
2382					if (server != null && !hosts.contains(server)) {
2383						hosts.add(server);
2384					}
2385				}
2386			}
2387		}
2388		return hosts;
2389	}
2390
2391	public List<String> getKnownConferenceHosts() {
2392		final ArrayList<String> mucServers = new ArrayList<>();
2393		for (final Account account : accounts) {
2394			if (account.getXmppConnection() != null) {
2395				final String server = account.getXmppConnection().getMucServer();
2396				if (server != null && !mucServers.contains(server)) {
2397					mucServers.add(server);
2398				}
2399			}
2400		}
2401		return mucServers;
2402	}
2403
2404	public void sendMessagePacket(Account account, MessagePacket packet) {
2405		XmppConnection connection = account.getXmppConnection();
2406		if (connection != null) {
2407			connection.sendMessagePacket(packet);
2408		}
2409	}
2410
2411	public void sendPresencePacket(Account account, PresencePacket packet) {
2412		XmppConnection connection = account.getXmppConnection();
2413		if (connection != null) {
2414			connection.sendPresencePacket(packet);
2415		}
2416	}
2417
2418	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2419		final XmppConnection connection = account.getXmppConnection();
2420		if (connection != null) {
2421			connection.sendIqPacket(packet, callback);
2422		}
2423	}
2424
2425	public void sendPresence(final Account account) {
2426		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2427	}
2428
2429	public void sendOfflinePresence(final Account account) {
2430		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2431	}
2432
2433	public MessageGenerator getMessageGenerator() {
2434		return this.mMessageGenerator;
2435	}
2436
2437	public PresenceGenerator getPresenceGenerator() {
2438		return this.mPresenceGenerator;
2439	}
2440
2441	public IqGenerator getIqGenerator() {
2442		return this.mIqGenerator;
2443	}
2444
2445	public IqParser getIqParser() {
2446		return this.mIqParser;
2447	}
2448
2449	public JingleConnectionManager getJingleConnectionManager() {
2450		return this.mJingleConnectionManager;
2451	}
2452
2453	public MessageArchiveService getMessageArchiveService() {
2454		return this.mMessageArchiveService;
2455	}
2456
2457	public List<Contact> findContacts(Jid jid) {
2458		ArrayList<Contact> contacts = new ArrayList<>();
2459		for (Account account : getAccounts()) {
2460			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2461				Contact contact = account.getRoster().getContactFromRoster(jid);
2462				if (contact != null) {
2463					contacts.add(contact);
2464				}
2465			}
2466		}
2467		return contacts;
2468	}
2469
2470	public NotificationService getNotificationService() {
2471		return this.mNotificationService;
2472	}
2473
2474	public HttpConnectionManager getHttpConnectionManager() {
2475		return this.mHttpConnectionManager;
2476	}
2477
2478	public void resendFailedMessages(final Message message) {
2479		final Collection<Message> messages = new ArrayList<>();
2480		Message current = message;
2481		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2482			messages.add(current);
2483			if (current.mergeable(current.next())) {
2484				current = current.next();
2485			} else {
2486				break;
2487			}
2488		}
2489		for (final Message msg : messages) {
2490			markMessage(msg, Message.STATUS_WAITING);
2491			this.resendMessage(msg);
2492		}
2493	}
2494
2495	public void clearConversationHistory(final Conversation conversation) {
2496		conversation.clearMessages();
2497		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2498		new Thread(new Runnable() {
2499			@Override
2500			public void run() {
2501				databaseBackend.deleteMessagesInConversation(conversation);
2502			}
2503		}).start();
2504	}
2505
2506	public void sendBlockRequest(final Blockable blockable) {
2507		if (blockable != null && blockable.getBlockedJid() != null) {
2508			final Jid jid = blockable.getBlockedJid();
2509			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2510
2511				@Override
2512				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2513					if (packet.getType() == IqPacket.TYPE.RESULT) {
2514						account.getBlocklist().add(jid);
2515						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2516					}
2517				}
2518			});
2519		}
2520	}
2521
2522	public void sendUnblockRequest(final Blockable blockable) {
2523		if (blockable != null && blockable.getJid() != null) {
2524			final Jid jid = blockable.getBlockedJid();
2525			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2526				@Override
2527				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2528					if (packet.getType() == IqPacket.TYPE.RESULT) {
2529						account.getBlocklist().remove(jid);
2530						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2531					}
2532				}
2533			});
2534		}
2535	}
2536
2537	public interface OnMoreMessagesLoaded {
2538		public void onMoreMessagesLoaded(int count, Conversation conversation);
2539
2540		public void informUser(int r);
2541	}
2542
2543	public interface OnAccountPasswordChanged {
2544		public void onPasswordChangeSucceeded();
2545
2546		public void onPasswordChangeFailed();
2547	}
2548
2549	public interface OnAffiliationChanged {
2550		public void onAffiliationChangedSuccessful(Jid jid);
2551
2552		public void onAffiliationChangeFailed(Jid jid, int resId);
2553	}
2554
2555	public interface OnRoleChanged {
2556		public void onRoleChangedSuccessful(String nick);
2557
2558		public void onRoleChangeFailed(String nick, int resid);
2559	}
2560
2561	public interface OnConversationUpdate {
2562		public void onConversationUpdate();
2563	}
2564
2565	public interface OnAccountUpdate {
2566		public void onAccountUpdate();
2567	}
2568
2569	public interface OnRosterUpdate {
2570		public void onRosterUpdate();
2571	}
2572
2573	public interface OnMucRosterUpdate {
2574		public void onMucRosterUpdate();
2575	}
2576
2577	public interface OnConferenceOptionsPushed {
2578		public void onPushSucceeded();
2579
2580		public void onPushFailed();
2581	}
2582
2583	public class XmppConnectionBinder extends Binder {
2584		public XmppConnectionService getService() {
2585			return XmppConnectionService.this;
2586		}
2587	}
2588}