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