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