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