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