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