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