XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.annotation.SuppressLint;
   4import android.app.AlarmManager;
   5import android.app.PendingIntent;
   6import android.app.Service;
   7import android.content.Context;
   8import android.content.Intent;
   9import android.content.SharedPreferences;
  10import android.database.ContentObserver;
  11import android.graphics.Bitmap;
  12import android.net.ConnectivityManager;
  13import android.net.NetworkInfo;
  14import android.net.Uri;
  15import android.os.Binder;
  16import android.os.Bundle;
  17import android.os.FileObserver;
  18import android.os.IBinder;
  19import android.os.Looper;
  20import android.os.PowerManager;
  21import android.os.PowerManager.WakeLock;
  22import android.os.SystemClock;
  23import android.preference.PreferenceManager;
  24import android.provider.ContactsContract;
  25import android.util.Log;
  26import android.util.LruCache;
  27
  28import net.java.otr4j.OtrException;
  29import net.java.otr4j.session.Session;
  30import net.java.otr4j.session.SessionID;
  31import net.java.otr4j.session.SessionImpl;
  32import net.java.otr4j.session.SessionStatus;
  33
  34import org.openintents.openpgp.util.OpenPgpApi;
  35import org.openintents.openpgp.util.OpenPgpServiceConnection;
  36
  37import java.math.BigInteger;
  38import java.security.SecureRandom;
  39import java.util.ArrayList;
  40import java.util.Arrays;
  41import java.util.Collection;
  42import java.util.Collections;
  43import java.util.Comparator;
  44import java.util.Hashtable;
  45import java.util.Iterator;
  46import java.util.List;
  47import java.util.Locale;
  48import java.util.Map;
  49import java.util.concurrent.CopyOnWriteArrayList;
  50
  51import de.duenndns.ssl.MemorizingTrustManager;
  52import eu.siacs.conversations.Config;
  53import eu.siacs.conversations.R;
  54import eu.siacs.conversations.crypto.PgpEngine;
  55import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  56import eu.siacs.conversations.entities.Account;
  57import eu.siacs.conversations.entities.Blockable;
  58import eu.siacs.conversations.entities.Bookmark;
  59import eu.siacs.conversations.entities.Contact;
  60import eu.siacs.conversations.entities.Conversation;
  61import eu.siacs.conversations.entities.Message;
  62import eu.siacs.conversations.entities.MucOptions;
  63import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  64import eu.siacs.conversations.entities.Transferable;
  65import eu.siacs.conversations.entities.TransferablePlaceholder;
  66import eu.siacs.conversations.generator.IqGenerator;
  67import eu.siacs.conversations.generator.MessageGenerator;
  68import eu.siacs.conversations.generator.PresenceGenerator;
  69import eu.siacs.conversations.http.HttpConnectionManager;
  70import eu.siacs.conversations.parser.IqParser;
  71import eu.siacs.conversations.parser.MessageParser;
  72import eu.siacs.conversations.parser.PresenceParser;
  73import eu.siacs.conversations.persistance.DatabaseBackend;
  74import eu.siacs.conversations.persistance.FileBackend;
  75import eu.siacs.conversations.ui.UiCallback;
  76import eu.siacs.conversations.utils.CryptoHelper;
  77import eu.siacs.conversations.utils.ExceptionHelper;
  78import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
  79import eu.siacs.conversations.utils.PRNGFixes;
  80import eu.siacs.conversations.utils.PhoneHelper;
  81import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  82import eu.siacs.conversations.utils.Xmlns;
  83import eu.siacs.conversations.xml.Element;
  84import eu.siacs.conversations.xmpp.OnBindListener;
  85import eu.siacs.conversations.xmpp.OnContactStatusChanged;
  86import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  87import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
  88import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
  89import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  90import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
  91import eu.siacs.conversations.xmpp.OnStatusChanged;
  92import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  93import eu.siacs.conversations.xmpp.XmppConnection;
  94import eu.siacs.conversations.xmpp.chatstate.ChatState;
  95import eu.siacs.conversations.xmpp.forms.Data;
  96import eu.siacs.conversations.xmpp.forms.Field;
  97import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  98import eu.siacs.conversations.xmpp.jid.Jid;
  99import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 100import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 101import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 102import eu.siacs.conversations.xmpp.pep.Avatar;
 103import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 104import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 105import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 106import me.leolin.shortcutbadger.ShortcutBadger;
 107
 108public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
 109
 110	public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 111	public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
 112	private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
 113	public static final String ACTION_TRY_AGAIN = "try_again";
 114	public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
 115	private ContentObserver contactObserver = new ContentObserver(null) {
 116		@Override
 117		public void onChange(boolean selfChange) {
 118			super.onChange(selfChange);
 119			Intent intent = new Intent(getApplicationContext(),
 120					XmppConnectionService.class);
 121			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 122			startService(intent);
 123		}
 124	};
 125
 126	private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
 127	private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
 128
 129	private final IBinder mBinder = new XmppConnectionBinder();
 130	private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 131	private final FileObserver fileObserver = new FileObserver(
 132			FileBackend.getConversationsImageDirectory()) {
 133
 134		@Override
 135		public void onEvent(int event, String path) {
 136			if (event == FileObserver.DELETE) {
 137				markFileDeleted(path.split("\\.")[0]);
 138			}
 139		}
 140	};
 141	private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 142
 143		@Override
 144		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 145			mJingleConnectionManager.deliverPacket(account, packet);
 146		}
 147	};
 148	private final OnBindListener mOnBindListener = new OnBindListener() {
 149
 150		@Override
 151		public void onBind(final Account account) {
 152			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 OnKeyStatusUpdated mOnKeyStatusUpdated = null;
 313	private int keyStatusUpdatedListenerCount = 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 setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1376		synchronized (this) {
1377			if (checkListeners()) {
1378				switchToForeground();
1379			}
1380			this.mOnKeyStatusUpdated = listener;
1381			if (this.keyStatusUpdatedListenerCount < 2) {
1382				this.keyStatusUpdatedListenerCount++;
1383			}
1384		}
1385	}
1386
1387	public void removeOnNewKeysAvailableListener() {
1388		synchronized (this) {
1389			this.keyStatusUpdatedListenerCount--;
1390			if (this.keyStatusUpdatedListenerCount <= 0) {
1391				this.keyStatusUpdatedListenerCount = 0;
1392				this.mOnKeyStatusUpdated = null;
1393				if (checkListeners()) {
1394					switchToBackground();
1395				}
1396			}
1397		}
1398	}
1399
1400	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1401		synchronized (this) {
1402			if (checkListeners()) {
1403				switchToForeground();
1404			}
1405			this.mOnMucRosterUpdate = listener;
1406			if (this.mucRosterChangedListenerCount < 2) {
1407				this.mucRosterChangedListenerCount++;
1408			}
1409		}
1410	}
1411
1412	public void removeOnMucRosterUpdateListener() {
1413		synchronized (this) {
1414			this.mucRosterChangedListenerCount--;
1415			if (this.mucRosterChangedListenerCount <= 0) {
1416				this.mucRosterChangedListenerCount = 0;
1417				this.mOnMucRosterUpdate = null;
1418				if (checkListeners()) {
1419					switchToBackground();
1420				}
1421			}
1422		}
1423	}
1424
1425	private boolean checkListeners() {
1426		return (this.mOnAccountUpdate == null
1427				&& this.mOnConversationUpdate == null
1428				&& this.mOnRosterUpdate == null
1429				&& this.mOnUpdateBlocklist == null
1430				&& this.mOnShowErrorToast == null
1431				&& this.mOnKeyStatusUpdated == null);
1432	}
1433
1434	private void switchToForeground() {
1435		for (Account account : getAccounts()) {
1436			if (account.getStatus() == Account.State.ONLINE) {
1437				XmppConnection connection = account.getXmppConnection();
1438				if (connection != null && connection.getFeatures().csi()) {
1439					connection.sendActive();
1440				}
1441			}
1442		}
1443		Log.d(Config.LOGTAG, "app switched into foreground");
1444	}
1445
1446	private void switchToBackground() {
1447		for (Account account : getAccounts()) {
1448			if (account.getStatus() == Account.State.ONLINE) {
1449				XmppConnection connection = account.getXmppConnection();
1450				if (connection != null && connection.getFeatures().csi()) {
1451					connection.sendInactive();
1452				}
1453			}
1454		}
1455		for(Conversation conversation : getConversations()) {
1456			conversation.setIncomingChatState(ChatState.ACTIVE);
1457		}
1458		this.mNotificationService.setIsInForeground(false);
1459		Log.d(Config.LOGTAG, "app switched into background");
1460	}
1461
1462	private void connectMultiModeConversations(Account account) {
1463		List<Conversation> conversations = getConversations();
1464		for (Conversation conversation : conversations) {
1465			if ((conversation.getMode() == Conversation.MODE_MULTI)
1466					&& (conversation.getAccount() == account)) {
1467				conversation.resetMucOptions();
1468				joinMuc(conversation);
1469			}
1470		}
1471	}
1472
1473	public void joinMuc(Conversation conversation) {
1474		Account account = conversation.getAccount();
1475		account.pendingConferenceJoins.remove(conversation);
1476		account.pendingConferenceLeaves.remove(conversation);
1477		if (account.getStatus() == Account.State.ONLINE) {
1478			final String nick = conversation.getMucOptions().getProposedNick();
1479			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1480			if (joinJid == null) {
1481				return; //safety net
1482			}
1483			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1484			PresencePacket packet = new PresencePacket();
1485			packet.setFrom(conversation.getAccount().getJid());
1486			packet.setTo(joinJid);
1487			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1488			if (conversation.getMucOptions().getPassword() != null) {
1489				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1490			}
1491			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1492			String sig = account.getPgpSignature();
1493			if (sig != null) {
1494				packet.addChild("status").setContent("online");
1495				packet.addChild("x", "jabber:x:signed").setContent(sig);
1496			}
1497			sendPresencePacket(account, packet);
1498			fetchConferenceConfiguration(conversation);
1499			if (!joinJid.equals(conversation.getJid())) {
1500				conversation.setContactJid(joinJid);
1501				databaseBackend.updateConversation(conversation);
1502			}
1503			conversation.setHasMessagesLeftOnServer(false);
1504		} else {
1505			account.pendingConferenceJoins.add(conversation);
1506		}
1507	}
1508
1509	public void providePasswordForMuc(Conversation conversation, String password) {
1510		if (conversation.getMode() == Conversation.MODE_MULTI) {
1511			conversation.getMucOptions().setPassword(password);
1512			if (conversation.getBookmark() != null) {
1513				conversation.getBookmark().setAutojoin(true);
1514				pushBookmarks(conversation.getAccount());
1515			}
1516			databaseBackend.updateConversation(conversation);
1517			joinMuc(conversation);
1518		}
1519	}
1520
1521	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1522		final MucOptions options = conversation.getMucOptions();
1523		final Jid joinJid = options.createJoinJid(nick);
1524		if (options.online()) {
1525			Account account = conversation.getAccount();
1526			options.setOnRenameListener(new OnRenameListener() {
1527
1528				@Override
1529				public void onSuccess() {
1530					conversation.setContactJid(joinJid);
1531					databaseBackend.updateConversation(conversation);
1532					Bookmark bookmark = conversation.getBookmark();
1533					if (bookmark != null) {
1534						bookmark.setNick(nick);
1535						pushBookmarks(bookmark.getAccount());
1536					}
1537					callback.success(conversation);
1538				}
1539
1540				@Override
1541				public void onFailure() {
1542					callback.error(R.string.nick_in_use, conversation);
1543				}
1544			});
1545
1546			PresencePacket packet = new PresencePacket();
1547			packet.setTo(joinJid);
1548			packet.setFrom(conversation.getAccount().getJid());
1549
1550			String sig = account.getPgpSignature();
1551			if (sig != null) {
1552				packet.addChild("status").setContent("online");
1553				packet.addChild("x", "jabber:x:signed").setContent(sig);
1554			}
1555			sendPresencePacket(account, packet);
1556		} else {
1557			conversation.setContactJid(joinJid);
1558			databaseBackend.updateConversation(conversation);
1559			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1560				Bookmark bookmark = conversation.getBookmark();
1561				if (bookmark != null) {
1562					bookmark.setNick(nick);
1563					pushBookmarks(bookmark.getAccount());
1564				}
1565				joinMuc(conversation);
1566			}
1567		}
1568	}
1569
1570	public void leaveMuc(Conversation conversation) {
1571		Account account = conversation.getAccount();
1572		account.pendingConferenceJoins.remove(conversation);
1573		account.pendingConferenceLeaves.remove(conversation);
1574		if (account.getStatus() == Account.State.ONLINE) {
1575			PresencePacket packet = new PresencePacket();
1576			packet.setTo(conversation.getJid());
1577			packet.setFrom(conversation.getAccount().getJid());
1578			packet.setAttribute("type", "unavailable");
1579			sendPresencePacket(conversation.getAccount(), packet);
1580			conversation.getMucOptions().setOffline();
1581			conversation.deregisterWithBookmark();
1582			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1583					+ ": leaving muc " + conversation.getJid());
1584		} else {
1585			account.pendingConferenceLeaves.add(conversation);
1586		}
1587	}
1588
1589	private String findConferenceServer(final Account account) {
1590		String server;
1591		if (account.getXmppConnection() != null) {
1592			server = account.getXmppConnection().getMucServer();
1593			if (server != null) {
1594				return server;
1595			}
1596		}
1597		for (Account other : getAccounts()) {
1598			if (other != account && other.getXmppConnection() != null) {
1599				server = other.getXmppConnection().getMucServer();
1600				if (server != null) {
1601					return server;
1602				}
1603			}
1604		}
1605		return null;
1606	}
1607
1608	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1609		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1610		if (account.getStatus() == Account.State.ONLINE) {
1611			try {
1612				String server = findConferenceServer(account);
1613				if (server == null) {
1614					if (callback != null) {
1615						callback.error(R.string.no_conference_server_found, null);
1616					}
1617					return;
1618				}
1619				String name = new BigInteger(75, getRNG()).toString(32);
1620				Jid jid = Jid.fromParts(name, server, null);
1621				final Conversation conversation = findOrCreateConversation(account, jid, true);
1622				joinMuc(conversation);
1623				Bundle options = new Bundle();
1624				options.putString("muc#roomconfig_persistentroom", "1");
1625				options.putString("muc#roomconfig_membersonly", "1");
1626				options.putString("muc#roomconfig_publicroom", "0");
1627				options.putString("muc#roomconfig_whois", "anyone");
1628				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1629					@Override
1630					public void onPushSucceeded() {
1631						for (Jid invite : jids) {
1632							invite(conversation, invite);
1633						}
1634						if (account.countPresences() > 1) {
1635							directInvite(conversation, account.getJid().toBareJid());
1636						}
1637						if (callback != null) {
1638							callback.success(conversation);
1639						}
1640					}
1641
1642					@Override
1643					public void onPushFailed() {
1644						if (callback != null) {
1645							callback.error(R.string.conference_creation_failed, conversation);
1646						}
1647					}
1648				});
1649
1650			} catch (InvalidJidException e) {
1651				if (callback != null) {
1652					callback.error(R.string.conference_creation_failed, null);
1653				}
1654			}
1655		} else {
1656			if (callback != null) {
1657				callback.error(R.string.not_connected_try_again, null);
1658			}
1659		}
1660	}
1661
1662	public void fetchConferenceConfiguration(final Conversation conversation) {
1663		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1664		request.setTo(conversation.getJid().toBareJid());
1665		request.query("http://jabber.org/protocol/disco#info");
1666		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1667			@Override
1668			public void onIqPacketReceived(Account account, IqPacket packet) {
1669				if (packet.getType() != IqPacket.TYPE.ERROR) {
1670					ArrayList<String> features = new ArrayList<>();
1671					for (Element child : packet.query().getChildren()) {
1672						if (child != null && child.getName().equals("feature")) {
1673							String var = child.getAttribute("var");
1674							if (var != null) {
1675								features.add(var);
1676							}
1677						}
1678					}
1679					conversation.getMucOptions().updateFeatures(features);
1680					updateConversationUi();
1681				}
1682			}
1683		});
1684	}
1685
1686	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1687		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1688		request.setTo(conversation.getJid().toBareJid());
1689		request.query("http://jabber.org/protocol/muc#owner");
1690		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1691			@Override
1692			public void onIqPacketReceived(Account account, IqPacket packet) {
1693				if (packet.getType() != IqPacket.TYPE.ERROR) {
1694					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1695					for (Field field : data.getFields()) {
1696						if (options.containsKey(field.getName())) {
1697							field.setValue(options.getString(field.getName()));
1698						}
1699					}
1700					data.submit();
1701					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1702					set.setTo(conversation.getJid().toBareJid());
1703					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1704					sendIqPacket(account, set, new OnIqPacketReceived() {
1705						@Override
1706						public void onIqPacketReceived(Account account, IqPacket packet) {
1707							if (packet.getType() == IqPacket.TYPE.RESULT) {
1708								if (callback != null) {
1709									callback.onPushSucceeded();
1710								}
1711							} else {
1712								if (callback != null) {
1713									callback.onPushFailed();
1714								}
1715							}
1716						}
1717					});
1718				} else {
1719					if (callback != null) {
1720						callback.onPushFailed();
1721					}
1722				}
1723			}
1724		});
1725	}
1726
1727	public void pushSubjectToConference(final Conversation conference, final String subject) {
1728		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1729		this.sendMessagePacket(conference.getAccount(), packet);
1730		final MucOptions mucOptions = conference.getMucOptions();
1731		final MucOptions.User self = mucOptions.getSelf();
1732		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1733			Bundle options = new Bundle();
1734			options.putString("muc#roomconfig_persistentroom", "1");
1735			this.pushConferenceConfiguration(conference, options, null);
1736		}
1737	}
1738
1739	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1740		final Jid jid = user.toBareJid();
1741		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1742		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1743			@Override
1744			public void onIqPacketReceived(Account account, IqPacket packet) {
1745				if (packet.getType() == IqPacket.TYPE.RESULT) {
1746					callback.onAffiliationChangedSuccessful(jid);
1747				} else {
1748					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1749				}
1750			}
1751		});
1752	}
1753
1754	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1755		List<Jid> jids = new ArrayList<>();
1756		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1757			if (user.getAffiliation() == before && user.getJid() != null) {
1758				jids.add(user.getJid());
1759			}
1760		}
1761		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1762		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1763	}
1764
1765	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1766		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1767		Log.d(Config.LOGTAG, request.toString());
1768		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1769			@Override
1770			public void onIqPacketReceived(Account account, IqPacket packet) {
1771				Log.d(Config.LOGTAG, packet.toString());
1772				if (packet.getType() == IqPacket.TYPE.RESULT) {
1773					callback.onRoleChangedSuccessful(nick);
1774				} else {
1775					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1776				}
1777			}
1778		});
1779	}
1780
1781	public void disconnect(Account account, boolean force) {
1782		if ((account.getStatus() == Account.State.ONLINE)
1783				|| (account.getStatus() == Account.State.DISABLED)) {
1784			if (!force) {
1785				List<Conversation> conversations = getConversations();
1786				for (Conversation conversation : conversations) {
1787					if (conversation.getAccount() == account) {
1788						if (conversation.getMode() == Conversation.MODE_MULTI) {
1789							leaveMuc(conversation);
1790						} else {
1791							if (conversation.endOtrIfNeeded()) {
1792								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1793										+ ": ended otr session with "
1794										+ conversation.getJid());
1795							}
1796						}
1797					}
1798				}
1799				sendOfflinePresence(account);
1800			}
1801			account.getXmppConnection().disconnect(force);
1802		}
1803	}
1804
1805	@Override
1806	public IBinder onBind(Intent intent) {
1807		return mBinder;
1808	}
1809
1810	public void updateMessage(Message message) {
1811		databaseBackend.updateMessage(message);
1812		updateConversationUi();
1813	}
1814
1815	protected void syncDirtyContacts(Account account) {
1816		for (Contact contact : account.getRoster().getContacts()) {
1817			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1818				pushContactToServer(contact);
1819			}
1820			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1821				deleteContactOnServer(contact);
1822			}
1823		}
1824	}
1825
1826	public void createContact(Contact contact) {
1827		SharedPreferences sharedPref = getPreferences();
1828		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1829		if (autoGrant) {
1830			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1831			contact.setOption(Contact.Options.ASKING);
1832		}
1833		pushContactToServer(contact);
1834	}
1835
1836	public void onOtrSessionEstablished(Conversation conversation) {
1837		final Account account = conversation.getAccount();
1838		final Session otrSession = conversation.getOtrSession();
1839		Log.d(Config.LOGTAG,
1840				account.getJid().toBareJid() + " otr session established with "
1841						+ conversation.getJid() + "/"
1842						+ otrSession.getSessionID().getUserID());
1843		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
1844
1845			@Override
1846			public void onMessageFound(Message message) {
1847				SessionID id = otrSession.getSessionID();
1848				try {
1849					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1850				} catch (InvalidJidException e) {
1851					return;
1852				}
1853				if (message.needsUploading()) {
1854					mJingleConnectionManager.createNewConnection(message);
1855				} else {
1856					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
1857					if (outPacket != null) {
1858						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
1859						message.setStatus(Message.STATUS_SEND);
1860						databaseBackend.updateMessage(message);
1861						sendMessagePacket(account, outPacket);
1862					}
1863				}
1864				updateConversationUi();
1865			}
1866		});
1867	}
1868
1869	public boolean renewSymmetricKey(Conversation conversation) {
1870		Account account = conversation.getAccount();
1871		byte[] symmetricKey = new byte[32];
1872		this.mRandom.nextBytes(symmetricKey);
1873		Session otrSession = conversation.getOtrSession();
1874		if (otrSession != null) {
1875			MessagePacket packet = new MessagePacket();
1876			packet.setType(MessagePacket.TYPE_CHAT);
1877			packet.setFrom(account.getJid());
1878			packet.addChild("private", "urn:xmpp:carbons:2");
1879			packet.addChild("no-copy", "urn:xmpp:hints");
1880			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1881					+ otrSession.getSessionID().getUserID());
1882			try {
1883				packet.setBody(otrSession
1884						.transformSending(CryptoHelper.FILETRANSFER
1885								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1886				sendMessagePacket(account, packet);
1887				conversation.setSymmetricKey(symmetricKey);
1888				return true;
1889			} catch (OtrException e) {
1890				return false;
1891			}
1892		}
1893		return false;
1894	}
1895
1896	public void pushContactToServer(final Contact contact) {
1897		contact.resetOption(Contact.Options.DIRTY_DELETE);
1898		contact.setOption(Contact.Options.DIRTY_PUSH);
1899		final Account account = contact.getAccount();
1900		if (account.getStatus() == Account.State.ONLINE) {
1901			final boolean ask = contact.getOption(Contact.Options.ASKING);
1902			final boolean sendUpdates = contact
1903					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1904					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1905			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1906			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1907			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1908			if (sendUpdates) {
1909				sendPresencePacket(account,
1910						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1911			}
1912			if (ask) {
1913				sendPresencePacket(account,
1914						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1915			}
1916		}
1917	}
1918
1919	public void publishAvatar(final Account account,
1920							  final Uri image,
1921							  final UiCallback<Avatar> callback) {
1922		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1923		final int size = Config.AVATAR_SIZE;
1924		final Avatar avatar = getFileBackend()
1925				.getPepAvatar(image, size, format);
1926		if (avatar != null) {
1927			avatar.height = size;
1928			avatar.width = size;
1929			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1930				avatar.type = "image/webp";
1931			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1932				avatar.type = "image/jpeg";
1933			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1934				avatar.type = "image/png";
1935			}
1936			if (!getFileBackend().save(avatar)) {
1937				callback.error(R.string.error_saving_avatar, avatar);
1938				return;
1939			}
1940			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1941			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1942
1943				@Override
1944				public void onIqPacketReceived(Account account, IqPacket result) {
1945					if (result.getType() == IqPacket.TYPE.RESULT) {
1946						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1947								.publishAvatarMetadata(avatar);
1948						sendIqPacket(account, packet, new OnIqPacketReceived() {
1949
1950							@Override
1951							public void onIqPacketReceived(Account account,
1952														   IqPacket result) {
1953								if (result.getType() == IqPacket.TYPE.RESULT) {
1954									if (account.setAvatar(avatar.getFilename())) {
1955										getAvatarService().clear(account);
1956										databaseBackend.updateAccount(account);
1957									}
1958									callback.success(avatar);
1959								} else {
1960									callback.error(
1961											R.string.error_publish_avatar_server_reject,
1962											avatar);
1963								}
1964							}
1965						});
1966					} else {
1967						callback.error(
1968								R.string.error_publish_avatar_server_reject,
1969								avatar);
1970					}
1971				}
1972			});
1973		} else {
1974			callback.error(R.string.error_publish_avatar_converting, null);
1975		}
1976	}
1977
1978	public void fetchAvatar(Account account, Avatar avatar) {
1979		fetchAvatar(account, avatar, null);
1980	}
1981
1982	private static String generateFetchKey(Account account, final Avatar avatar) {
1983		return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1984	}
1985
1986	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1987		final String KEY = generateFetchKey(account, avatar);
1988		synchronized(this.mInProgressAvatarFetches) {
1989			if (this.mInProgressAvatarFetches.contains(KEY)) {
1990				return;
1991			} else {
1992				switch (avatar.origin) {
1993					case PEP:
1994						this.mInProgressAvatarFetches.add(KEY);
1995						fetchAvatarPep(account, avatar, callback);
1996						break;
1997					case VCARD:
1998						this.mInProgressAvatarFetches.add(KEY);
1999						fetchAvatarVcard(account, avatar, callback);
2000						break;
2001				}
2002			}
2003		}
2004	}
2005
2006	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2007		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2008		sendIqPacket(account, packet, new OnIqPacketReceived() {
2009
2010			@Override
2011			public void onIqPacketReceived(Account account, IqPacket result) {
2012				synchronized (mInProgressAvatarFetches) {
2013					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2014				}
2015				final String ERROR = account.getJid().toBareJid()
2016						+ ": fetching avatar for " + avatar.owner + " failed ";
2017				if (result.getType() == IqPacket.TYPE.RESULT) {
2018					avatar.image = mIqParser.avatarData(result);
2019					if (avatar.image != null) {
2020						if (getFileBackend().save(avatar)) {
2021							if (account.getJid().toBareJid().equals(avatar.owner)) {
2022								if (account.setAvatar(avatar.getFilename())) {
2023									databaseBackend.updateAccount(account);
2024								}
2025								getAvatarService().clear(account);
2026								updateConversationUi();
2027								updateAccountUi();
2028							} else {
2029								Contact contact = account.getRoster()
2030										.getContact(avatar.owner);
2031								contact.setAvatar(avatar);
2032								getAvatarService().clear(contact);
2033								updateConversationUi();
2034								updateRosterUi();
2035							}
2036							if (callback != null) {
2037								callback.success(avatar);
2038							}
2039							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2040									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2041							return;
2042						}
2043					} else {
2044
2045						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2046					}
2047				} else {
2048					Element error = result.findChild("error");
2049					if (error == null) {
2050						Log.d(Config.LOGTAG, ERROR + "(server error)");
2051					} else {
2052						Log.d(Config.LOGTAG, ERROR + error.toString());
2053					}
2054				}
2055				if (callback != null) {
2056					callback.error(0, null);
2057				}
2058
2059			}
2060		});
2061	}
2062
2063	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2064		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2065		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2066			@Override
2067			public void onIqPacketReceived(Account account, IqPacket packet) {
2068				synchronized (mInProgressAvatarFetches) {
2069					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2070				}
2071				if (packet.getType() == IqPacket.TYPE.RESULT) {
2072					Element vCard = packet.findChild("vCard", "vcard-temp");
2073					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2074					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2075					if (image != null) {
2076						avatar.image = image;
2077						if (getFileBackend().save(avatar)) {
2078							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2079									+ ": successfully fetched vCard avatar for " + avatar.owner);
2080							Contact contact = account.getRoster()
2081									.getContact(avatar.owner);
2082							contact.setAvatar(avatar);
2083							getAvatarService().clear(contact);
2084							updateConversationUi();
2085							updateRosterUi();
2086						}
2087					}
2088				}
2089			}
2090		});
2091	}
2092
2093	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2094		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2095		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2096
2097			@Override
2098			public void onIqPacketReceived(Account account, IqPacket packet) {
2099				if (packet.getType() == IqPacket.TYPE.RESULT) {
2100					Element pubsub = packet.findChild("pubsub",
2101							"http://jabber.org/protocol/pubsub");
2102					if (pubsub != null) {
2103						Element items = pubsub.findChild("items");
2104						if (items != null) {
2105							Avatar avatar = Avatar.parseMetadata(items);
2106							if (avatar != null) {
2107								avatar.owner = account.getJid().toBareJid();
2108								if (fileBackend.isAvatarCached(avatar)) {
2109									if (account.setAvatar(avatar.getFilename())) {
2110										databaseBackend.updateAccount(account);
2111									}
2112									getAvatarService().clear(account);
2113									callback.success(avatar);
2114								} else {
2115									fetchAvatarPep(account, avatar, callback);
2116								}
2117								return;
2118							}
2119						}
2120					}
2121				}
2122				callback.error(0, null);
2123			}
2124		});
2125	}
2126
2127	public void deleteContactOnServer(Contact contact) {
2128		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2129		contact.resetOption(Contact.Options.DIRTY_PUSH);
2130		contact.setOption(Contact.Options.DIRTY_DELETE);
2131		Account account = contact.getAccount();
2132		if (account.getStatus() == Account.State.ONLINE) {
2133			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2134			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2135			item.setAttribute("jid", contact.getJid().toString());
2136			item.setAttribute("subscription", "remove");
2137			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2138		}
2139	}
2140
2141	public void updateConversation(Conversation conversation) {
2142		this.databaseBackend.updateConversation(conversation);
2143	}
2144
2145	public void reconnectAccount(final Account account, final boolean force) {
2146		synchronized (account) {
2147			if (account.getXmppConnection() != null) {
2148				disconnect(account, force);
2149			}
2150			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2151
2152				synchronized (this.mInProgressAvatarFetches) {
2153					for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2154						final String KEY = iterator.next();
2155						if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2156							iterator.remove();
2157						}
2158					}
2159				}
2160
2161				if (account.getXmppConnection() == null) {
2162					account.setXmppConnection(createConnection(account));
2163				}
2164				Thread thread = new Thread(account.getXmppConnection());
2165				thread.start();
2166				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2167			} else {
2168				account.getRoster().clearPresences();
2169				account.setXmppConnection(null);
2170			}
2171		}
2172	}
2173
2174	public void reconnectAccountInBackground(final Account account) {
2175		new Thread(new Runnable() {
2176			@Override
2177			public void run() {
2178				reconnectAccount(account,false);
2179			}
2180		}).start();
2181	}
2182
2183	public void invite(Conversation conversation, Jid contact) {
2184		Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2185		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2186		sendMessagePacket(conversation.getAccount(), packet);
2187	}
2188
2189	public void directInvite(Conversation conversation, Jid jid) {
2190		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2191		sendMessagePacket(conversation.getAccount(),packet);
2192	}
2193
2194	public void resetSendingToWaiting(Account account) {
2195		for (Conversation conversation : getConversations()) {
2196			if (conversation.getAccount() == account) {
2197				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2198
2199					@Override
2200					public void onMessageFound(Message message) {
2201						markMessage(message, Message.STATUS_WAITING);
2202					}
2203				});
2204			}
2205		}
2206	}
2207
2208	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2209		if (uuid == null) {
2210			return null;
2211		}
2212		for (Conversation conversation : getConversations()) {
2213			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2214				final Message message = conversation.findSentMessageWithUuid(uuid);
2215				if (message != null) {
2216					markMessage(message, status);
2217				}
2218				return message;
2219			}
2220		}
2221		return null;
2222	}
2223
2224	public boolean markMessage(Conversation conversation, String uuid,
2225							   int status) {
2226		if (uuid == null) {
2227			return false;
2228		} else {
2229			Message message = conversation.findSentMessageWithUuid(uuid);
2230			if (message != null) {
2231				markMessage(message, status);
2232				return true;
2233			} else {
2234				return false;
2235			}
2236		}
2237	}
2238
2239	public void markMessage(Message message, int status) {
2240		if (status == Message.STATUS_SEND_FAILED
2241				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2242				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2243			return;
2244		}
2245		message.setStatus(status);
2246		databaseBackend.updateMessage(message);
2247		updateConversationUi();
2248	}
2249
2250	public SharedPreferences getPreferences() {
2251		return PreferenceManager
2252				.getDefaultSharedPreferences(getApplicationContext());
2253	}
2254
2255	public boolean forceEncryption() {
2256		return getPreferences().getBoolean("force_encryption", false);
2257	}
2258
2259	public boolean confirmMessages() {
2260		return getPreferences().getBoolean("confirm_messages", true);
2261	}
2262
2263	public boolean sendChatStates() {
2264		return getPreferences().getBoolean("chat_states", false);
2265	}
2266
2267	public boolean saveEncryptedMessages() {
2268		return !getPreferences().getBoolean("dont_save_encrypted", false);
2269	}
2270
2271	public boolean indicateReceived() {
2272		return getPreferences().getBoolean("indicate_received", false);
2273	}
2274
2275	public int unreadCount() {
2276		int count = 0;
2277		for(Conversation conversation : getConversations()) {
2278			count += conversation.unreadCount();
2279		}
2280		return count;
2281	}
2282
2283
2284	public void showErrorToastInUi(int resId) {
2285		if (mOnShowErrorToast != null) {
2286			mOnShowErrorToast.onShowErrorToast(resId);
2287		}
2288	}
2289
2290	public void updateConversationUi() {
2291		if (mOnConversationUpdate != null) {
2292			mOnConversationUpdate.onConversationUpdate();
2293		}
2294	}
2295
2296	public void updateAccountUi() {
2297		if (mOnAccountUpdate != null) {
2298			mOnAccountUpdate.onAccountUpdate();
2299		}
2300	}
2301
2302	public void updateRosterUi() {
2303		if (mOnRosterUpdate != null) {
2304			mOnRosterUpdate.onRosterUpdate();
2305		}
2306	}
2307
2308	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2309		if (mOnUpdateBlocklist != null) {
2310			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2311		}
2312	}
2313
2314	public void updateMucRosterUi() {
2315		if (mOnMucRosterUpdate != null) {
2316			mOnMucRosterUpdate.onMucRosterUpdate();
2317		}
2318	}
2319
2320	public void keyStatusUpdated() {
2321		if(mOnKeyStatusUpdated != null) {
2322			mOnKeyStatusUpdated.onKeyStatusUpdated();
2323		}
2324	}
2325
2326	public Account findAccountByJid(final Jid accountJid) {
2327		for (Account account : this.accounts) {
2328			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2329				return account;
2330			}
2331		}
2332		return null;
2333	}
2334
2335	public Conversation findConversationByUuid(String uuid) {
2336		for (Conversation conversation : getConversations()) {
2337			if (conversation.getUuid().equals(uuid)) {
2338				return conversation;
2339			}
2340		}
2341		return null;
2342	}
2343
2344	public void markRead(final Conversation conversation) {
2345		mNotificationService.clear(conversation);
2346		conversation.markRead();
2347		updateUnreadCountBadge();
2348	}
2349
2350	public synchronized void updateUnreadCountBadge() {
2351		int count = unreadCount();
2352		if (unreadCount != count) {
2353			Log.d(Config.LOGTAG, "update unread count to " + count);
2354			if (count > 0) {
2355				ShortcutBadger.with(getApplicationContext()).count(count);
2356			} else {
2357				ShortcutBadger.with(getApplicationContext()).remove();
2358			}
2359			unreadCount = count;
2360		}
2361	}
2362
2363	public void sendReadMarker(final Conversation conversation) {
2364		final Message markable = conversation.getLatestMarkableMessage();
2365		this.markRead(conversation);
2366		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2367			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2368			Account account = conversation.getAccount();
2369			final Jid to = markable.getCounterpart();
2370			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2371			this.sendMessagePacket(conversation.getAccount(), packet);
2372		}
2373		updateConversationUi();
2374	}
2375
2376	public SecureRandom getRNG() {
2377		return this.mRandom;
2378	}
2379
2380	public MemorizingTrustManager getMemorizingTrustManager() {
2381		return this.mMemorizingTrustManager;
2382	}
2383
2384	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2385		this.mMemorizingTrustManager = trustManager;
2386	}
2387
2388	public void updateMemorizingTrustmanager() {
2389		final MemorizingTrustManager tm;
2390		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2391		if (dontTrustSystemCAs) {
2392			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2393		} else {
2394			tm = new MemorizingTrustManager(getApplicationContext());
2395		}
2396		setMemorizingTrustManager(tm);
2397	}
2398
2399	public PowerManager getPowerManager() {
2400		return this.pm;
2401	}
2402
2403	public LruCache<String, Bitmap> getBitmapCache() {
2404		return this.mBitmapCache;
2405	}
2406
2407	public void syncRosterToDisk(final Account account) {
2408		Runnable runnable = new Runnable() {
2409
2410			@Override
2411			public void run() {
2412				databaseBackend.writeRoster(account.getRoster());
2413			}
2414		};
2415		mDatabaseExecutor.execute(runnable);
2416
2417	}
2418
2419	public List<String> getKnownHosts() {
2420		final List<String> hosts = new ArrayList<>();
2421		for (final Account account : getAccounts()) {
2422			if (!hosts.contains(account.getServer().toString())) {
2423				hosts.add(account.getServer().toString());
2424			}
2425			for (final Contact contact : account.getRoster().getContacts()) {
2426				if (contact.showInRoster()) {
2427					final String server = contact.getServer().toString();
2428					if (server != null && !hosts.contains(server)) {
2429						hosts.add(server);
2430					}
2431				}
2432			}
2433		}
2434		return hosts;
2435	}
2436
2437	public List<String> getKnownConferenceHosts() {
2438		final ArrayList<String> mucServers = new ArrayList<>();
2439		for (final Account account : accounts) {
2440			if (account.getXmppConnection() != null) {
2441				final String server = account.getXmppConnection().getMucServer();
2442				if (server != null && !mucServers.contains(server)) {
2443					mucServers.add(server);
2444				}
2445			}
2446		}
2447		return mucServers;
2448	}
2449
2450	public void sendMessagePacket(Account account, MessagePacket packet) {
2451		XmppConnection connection = account.getXmppConnection();
2452		if (connection != null) {
2453			connection.sendMessagePacket(packet);
2454		}
2455	}
2456
2457	public void sendPresencePacket(Account account, PresencePacket packet) {
2458		XmppConnection connection = account.getXmppConnection();
2459		if (connection != null) {
2460			connection.sendPresencePacket(packet);
2461		}
2462	}
2463
2464	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2465		final XmppConnection connection = account.getXmppConnection();
2466		if (connection != null) {
2467			connection.sendIqPacket(packet, callback);
2468		}
2469	}
2470
2471	public void sendPresence(final Account account) {
2472		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2473	}
2474
2475	public void sendOfflinePresence(final Account account) {
2476		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2477	}
2478
2479	public MessageGenerator getMessageGenerator() {
2480		return this.mMessageGenerator;
2481	}
2482
2483	public PresenceGenerator getPresenceGenerator() {
2484		return this.mPresenceGenerator;
2485	}
2486
2487	public IqGenerator getIqGenerator() {
2488		return this.mIqGenerator;
2489	}
2490
2491	public IqParser getIqParser() {
2492		return this.mIqParser;
2493	}
2494
2495	public JingleConnectionManager getJingleConnectionManager() {
2496		return this.mJingleConnectionManager;
2497	}
2498
2499	public MessageArchiveService getMessageArchiveService() {
2500		return this.mMessageArchiveService;
2501	}
2502
2503	public List<Contact> findContacts(Jid jid) {
2504		ArrayList<Contact> contacts = new ArrayList<>();
2505		for (Account account : getAccounts()) {
2506			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2507				Contact contact = account.getRoster().getContactFromRoster(jid);
2508				if (contact != null) {
2509					contacts.add(contact);
2510				}
2511			}
2512		}
2513		return contacts;
2514	}
2515
2516	public NotificationService getNotificationService() {
2517		return this.mNotificationService;
2518	}
2519
2520	public HttpConnectionManager getHttpConnectionManager() {
2521		return this.mHttpConnectionManager;
2522	}
2523
2524	public void resendFailedMessages(final Message message) {
2525		final Collection<Message> messages = new ArrayList<>();
2526		Message current = message;
2527		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2528			messages.add(current);
2529			if (current.mergeable(current.next())) {
2530				current = current.next();
2531			} else {
2532				break;
2533			}
2534		}
2535		for (final Message msg : messages) {
2536			msg.setTime(System.currentTimeMillis());
2537			markMessage(msg, Message.STATUS_WAITING);
2538			this.resendMessage(msg,false);
2539		}
2540	}
2541
2542	public void clearConversationHistory(final Conversation conversation) {
2543		conversation.clearMessages();
2544		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2545		new Thread(new Runnable() {
2546			@Override
2547			public void run() {
2548				databaseBackend.deleteMessagesInConversation(conversation);
2549			}
2550		}).start();
2551	}
2552
2553	public void sendBlockRequest(final Blockable blockable) {
2554		if (blockable != null && blockable.getBlockedJid() != null) {
2555			final Jid jid = blockable.getBlockedJid();
2556			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2557
2558				@Override
2559				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2560					if (packet.getType() == IqPacket.TYPE.RESULT) {
2561						account.getBlocklist().add(jid);
2562						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2563					}
2564				}
2565			});
2566		}
2567	}
2568
2569	public void sendUnblockRequest(final Blockable blockable) {
2570		if (blockable != null && blockable.getJid() != null) {
2571			final Jid jid = blockable.getBlockedJid();
2572			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2573				@Override
2574				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2575					if (packet.getType() == IqPacket.TYPE.RESULT) {
2576						account.getBlocklist().remove(jid);
2577						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2578					}
2579				}
2580			});
2581		}
2582	}
2583
2584	public interface OnMoreMessagesLoaded {
2585		public void onMoreMessagesLoaded(int count, Conversation conversation);
2586
2587		public void informUser(int r);
2588	}
2589
2590	public interface OnAccountPasswordChanged {
2591		public void onPasswordChangeSucceeded();
2592
2593		public void onPasswordChangeFailed();
2594	}
2595
2596	public interface OnAffiliationChanged {
2597		public void onAffiliationChangedSuccessful(Jid jid);
2598
2599		public void onAffiliationChangeFailed(Jid jid, int resId);
2600	}
2601
2602	public interface OnRoleChanged {
2603		public void onRoleChangedSuccessful(String nick);
2604
2605		public void onRoleChangeFailed(String nick, int resid);
2606	}
2607
2608	public interface OnConversationUpdate {
2609		public void onConversationUpdate();
2610	}
2611
2612	public interface OnAccountUpdate {
2613		public void onAccountUpdate();
2614	}
2615
2616	public interface OnRosterUpdate {
2617		public void onRosterUpdate();
2618	}
2619
2620	public interface OnMucRosterUpdate {
2621		public void onMucRosterUpdate();
2622	}
2623
2624	public interface OnConferenceOptionsPushed {
2625		public void onPushSucceeded();
2626
2627		public void onPushFailed();
2628	}
2629
2630	public interface OnShowErrorToast {
2631		void onShowErrorToast(int resId);
2632	}
2633
2634	public class XmppConnectionBinder extends Binder {
2635		public XmppConnectionService getService() {
2636			return XmppConnectionService.this;
2637		}
2638	}
2639}