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		try {
 666			unregisterReceiver(this.mEventReceiver);
 667		} catch (IllegalArgumentException e) {
 668			//ignored
 669		}
 670		super.onDestroy();
 671	}
 672
 673	public void toggleScreenEventReceiver() {
 674		if (awayWhenScreenOff()) {
 675			final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
 676			filter.addAction(Intent.ACTION_SCREEN_OFF);
 677			registerReceiver(this.mEventReceiver, filter);
 678		} else {
 679			try {
 680				unregisterReceiver(this.mEventReceiver);
 681			} catch (IllegalArgumentException e) {
 682				//ignored
 683			}
 684		}
 685	}
 686
 687	public void toggleForegroundService() {
 688		if (getPreferences().getBoolean("keep_foreground_service", false)) {
 689			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 690		} else {
 691			stopForeground(true);
 692		}
 693	}
 694
 695	@Override
 696	public void onTaskRemoved(final Intent rootIntent) {
 697		super.onTaskRemoved(rootIntent);
 698		if (!getPreferences().getBoolean("keep_foreground_service",false)) {
 699			this.logoutAndSave();
 700		}
 701	}
 702
 703	private void logoutAndSave() {
 704		for (final Account account : accounts) {
 705			databaseBackend.writeRoster(account.getRoster());
 706			if (account.getXmppConnection() != null) {
 707				disconnect(account, false);
 708			}
 709		}
 710		Context context = getApplicationContext();
 711		AlarmManager alarmManager = (AlarmManager) context
 712				.getSystemService(Context.ALARM_SERVICE);
 713		Intent intent = new Intent(context, EventReceiver.class);
 714		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 715		Log.d(Config.LOGTAG, "good bye");
 716		stopSelf();
 717	}
 718
 719	protected void scheduleWakeUpCall(int seconds, int requestCode) {
 720		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
 721
 722		Context context = getApplicationContext();
 723		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 724
 725		Intent intent = new Intent(context, EventReceiver.class);
 726		intent.setAction("ping");
 727		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
 728		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 729	}
 730
 731	public XmppConnection createConnection(final Account account) {
 732		final SharedPreferences sharedPref = getPreferences();
 733		account.setResource(sharedPref.getString("resource", "mobile")
 734				.toLowerCase(Locale.getDefault()));
 735		final XmppConnection connection = new XmppConnection(account, this);
 736		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 737		connection.setOnStatusChangedListener(this.statusListener);
 738		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 739		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 740		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 741		connection.setOnBindListener(this.mOnBindListener);
 742		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 743		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 744		return connection;
 745	}
 746
 747	public void sendChatState(Conversation conversation) {
 748		if (sendChatStates()) {
 749			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
 750			sendMessagePacket(conversation.getAccount(), packet);
 751		}
 752	}
 753
 754	private void sendFileMessage(final Message message, final boolean delay) {
 755		Log.d(Config.LOGTAG, "send file message");
 756		final Account account = message.getConversation().getAccount();
 757		final XmppConnection connection = account.getXmppConnection();
 758		if (connection != null && connection.getFeatures().httpUpload()) {
 759			mHttpConnectionManager.createNewUploadConnection(message, delay);
 760		} else {
 761			mJingleConnectionManager.createNewConnection(message);
 762		}
 763	}
 764
 765	public void sendMessage(final Message message) {
 766		sendMessage(message, false, false);
 767	}
 768
 769	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
 770		final Account account = message.getConversation().getAccount();
 771		final Conversation conversation = message.getConversation();
 772		account.deactivateGracePeriod();
 773		MessagePacket packet = null;
 774		boolean saveInDb = true;
 775		message.setStatus(Message.STATUS_WAITING);
 776
 777		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
 778			message.getConversation().endOtrIfNeeded();
 779			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
 780					new Conversation.OnMessageFound() {
 781				@Override
 782				public void onMessageFound(Message message) {
 783					markMessage(message,Message.STATUS_SEND_FAILED);
 784				}
 785			});
 786		}
 787
 788		if (account.isOnlineAndConnected()) {
 789			switch (message.getEncryption()) {
 790				case Message.ENCRYPTION_NONE:
 791					if (message.needsUploading()) {
 792						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 793							this.sendFileMessage(message,delay);
 794						} else {
 795							break;
 796						}
 797					} else {
 798						packet = mMessageGenerator.generateChat(message);
 799					}
 800					break;
 801				case Message.ENCRYPTION_PGP:
 802				case Message.ENCRYPTION_DECRYPTED:
 803					if (message.needsUploading()) {
 804						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 805							this.sendFileMessage(message,delay);
 806						} else {
 807							break;
 808						}
 809					} else {
 810						packet = mMessageGenerator.generatePgpChat(message);
 811					}
 812					break;
 813				case Message.ENCRYPTION_OTR:
 814					SessionImpl otrSession = conversation.getOtrSession();
 815					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
 816						try {
 817							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
 818						} catch (InvalidJidException e) {
 819							break;
 820						}
 821						if (message.needsUploading()) {
 822							mJingleConnectionManager.createNewConnection(message);
 823						} else {
 824							packet = mMessageGenerator.generateOtrChat(message);
 825						}
 826					} else if (otrSession == null) {
 827						if (message.fixCounterpart()) {
 828							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
 829						} else {
 830							break;
 831						}
 832					}
 833					break;
 834				case Message.ENCRYPTION_AXOLOTL:
 835					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 836					if (message.needsUploading()) {
 837						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 838							this.sendFileMessage(message,delay);
 839						} else {
 840							break;
 841						}
 842					} else {
 843						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
 844						if (axolotlMessage == null) {
 845							account.getAxolotlService().preparePayloadMessage(message, delay);
 846						} else {
 847							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
 848						}
 849					}
 850					break;
 851
 852			}
 853			if (packet != null) {
 854				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 855					message.setStatus(Message.STATUS_UNSEND);
 856				} else {
 857					message.setStatus(Message.STATUS_SEND);
 858				}
 859			}
 860		} else {
 861			switch(message.getEncryption()) {
 862				case Message.ENCRYPTION_DECRYPTED:
 863					if (!message.needsUploading()) {
 864						String pgpBody = message.getEncryptedBody();
 865						String decryptedBody = message.getBody();
 866						message.setBody(pgpBody);
 867						message.setEncryption(Message.ENCRYPTION_PGP);
 868						databaseBackend.createMessage(message);
 869						saveInDb = false;
 870						message.setBody(decryptedBody);
 871						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 872					}
 873					break;
 874				case Message.ENCRYPTION_OTR:
 875					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
 876						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
 877					}
 878					break;
 879				case Message.ENCRYPTION_AXOLOTL:
 880					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 881					break;
 882			}
 883		}
 884
 885		if (resend) {
 886			if (packet != null) {
 887				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 888					markMessage(message,Message.STATUS_UNSEND);
 889				} else {
 890					markMessage(message,Message.STATUS_SEND);
 891				}
 892			}
 893		} else {
 894			conversation.add(message);
 895			if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
 896				databaseBackend.createMessage(message);
 897			}
 898			updateConversationUi();
 899		}
 900		if (packet != null) {
 901			if (delay) {
 902				mMessageGenerator.addDelay(packet,message.getTimeSent());
 903			}
 904			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 905				if (this.sendChatStates()) {
 906					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
 907				}
 908			}
 909			sendMessagePacket(account, packet);
 910		}
 911	}
 912
 913	private void sendUnsentMessages(final Conversation conversation) {
 914		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 915
 916			@Override
 917			public void onMessageFound(Message message) {
 918				resendMessage(message, true);
 919			}
 920		});
 921	}
 922
 923	public void resendMessage(final Message message, final boolean delay) {
 924		sendMessage(message, true, delay);
 925	}
 926
 927	public void fetchRosterFromServer(final Account account) {
 928		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 929		if (!"".equals(account.getRosterVersion())) {
 930			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 931					+ ": fetching roster version " + account.getRosterVersion());
 932		} else {
 933			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 934		}
 935		iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
 936		sendIqPacket(account, iqPacket, mIqParser);
 937	}
 938
 939	public void fetchBookmarks(final Account account) {
 940		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 941		final Element query = iqPacket.query("jabber:iq:private");
 942		query.addChild("storage", "storage:bookmarks");
 943		final OnIqPacketReceived callback = new OnIqPacketReceived() {
 944
 945			@Override
 946			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 947				if (packet.getType() == IqPacket.TYPE.RESULT) {
 948					final Element query = packet.query();
 949					final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 950					final Element storage = query.findChild("storage", "storage:bookmarks");
 951					if (storage != null) {
 952						for (final Element item : storage.getChildren()) {
 953							if (item.getName().equals("conference")) {
 954								final Bookmark bookmark = Bookmark.parse(item, account);
 955								bookmarks.add(bookmark);
 956								Conversation conversation = find(bookmark);
 957								if (conversation != null) {
 958									conversation.setBookmark(bookmark);
 959								} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 960									conversation = findOrCreateConversation(
 961											account, bookmark.getJid(), true);
 962									conversation.setBookmark(bookmark);
 963									joinMuc(conversation);
 964								}
 965							}
 966						}
 967					}
 968					account.setBookmarks(bookmarks);
 969				} else {
 970					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fetch bookmarks");
 971				}
 972			}
 973		};
 974		sendIqPacket(account, iqPacket, callback);
 975	}
 976
 977	public void pushBookmarks(Account account) {
 978		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
 979		Element query = iqPacket.query("jabber:iq:private");
 980		Element storage = query.addChild("storage", "storage:bookmarks");
 981		for (Bookmark bookmark : account.getBookmarks()) {
 982			storage.addChild(bookmark);
 983		}
 984		sendIqPacket(account, iqPacket, mDefaultIqHandler);
 985	}
 986
 987	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
 988		if (mPhoneContactMergerThread != null) {
 989			mPhoneContactMergerThread.interrupt();
 990		}
 991		mPhoneContactMergerThread = new Thread(new Runnable() {
 992			@Override
 993			public void run() {
 994				Log.d(Config.LOGTAG,"start merging phone contacts with roster");
 995				for (Account account : accounts) {
 996					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
 997					for (Bundle phoneContact : phoneContacts) {
 998						if (Thread.interrupted()) {
 999							Log.d(Config.LOGTAG,"interrupted merging phone contacts");
1000							return;
1001						}
1002						Jid jid;
1003						try {
1004							jid = Jid.fromString(phoneContact.getString("jid"));
1005						} catch (final InvalidJidException e) {
1006							continue;
1007						}
1008						final Contact contact = account.getRoster().getContact(jid);
1009						String systemAccount = phoneContact.getInt("phoneid")
1010							+ "#"
1011							+ phoneContact.getString("lookup");
1012						contact.setSystemAccount(systemAccount);
1013						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1014							getAvatarService().clear(contact);
1015						}
1016						contact.setSystemName(phoneContact.getString("displayname"));
1017						withSystemAccounts.remove(contact);
1018					}
1019					for(Contact contact : withSystemAccounts) {
1020						contact.setSystemAccount(null);
1021						contact.setSystemName(null);
1022						if (contact.setPhotoUri(null)) {
1023							getAvatarService().clear(contact);
1024						}
1025					}
1026				}
1027				Log.d(Config.LOGTAG,"finished merging phone contacts");
1028				updateAccountUi();
1029			}
1030		});
1031		mPhoneContactMergerThread.start();
1032	}
1033
1034	private void restoreFromDatabase() {
1035		synchronized (this.conversations) {
1036			final Map<String, Account> accountLookupTable = new Hashtable<>();
1037			for (Account account : this.accounts) {
1038				accountLookupTable.put(account.getUuid(), account);
1039			}
1040			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1041			for (Conversation conversation : this.conversations) {
1042				Account account = accountLookupTable.get(conversation.getAccountUuid());
1043				conversation.setAccount(account);
1044			}
1045			Runnable runnable =new Runnable() {
1046				@Override
1047				public void run() {
1048					Log.d(Config.LOGTAG,"restoring roster");
1049					for(Account account : accounts) {
1050						databaseBackend.readRoster(account.getRoster());
1051						account.initAccountServices(XmppConnectionService.this);
1052					}
1053					getBitmapCache().evictAll();
1054					Looper.prepare();
1055					PhoneHelper.loadPhoneContacts(getApplicationContext(),
1056							new CopyOnWriteArrayList<Bundle>(),
1057							XmppConnectionService.this);
1058					Log.d(Config.LOGTAG,"restoring messages");
1059					for (Conversation conversation : conversations) {
1060						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1061						checkDeletedFiles(conversation);
1062					}
1063					mRestoredFromDatabase = true;
1064					Log.d(Config.LOGTAG,"restored all messages");
1065					updateConversationUi();
1066				}
1067			};
1068			mDatabaseExecutor.execute(runnable);
1069		}
1070	}
1071
1072	public List<Conversation> getConversations() {
1073		return this.conversations;
1074	}
1075
1076	private void checkDeletedFiles(Conversation conversation) {
1077		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1078
1079			@Override
1080			public void onMessageFound(Message message) {
1081				if (!getFileBackend().isFileAvailable(message)) {
1082					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1083					final int s = message.getStatus();
1084					if(s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1085						markMessage(message,Message.STATUS_SEND_FAILED);
1086					}
1087				}
1088			}
1089		});
1090	}
1091
1092	private void markFileDeleted(String uuid) {
1093		for (Conversation conversation : getConversations()) {
1094			Message message = conversation.findMessageWithFileAndUuid(uuid);
1095			if (message != null) {
1096				if (!getFileBackend().isFileAvailable(message)) {
1097					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1098					final int s = message.getStatus();
1099					if(s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1100						markMessage(message,Message.STATUS_SEND_FAILED);
1101					} else {
1102						updateConversationUi();
1103					}
1104				}
1105				return;
1106			}
1107		}
1108	}
1109
1110	public void populateWithOrderedConversations(final List<Conversation> list) {
1111		populateWithOrderedConversations(list, true);
1112	}
1113
1114	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1115		list.clear();
1116		if (includeNoFileUpload) {
1117			list.addAll(getConversations());
1118		} else {
1119			for (Conversation conversation : getConversations()) {
1120				if (conversation.getMode() == Conversation.MODE_SINGLE
1121						|| conversation.getAccount().httpUploadAvailable()) {
1122					list.add(conversation);
1123				}
1124			}
1125		}
1126		Collections.sort(list, new Comparator<Conversation>() {
1127			@Override
1128			public int compare(Conversation lhs, Conversation rhs) {
1129				Message left = lhs.getLatestMessage();
1130				Message right = rhs.getLatestMessage();
1131				if (left.getTimeSent() > right.getTimeSent()) {
1132					return -1;
1133				} else if (left.getTimeSent() < right.getTimeSent()) {
1134					return 1;
1135				} else {
1136					return 0;
1137				}
1138			}
1139		});
1140	}
1141
1142	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1143		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1144			return;
1145		}
1146		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1147		Runnable runnable = new Runnable() {
1148			@Override
1149			public void run() {
1150				final Account account = conversation.getAccount();
1151				List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1152				if (messages.size() > 0) {
1153					conversation.addAll(0, messages);
1154					checkDeletedFiles(conversation);
1155					callback.onMoreMessagesLoaded(messages.size(), conversation);
1156				} else if (conversation.hasMessagesLeftOnServer()
1157						&& account.isOnlineAndConnected()) {
1158					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1159							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1160						MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1161						if (query != null) {
1162							query.setCallback(callback);
1163						}
1164						callback.informUser(R.string.fetching_history_from_server);
1165					}
1166				}
1167			}
1168		};
1169		mDatabaseExecutor.execute(runnable);
1170	}
1171
1172	public List<Account> getAccounts() {
1173		return this.accounts;
1174	}
1175
1176	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1177		for (final Conversation conversation : haystack) {
1178			if (conversation.getContact() == contact) {
1179				return conversation;
1180			}
1181		}
1182		return null;
1183	}
1184
1185	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1186		if (jid == null) {
1187			return null;
1188		}
1189		for (final Conversation conversation : haystack) {
1190			if ((account == null || conversation.getAccount() == account)
1191					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1192				return conversation;
1193			}
1194		}
1195		return null;
1196	}
1197
1198	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1199		return this.findOrCreateConversation(account, jid, muc, null);
1200	}
1201
1202	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1203		synchronized (this.conversations) {
1204			Conversation conversation = find(account, jid);
1205			if (conversation != null) {
1206				return conversation;
1207			}
1208			conversation = databaseBackend.findConversation(account, jid);
1209			if (conversation != null) {
1210				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1211				conversation.setAccount(account);
1212				if (muc) {
1213					conversation.setMode(Conversation.MODE_MULTI);
1214					conversation.setContactJid(jid);
1215				} else {
1216					conversation.setMode(Conversation.MODE_SINGLE);
1217					conversation.setContactJid(jid.toBareJid());
1218				}
1219				conversation.setNextEncryption(-1);
1220				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1221				this.databaseBackend.updateConversation(conversation);
1222			} else {
1223				String conversationName;
1224				Contact contact = account.getRoster().getContact(jid);
1225				if (contact != null) {
1226					conversationName = contact.getDisplayName();
1227				} else {
1228					conversationName = jid.getLocalpart();
1229				}
1230				if (muc) {
1231					conversation = new Conversation(conversationName, account, jid,
1232							Conversation.MODE_MULTI);
1233				} else {
1234					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1235							Conversation.MODE_SINGLE);
1236				}
1237				this.databaseBackend.createConversation(conversation);
1238			}
1239			if (account.getXmppConnection() != null
1240					&& account.getXmppConnection().getFeatures().mam()
1241					&& !muc) {
1242				if (query == null) {
1243					this.mMessageArchiveService.query(conversation);
1244				} else {
1245					if (query.getConversation() == null) {
1246						this.mMessageArchiveService.query(conversation, query.getStart());
1247					}
1248				}
1249			}
1250			checkDeletedFiles(conversation);
1251			this.conversations.add(conversation);
1252			updateConversationUi();
1253			return conversation;
1254		}
1255	}
1256
1257	public void archiveConversation(Conversation conversation) {
1258		getNotificationService().clear(conversation);
1259		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1260		conversation.setNextEncryption(-1);
1261		synchronized (this.conversations) {
1262			if (conversation.getMode() == Conversation.MODE_MULTI) {
1263				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1264					Bookmark bookmark = conversation.getBookmark();
1265					if (bookmark != null && bookmark.autojoin()) {
1266						bookmark.setAutojoin(false);
1267						pushBookmarks(bookmark.getAccount());
1268					}
1269				}
1270				leaveMuc(conversation);
1271			} else {
1272				conversation.endOtrIfNeeded();
1273			}
1274			this.databaseBackend.updateConversation(conversation);
1275			this.conversations.remove(conversation);
1276			updateConversationUi();
1277		}
1278	}
1279
1280	public void createAccount(final Account account) {
1281		account.initAccountServices(this);
1282		databaseBackend.createAccount(account);
1283		this.accounts.add(account);
1284		this.reconnectAccountInBackground(account);
1285		updateAccountUi();
1286	}
1287
1288	public void updateAccount(final Account account) {
1289		this.statusListener.onStatusChanged(account);
1290		databaseBackend.updateAccount(account);
1291		reconnectAccount(account, false, true);
1292		updateAccountUi();
1293		getNotificationService().updateErrorNotification();
1294	}
1295
1296	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1297		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1298		sendIqPacket(account, iq, new OnIqPacketReceived() {
1299			@Override
1300			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1301				if (packet.getType() == IqPacket.TYPE.RESULT) {
1302					account.setPassword(newPassword);
1303					databaseBackend.updateAccount(account);
1304					callback.onPasswordChangeSucceeded();
1305				} else {
1306					callback.onPasswordChangeFailed();
1307				}
1308			}
1309		});
1310	}
1311
1312	public void deleteAccount(final Account account) {
1313		synchronized (this.conversations) {
1314			for (final Conversation conversation : conversations) {
1315				if (conversation.getAccount() == account) {
1316					if (conversation.getMode() == Conversation.MODE_MULTI) {
1317						leaveMuc(conversation);
1318					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1319						conversation.endOtrIfNeeded();
1320					}
1321					conversations.remove(conversation);
1322				}
1323			}
1324			if (account.getXmppConnection() != null) {
1325				this.disconnect(account, true);
1326			}
1327			databaseBackend.deleteAccount(account);
1328			this.accounts.remove(account);
1329			updateAccountUi();
1330			getNotificationService().updateErrorNotification();
1331		}
1332	}
1333
1334	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1335		synchronized (this) {
1336			if (checkListeners()) {
1337				switchToForeground();
1338			}
1339			this.mOnConversationUpdate = listener;
1340			this.mNotificationService.setIsInForeground(true);
1341			if (this.convChangedListenerCount < 2) {
1342				this.convChangedListenerCount++;
1343			}
1344		}
1345	}
1346
1347	public void removeOnConversationListChangedListener() {
1348		synchronized (this) {
1349			this.convChangedListenerCount--;
1350			if (this.convChangedListenerCount <= 0) {
1351				this.convChangedListenerCount = 0;
1352				this.mOnConversationUpdate = null;
1353				this.mNotificationService.setIsInForeground(false);
1354				if (checkListeners()) {
1355					switchToBackground();
1356				}
1357			}
1358		}
1359	}
1360
1361	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1362		synchronized (this) {
1363			if (checkListeners()) {
1364				switchToForeground();
1365			}
1366			this.mOnShowErrorToast = onShowErrorToast;
1367			if (this.showErrorToastListenerCount < 2) {
1368				this.showErrorToastListenerCount++;
1369			}
1370		}
1371		this.mOnShowErrorToast = onShowErrorToast;
1372	}
1373
1374	public void removeOnShowErrorToastListener() {
1375		synchronized (this) {
1376			this.showErrorToastListenerCount--;
1377			if (this.showErrorToastListenerCount <= 0) {
1378				this.showErrorToastListenerCount = 0;
1379				this.mOnShowErrorToast = null;
1380				if (checkListeners()) {
1381					switchToBackground();
1382				}
1383			}
1384		}
1385	}
1386
1387	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1388		synchronized (this) {
1389			if (checkListeners()) {
1390				switchToForeground();
1391			}
1392			this.mOnAccountUpdate = listener;
1393			if (this.accountChangedListenerCount < 2) {
1394				this.accountChangedListenerCount++;
1395			}
1396		}
1397	}
1398
1399	public void removeOnAccountListChangedListener() {
1400		synchronized (this) {
1401			this.accountChangedListenerCount--;
1402			if (this.accountChangedListenerCount <= 0) {
1403				this.mOnAccountUpdate = null;
1404				this.accountChangedListenerCount = 0;
1405				if (checkListeners()) {
1406					switchToBackground();
1407				}
1408			}
1409		}
1410	}
1411
1412	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1413		synchronized (this) {
1414			if (checkListeners()) {
1415				switchToForeground();
1416			}
1417			this.mOnRosterUpdate = listener;
1418			if (this.rosterChangedListenerCount < 2) {
1419				this.rosterChangedListenerCount++;
1420			}
1421		}
1422	}
1423
1424	public void removeOnRosterUpdateListener() {
1425		synchronized (this) {
1426			this.rosterChangedListenerCount--;
1427			if (this.rosterChangedListenerCount <= 0) {
1428				this.rosterChangedListenerCount = 0;
1429				this.mOnRosterUpdate = null;
1430				if (checkListeners()) {
1431					switchToBackground();
1432				}
1433			}
1434		}
1435	}
1436
1437	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1438		synchronized (this) {
1439			if (checkListeners()) {
1440				switchToForeground();
1441			}
1442			this.mOnUpdateBlocklist = listener;
1443			if (this.updateBlocklistListenerCount < 2) {
1444				this.updateBlocklistListenerCount++;
1445			}
1446		}
1447	}
1448
1449	public void removeOnUpdateBlocklistListener() {
1450		synchronized (this) {
1451			this.updateBlocklistListenerCount--;
1452			if (this.updateBlocklistListenerCount <= 0) {
1453				this.updateBlocklistListenerCount = 0;
1454				this.mOnUpdateBlocklist = null;
1455				if (checkListeners()) {
1456					switchToBackground();
1457				}
1458			}
1459		}
1460	}
1461
1462	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1463		synchronized (this) {
1464			if (checkListeners()) {
1465				switchToForeground();
1466			}
1467			this.mOnKeyStatusUpdated = listener;
1468			if (this.keyStatusUpdatedListenerCount < 2) {
1469				this.keyStatusUpdatedListenerCount++;
1470			}
1471		}
1472	}
1473
1474	public void removeOnNewKeysAvailableListener() {
1475		synchronized (this) {
1476			this.keyStatusUpdatedListenerCount--;
1477			if (this.keyStatusUpdatedListenerCount <= 0) {
1478				this.keyStatusUpdatedListenerCount = 0;
1479				this.mOnKeyStatusUpdated = null;
1480				if (checkListeners()) {
1481					switchToBackground();
1482				}
1483			}
1484		}
1485	}
1486
1487	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1488		synchronized (this) {
1489			if (checkListeners()) {
1490				switchToForeground();
1491			}
1492			this.mOnMucRosterUpdate = listener;
1493			if (this.mucRosterChangedListenerCount < 2) {
1494				this.mucRosterChangedListenerCount++;
1495			}
1496		}
1497	}
1498
1499	public void removeOnMucRosterUpdateListener() {
1500		synchronized (this) {
1501			this.mucRosterChangedListenerCount--;
1502			if (this.mucRosterChangedListenerCount <= 0) {
1503				this.mucRosterChangedListenerCount = 0;
1504				this.mOnMucRosterUpdate = null;
1505				if (checkListeners()) {
1506					switchToBackground();
1507				}
1508			}
1509		}
1510	}
1511
1512	private boolean checkListeners() {
1513		return (this.mOnAccountUpdate == null
1514				&& this.mOnConversationUpdate == null
1515				&& this.mOnRosterUpdate == null
1516				&& this.mOnUpdateBlocklist == null
1517				&& this.mOnShowErrorToast == null
1518				&& this.mOnKeyStatusUpdated == null);
1519	}
1520
1521	private void switchToForeground() {
1522		for (Account account : getAccounts()) {
1523			if (account.getStatus() == Account.State.ONLINE) {
1524				XmppConnection connection = account.getXmppConnection();
1525				if (connection != null && connection.getFeatures().csi()) {
1526					connection.sendActive();
1527				}
1528			}
1529		}
1530		Log.d(Config.LOGTAG, "app switched into foreground");
1531	}
1532
1533	private void switchToBackground() {
1534		for (Account account : getAccounts()) {
1535			if (account.getStatus() == Account.State.ONLINE) {
1536				XmppConnection connection = account.getXmppConnection();
1537				if (connection != null && connection.getFeatures().csi()) {
1538					connection.sendInactive();
1539				}
1540			}
1541		}
1542		for(Conversation conversation : getConversations()) {
1543			conversation.setIncomingChatState(ChatState.ACTIVE);
1544		}
1545		this.mNotificationService.setIsInForeground(false);
1546		Log.d(Config.LOGTAG, "app switched into background");
1547	}
1548
1549	private void connectMultiModeConversations(Account account) {
1550		List<Conversation> conversations = getConversations();
1551		for (Conversation conversation : conversations) {
1552			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1553				joinMuc(conversation,true);
1554			}
1555		}
1556	}
1557
1558	public void joinMuc(Conversation conversation) {
1559		joinMuc(conversation, false);
1560	}
1561
1562	private void joinMuc(Conversation conversation, boolean now) {
1563		Account account = conversation.getAccount();
1564		account.pendingConferenceJoins.remove(conversation);
1565		account.pendingConferenceLeaves.remove(conversation);
1566		if (account.getStatus() == Account.State.ONLINE || now) {
1567			conversation.resetMucOptions();
1568			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1569				@Override
1570				public void onConferenceConfigurationFetched(Conversation conversation) {
1571					Account account = conversation.getAccount();
1572					final String nick = conversation.getMucOptions().getProposedNick();
1573					final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1574					if (joinJid == null) {
1575						return; //safety net
1576					}
1577					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1578					PresencePacket packet = new PresencePacket();
1579					packet.setFrom(conversation.getAccount().getJid());
1580					packet.setTo(joinJid);
1581					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1582					if (conversation.getMucOptions().getPassword() != null) {
1583						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1584					}
1585
1586					if (conversation.getMucOptions().mamSupport()) {
1587						// Use MAM instead of the limited muc history to get history
1588						x.addChild("history").setAttribute("maxchars", "0");
1589					} else {
1590						// Fallback to muc history
1591						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1592					}
1593					String sig = account.getPgpSignature();
1594					if (sig != null) {
1595						packet.addChild("status").setContent("online");
1596						packet.addChild("x", "jabber:x:signed").setContent(sig);
1597					}
1598					sendPresencePacket(account, packet);
1599					fetchConferenceConfiguration(conversation);
1600					if (!joinJid.equals(conversation.getJid())) {
1601						conversation.setContactJid(joinJid);
1602						databaseBackend.updateConversation(conversation);
1603					}
1604					conversation.setHasMessagesLeftOnServer(false);
1605					if (conversation.getMucOptions().mamSupport()) {
1606						getMessageArchiveService().catchupMUC(conversation);
1607					}
1608				}
1609			});
1610
1611		} else {
1612			account.pendingConferenceJoins.add(conversation);
1613		}
1614	}
1615
1616	public void providePasswordForMuc(Conversation conversation, String password) {
1617		if (conversation.getMode() == Conversation.MODE_MULTI) {
1618			conversation.getMucOptions().setPassword(password);
1619			if (conversation.getBookmark() != null) {
1620				conversation.getBookmark().setAutojoin(true);
1621				pushBookmarks(conversation.getAccount());
1622			}
1623			databaseBackend.updateConversation(conversation);
1624			joinMuc(conversation);
1625		}
1626	}
1627
1628	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1629		final MucOptions options = conversation.getMucOptions();
1630		final Jid joinJid = options.createJoinJid(nick);
1631		if (options.online()) {
1632			Account account = conversation.getAccount();
1633			options.setOnRenameListener(new OnRenameListener() {
1634
1635				@Override
1636				public void onSuccess() {
1637					conversation.setContactJid(joinJid);
1638					databaseBackend.updateConversation(conversation);
1639					Bookmark bookmark = conversation.getBookmark();
1640					if (bookmark != null) {
1641						bookmark.setNick(nick);
1642						pushBookmarks(bookmark.getAccount());
1643					}
1644					callback.success(conversation);
1645				}
1646
1647				@Override
1648				public void onFailure() {
1649					callback.error(R.string.nick_in_use, conversation);
1650				}
1651			});
1652
1653			PresencePacket packet = new PresencePacket();
1654			packet.setTo(joinJid);
1655			packet.setFrom(conversation.getAccount().getJid());
1656
1657			String sig = account.getPgpSignature();
1658			if (sig != null) {
1659				packet.addChild("status").setContent("online");
1660				packet.addChild("x", "jabber:x:signed").setContent(sig);
1661			}
1662			sendPresencePacket(account, packet);
1663		} else {
1664			conversation.setContactJid(joinJid);
1665			databaseBackend.updateConversation(conversation);
1666			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1667				Bookmark bookmark = conversation.getBookmark();
1668				if (bookmark != null) {
1669					bookmark.setNick(nick);
1670					pushBookmarks(bookmark.getAccount());
1671				}
1672				joinMuc(conversation);
1673			}
1674		}
1675	}
1676
1677	public void leaveMuc(Conversation conversation) {
1678		Account account = conversation.getAccount();
1679		account.pendingConferenceJoins.remove(conversation);
1680		account.pendingConferenceLeaves.remove(conversation);
1681		if (account.getStatus() == Account.State.ONLINE) {
1682			PresencePacket packet = new PresencePacket();
1683			packet.setTo(conversation.getJid());
1684			packet.setFrom(conversation.getAccount().getJid());
1685			packet.setAttribute("type", "unavailable");
1686			sendPresencePacket(conversation.getAccount(), packet);
1687			conversation.getMucOptions().setOffline();
1688			conversation.deregisterWithBookmark();
1689			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1690					+ ": leaving muc " + conversation.getJid());
1691		} else {
1692			account.pendingConferenceLeaves.add(conversation);
1693		}
1694	}
1695
1696	private String findConferenceServer(final Account account) {
1697		String server;
1698		if (account.getXmppConnection() != null) {
1699			server = account.getXmppConnection().getMucServer();
1700			if (server != null) {
1701				return server;
1702			}
1703		}
1704		for (Account other : getAccounts()) {
1705			if (other != account && other.getXmppConnection() != null) {
1706				server = other.getXmppConnection().getMucServer();
1707				if (server != null) {
1708					return server;
1709				}
1710			}
1711		}
1712		return null;
1713	}
1714
1715	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1716		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1717		if (account.getStatus() == Account.State.ONLINE) {
1718			try {
1719				String server = findConferenceServer(account);
1720				if (server == null) {
1721					if (callback != null) {
1722						callback.error(R.string.no_conference_server_found, null);
1723					}
1724					return;
1725				}
1726				String name = new BigInteger(75, getRNG()).toString(32);
1727				Jid jid = Jid.fromParts(name, server, null);
1728				final Conversation conversation = findOrCreateConversation(account, jid, true);
1729				joinMuc(conversation);
1730				Bundle options = new Bundle();
1731				options.putString("muc#roomconfig_persistentroom", "1");
1732				options.putString("muc#roomconfig_membersonly", "1");
1733				options.putString("muc#roomconfig_publicroom", "0");
1734				options.putString("muc#roomconfig_whois", "anyone");
1735				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1736					@Override
1737					public void onPushSucceeded() {
1738						for (Jid invite : jids) {
1739							invite(conversation, invite);
1740						}
1741						if (account.countPresences() > 1) {
1742							directInvite(conversation, account.getJid().toBareJid());
1743						}
1744						if (callback != null) {
1745							callback.success(conversation);
1746						}
1747					}
1748
1749					@Override
1750					public void onPushFailed() {
1751						if (callback != null) {
1752							callback.error(R.string.conference_creation_failed, conversation);
1753						}
1754					}
1755				});
1756
1757			} catch (InvalidJidException e) {
1758				if (callback != null) {
1759					callback.error(R.string.conference_creation_failed, null);
1760				}
1761			}
1762		} else {
1763			if (callback != null) {
1764				callback.error(R.string.not_connected_try_again, null);
1765			}
1766		}
1767	}
1768
1769	public void fetchConferenceConfiguration(final Conversation conversation) {
1770		fetchConferenceConfiguration(conversation, null);
1771	}
1772
1773	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1774		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1775		request.setTo(conversation.getJid().toBareJid());
1776		request.query("http://jabber.org/protocol/disco#info");
1777		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1778			@Override
1779			public void onIqPacketReceived(Account account, IqPacket packet) {
1780				if (packet.getType() == IqPacket.TYPE.RESULT) {
1781					ArrayList<String> features = new ArrayList<>();
1782					for (Element child : packet.query().getChildren()) {
1783						if (child != null && child.getName().equals("feature")) {
1784							String var = child.getAttribute("var");
1785							if (var != null) {
1786								features.add(var);
1787							}
1788						}
1789					}
1790					conversation.getMucOptions().updateFeatures(features);
1791					if (callback != null) {
1792						callback.onConferenceConfigurationFetched(conversation);
1793					}
1794					updateConversationUi();
1795				}
1796			}
1797		});
1798	}
1799
1800	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1801		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1802		request.setTo(conversation.getJid().toBareJid());
1803		request.query("http://jabber.org/protocol/muc#owner");
1804		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1805			@Override
1806			public void onIqPacketReceived(Account account, IqPacket packet) {
1807				if (packet.getType() == IqPacket.TYPE.RESULT) {
1808					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1809					for (Field field : data.getFields()) {
1810						if (options.containsKey(field.getFieldName())) {
1811							field.setValue(options.getString(field.getFieldName()));
1812						}
1813					}
1814					data.submit();
1815					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1816					set.setTo(conversation.getJid().toBareJid());
1817					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1818					sendIqPacket(account, set, new OnIqPacketReceived() {
1819						@Override
1820						public void onIqPacketReceived(Account account, IqPacket packet) {
1821							if (callback != null) {
1822								if (packet.getType() == IqPacket.TYPE.RESULT) {
1823									callback.onPushSucceeded();
1824								} else {
1825									callback.onPushFailed();
1826								}
1827							}
1828						}
1829					});
1830				} else {
1831					if (callback != null) {
1832						callback.onPushFailed();
1833					}
1834				}
1835			}
1836		});
1837	}
1838
1839	public void pushSubjectToConference(final Conversation conference, final String subject) {
1840		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1841		this.sendMessagePacket(conference.getAccount(), packet);
1842		final MucOptions mucOptions = conference.getMucOptions();
1843		final MucOptions.User self = mucOptions.getSelf();
1844		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1845			Bundle options = new Bundle();
1846			options.putString("muc#roomconfig_persistentroom", "1");
1847			this.pushConferenceConfiguration(conference, options, null);
1848		}
1849	}
1850
1851	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1852		final Jid jid = user.toBareJid();
1853		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1854		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1855			@Override
1856			public void onIqPacketReceived(Account account, IqPacket packet) {
1857				if (packet.getType() == IqPacket.TYPE.RESULT) {
1858					callback.onAffiliationChangedSuccessful(jid);
1859				} else {
1860					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1861				}
1862			}
1863		});
1864	}
1865
1866	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1867		List<Jid> jids = new ArrayList<>();
1868		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1869			if (user.getAffiliation() == before && user.getJid() != null) {
1870				jids.add(user.getJid());
1871			}
1872		}
1873		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1874		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1875	}
1876
1877	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1878		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1879		Log.d(Config.LOGTAG, request.toString());
1880		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1881			@Override
1882			public void onIqPacketReceived(Account account, IqPacket packet) {
1883				Log.d(Config.LOGTAG, packet.toString());
1884				if (packet.getType() == IqPacket.TYPE.RESULT) {
1885					callback.onRoleChangedSuccessful(nick);
1886				} else {
1887					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1888				}
1889			}
1890		});
1891	}
1892
1893	public void disconnect(Account account, boolean force) {
1894		if ((account.getStatus() == Account.State.ONLINE)
1895				|| (account.getStatus() == Account.State.DISABLED)) {
1896			if (!force) {
1897				List<Conversation> conversations = getConversations();
1898				for (Conversation conversation : conversations) {
1899					if (conversation.getAccount() == account) {
1900						if (conversation.getMode() == Conversation.MODE_MULTI) {
1901							leaveMuc(conversation);
1902						} else {
1903							if (conversation.endOtrIfNeeded()) {
1904								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1905										+ ": ended otr session with "
1906										+ conversation.getJid());
1907							}
1908						}
1909					}
1910				}
1911				sendOfflinePresence(account);
1912			}
1913			account.getXmppConnection().disconnect(force);
1914		}
1915	}
1916
1917	@Override
1918	public IBinder onBind(Intent intent) {
1919		return mBinder;
1920	}
1921
1922	public void updateMessage(Message message) {
1923		databaseBackend.updateMessage(message);
1924		updateConversationUi();
1925	}
1926
1927	protected void syncDirtyContacts(Account account) {
1928		for (Contact contact : account.getRoster().getContacts()) {
1929			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1930				pushContactToServer(contact);
1931			}
1932			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1933				deleteContactOnServer(contact);
1934			}
1935		}
1936	}
1937
1938	public void createContact(Contact contact) {
1939		SharedPreferences sharedPref = getPreferences();
1940		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1941		if (autoGrant) {
1942			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1943			contact.setOption(Contact.Options.ASKING);
1944		}
1945		pushContactToServer(contact);
1946	}
1947
1948	public void onOtrSessionEstablished(Conversation conversation) {
1949		final Account account = conversation.getAccount();
1950		final Session otrSession = conversation.getOtrSession();
1951		Log.d(Config.LOGTAG,
1952				account.getJid().toBareJid() + " otr session established with "
1953						+ conversation.getJid() + "/"
1954						+ otrSession.getSessionID().getUserID());
1955		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
1956
1957			@Override
1958			public void onMessageFound(Message message) {
1959				SessionID id = otrSession.getSessionID();
1960				try {
1961					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1962				} catch (InvalidJidException e) {
1963					return;
1964				}
1965				if (message.needsUploading()) {
1966					mJingleConnectionManager.createNewConnection(message);
1967				} else {
1968					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
1969					if (outPacket != null) {
1970						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
1971						message.setStatus(Message.STATUS_SEND);
1972						databaseBackend.updateMessage(message);
1973						sendMessagePacket(account, outPacket);
1974					}
1975				}
1976				updateConversationUi();
1977			}
1978		});
1979	}
1980
1981	public boolean renewSymmetricKey(Conversation conversation) {
1982		Account account = conversation.getAccount();
1983		byte[] symmetricKey = new byte[32];
1984		this.mRandom.nextBytes(symmetricKey);
1985		Session otrSession = conversation.getOtrSession();
1986		if (otrSession != null) {
1987			MessagePacket packet = new MessagePacket();
1988			packet.setType(MessagePacket.TYPE_CHAT);
1989			packet.setFrom(account.getJid());
1990			MessageGenerator.addMessageHints(packet);
1991			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1992					+ otrSession.getSessionID().getUserID());
1993			try {
1994				packet.setBody(otrSession
1995						.transformSending(CryptoHelper.FILETRANSFER
1996								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1997				sendMessagePacket(account, packet);
1998				conversation.setSymmetricKey(symmetricKey);
1999				return true;
2000			} catch (OtrException e) {
2001				return false;
2002			}
2003		}
2004		return false;
2005	}
2006
2007	public void pushContactToServer(final Contact contact) {
2008		contact.resetOption(Contact.Options.DIRTY_DELETE);
2009		contact.setOption(Contact.Options.DIRTY_PUSH);
2010		final Account account = contact.getAccount();
2011		if (account.getStatus() == Account.State.ONLINE) {
2012			final boolean ask = contact.getOption(Contact.Options.ASKING);
2013			final boolean sendUpdates = contact
2014					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2015					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2016			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2017			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2018			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2019			if (sendUpdates) {
2020				sendPresencePacket(account,
2021						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2022			}
2023			if (ask) {
2024				sendPresencePacket(account,
2025						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2026			}
2027		}
2028	}
2029
2030	public void publishAvatar(final Account account,
2031							  final Uri image,
2032							  final UiCallback<Avatar> callback) {
2033		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2034		final int size = Config.AVATAR_SIZE;
2035		final Avatar avatar = getFileBackend()
2036				.getPepAvatar(image, size, format);
2037		if (avatar != null) {
2038			avatar.height = size;
2039			avatar.width = size;
2040			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2041				avatar.type = "image/webp";
2042			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2043				avatar.type = "image/jpeg";
2044			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2045				avatar.type = "image/png";
2046			}
2047			if (!getFileBackend().save(avatar)) {
2048				callback.error(R.string.error_saving_avatar, avatar);
2049				return;
2050			}
2051			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2052			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2053
2054				@Override
2055				public void onIqPacketReceived(Account account, IqPacket result) {
2056					if (result.getType() == IqPacket.TYPE.RESULT) {
2057						final IqPacket packet = XmppConnectionService.this.mIqGenerator
2058								.publishAvatarMetadata(avatar);
2059						sendIqPacket(account, packet, new OnIqPacketReceived() {
2060							@Override
2061							public void onIqPacketReceived(Account account, IqPacket result) {
2062								if (result.getType() == IqPacket.TYPE.RESULT) {
2063									if (account.setAvatar(avatar.getFilename())) {
2064										getAvatarService().clear(account);
2065										databaseBackend.updateAccount(account);
2066									}
2067									callback.success(avatar);
2068								} else {
2069									callback.error(
2070											R.string.error_publish_avatar_server_reject,
2071											avatar);
2072								}
2073							}
2074						});
2075					} else {
2076						callback.error(
2077								R.string.error_publish_avatar_server_reject,
2078								avatar);
2079					}
2080				}
2081			});
2082		} else {
2083			callback.error(R.string.error_publish_avatar_converting, null);
2084		}
2085	}
2086
2087	public void fetchAvatar(Account account, Avatar avatar) {
2088		fetchAvatar(account, avatar, null);
2089	}
2090
2091	private static String generateFetchKey(Account account, final Avatar avatar) {
2092		return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
2093	}
2094
2095	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2096		final String KEY = generateFetchKey(account, avatar);
2097		synchronized(this.mInProgressAvatarFetches) {
2098			if (this.mInProgressAvatarFetches.contains(KEY)) {
2099				return;
2100			} else {
2101				switch (avatar.origin) {
2102					case PEP:
2103						this.mInProgressAvatarFetches.add(KEY);
2104						fetchAvatarPep(account, avatar, callback);
2105						break;
2106					case VCARD:
2107						this.mInProgressAvatarFetches.add(KEY);
2108						fetchAvatarVcard(account, avatar, callback);
2109						break;
2110				}
2111			}
2112		}
2113	}
2114
2115	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2116		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2117		sendIqPacket(account, packet, new OnIqPacketReceived() {
2118
2119			@Override
2120			public void onIqPacketReceived(Account account, IqPacket result) {
2121				synchronized (mInProgressAvatarFetches) {
2122					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2123				}
2124				final String ERROR = account.getJid().toBareJid()
2125						+ ": fetching avatar for " + avatar.owner + " failed ";
2126				if (result.getType() == IqPacket.TYPE.RESULT) {
2127					avatar.image = mIqParser.avatarData(result);
2128					if (avatar.image != null) {
2129						if (getFileBackend().save(avatar)) {
2130							if (account.getJid().toBareJid().equals(avatar.owner)) {
2131								if (account.setAvatar(avatar.getFilename())) {
2132									databaseBackend.updateAccount(account);
2133								}
2134								getAvatarService().clear(account);
2135								updateConversationUi();
2136								updateAccountUi();
2137							} else {
2138								Contact contact = account.getRoster()
2139										.getContact(avatar.owner);
2140								contact.setAvatar(avatar);
2141								getAvatarService().clear(contact);
2142								updateConversationUi();
2143								updateRosterUi();
2144							}
2145							if (callback != null) {
2146								callback.success(avatar);
2147							}
2148							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2149									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2150							return;
2151						}
2152					} else {
2153
2154						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2155					}
2156				} else {
2157					Element error = result.findChild("error");
2158					if (error == null) {
2159						Log.d(Config.LOGTAG, ERROR + "(server error)");
2160					} else {
2161						Log.d(Config.LOGTAG, ERROR + error.toString());
2162					}
2163				}
2164				if (callback != null) {
2165					callback.error(0, null);
2166				}
2167
2168			}
2169		});
2170	}
2171
2172	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2173		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2174		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2175			@Override
2176			public void onIqPacketReceived(Account account, IqPacket packet) {
2177				synchronized (mInProgressAvatarFetches) {
2178					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2179				}
2180				if (packet.getType() == IqPacket.TYPE.RESULT) {
2181					Element vCard = packet.findChild("vCard", "vcard-temp");
2182					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2183					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2184					if (image != null) {
2185						avatar.image = image;
2186						if (getFileBackend().save(avatar)) {
2187							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2188									+ ": successfully fetched vCard avatar for " + avatar.owner);
2189							Contact contact = account.getRoster()
2190									.getContact(avatar.owner);
2191							contact.setAvatar(avatar);
2192							getAvatarService().clear(contact);
2193							updateConversationUi();
2194							updateRosterUi();
2195						}
2196					}
2197				}
2198			}
2199		});
2200	}
2201
2202	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2203		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2204		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2205
2206			@Override
2207			public void onIqPacketReceived(Account account, IqPacket packet) {
2208				if (packet.getType() == IqPacket.TYPE.RESULT) {
2209					Element pubsub = packet.findChild("pubsub",
2210							"http://jabber.org/protocol/pubsub");
2211					if (pubsub != null) {
2212						Element items = pubsub.findChild("items");
2213						if (items != null) {
2214							Avatar avatar = Avatar.parseMetadata(items);
2215							if (avatar != null) {
2216								avatar.owner = account.getJid().toBareJid();
2217								if (fileBackend.isAvatarCached(avatar)) {
2218									if (account.setAvatar(avatar.getFilename())) {
2219										databaseBackend.updateAccount(account);
2220									}
2221									getAvatarService().clear(account);
2222									callback.success(avatar);
2223								} else {
2224									fetchAvatarPep(account, avatar, callback);
2225								}
2226								return;
2227							}
2228						}
2229					}
2230				}
2231				callback.error(0, null);
2232			}
2233		});
2234	}
2235
2236	public void deleteContactOnServer(Contact contact) {
2237		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2238		contact.resetOption(Contact.Options.DIRTY_PUSH);
2239		contact.setOption(Contact.Options.DIRTY_DELETE);
2240		Account account = contact.getAccount();
2241		if (account.getStatus() == Account.State.ONLINE) {
2242			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2243			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2244			item.setAttribute("jid", contact.getJid().toString());
2245			item.setAttribute("subscription", "remove");
2246			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2247		}
2248	}
2249
2250	public void updateConversation(Conversation conversation) {
2251		this.databaseBackend.updateConversation(conversation);
2252	}
2253
2254	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2255		synchronized (account) {
2256			if (account.getXmppConnection() != null) {
2257				disconnect(account, force);
2258			}
2259			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2260
2261				synchronized (this.mInProgressAvatarFetches) {
2262					for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2263						final String KEY = iterator.next();
2264						if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2265							iterator.remove();
2266						}
2267					}
2268				}
2269
2270				if (account.getXmppConnection() == null) {
2271					account.setXmppConnection(createConnection(account));
2272				}
2273				Thread thread = new Thread(account.getXmppConnection());
2274				account.getXmppConnection().setInteractive(interactive);
2275				thread.start();
2276				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2277			} else {
2278				account.getRoster().clearPresences();
2279				account.setXmppConnection(null);
2280			}
2281		}
2282	}
2283
2284	public void reconnectAccountInBackground(final Account account) {
2285		new Thread(new Runnable() {
2286			@Override
2287			public void run() {
2288				reconnectAccount(account,false,true);
2289			}
2290		}).start();
2291	}
2292
2293	public void invite(Conversation conversation, Jid contact) {
2294		Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2295		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2296		sendMessagePacket(conversation.getAccount(), packet);
2297	}
2298
2299	public void directInvite(Conversation conversation, Jid jid) {
2300		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2301		sendMessagePacket(conversation.getAccount(),packet);
2302	}
2303
2304	public void resetSendingToWaiting(Account account) {
2305		for (Conversation conversation : getConversations()) {
2306			if (conversation.getAccount() == account) {
2307				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2308
2309					@Override
2310					public void onMessageFound(Message message) {
2311						markMessage(message, Message.STATUS_WAITING);
2312					}
2313				});
2314			}
2315		}
2316	}
2317
2318	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2319		if (uuid == null) {
2320			return null;
2321		}
2322		for (Conversation conversation : getConversations()) {
2323			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2324				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2325				if (message != null) {
2326					markMessage(message, status);
2327				}
2328				return message;
2329			}
2330		}
2331		return null;
2332	}
2333
2334	public boolean markMessage(Conversation conversation, String uuid, int status) {
2335		if (uuid == null) {
2336			return false;
2337		} else {
2338			Message message = conversation.findSentMessageWithUuid(uuid);
2339			if (message != null) {
2340				markMessage(message, status);
2341				return true;
2342			} else {
2343				return false;
2344			}
2345		}
2346	}
2347
2348	public void markMessage(Message message, int status) {
2349		if (status == Message.STATUS_SEND_FAILED
2350				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2351				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2352			return;
2353		}
2354		message.setStatus(status);
2355		databaseBackend.updateMessage(message);
2356		updateConversationUi();
2357	}
2358
2359	public SharedPreferences getPreferences() {
2360		return PreferenceManager
2361				.getDefaultSharedPreferences(getApplicationContext());
2362	}
2363
2364	public boolean forceEncryption() {
2365		return getPreferences().getBoolean("force_encryption", false);
2366	}
2367
2368	public boolean confirmMessages() {
2369		return getPreferences().getBoolean("confirm_messages", true);
2370	}
2371
2372	public boolean sendChatStates() {
2373		return getPreferences().getBoolean("chat_states", false);
2374	}
2375
2376	public boolean saveEncryptedMessages() {
2377		return !getPreferences().getBoolean("dont_save_encrypted", false);
2378	}
2379
2380	public boolean indicateReceived() {
2381		return getPreferences().getBoolean("indicate_received", false);
2382	}
2383
2384	public int unreadCount() {
2385		int count = 0;
2386		for(Conversation conversation : getConversations()) {
2387			count += conversation.unreadCount();
2388		}
2389		return count;
2390	}
2391
2392
2393	public void showErrorToastInUi(int resId) {
2394		if (mOnShowErrorToast != null) {
2395			mOnShowErrorToast.onShowErrorToast(resId);
2396		}
2397	}
2398
2399	public void updateConversationUi() {
2400		if (mOnConversationUpdate != null) {
2401			mOnConversationUpdate.onConversationUpdate();
2402		}
2403	}
2404
2405	public void updateAccountUi() {
2406		if (mOnAccountUpdate != null) {
2407			mOnAccountUpdate.onAccountUpdate();
2408		}
2409	}
2410
2411	public void updateRosterUi() {
2412		if (mOnRosterUpdate != null) {
2413			mOnRosterUpdate.onRosterUpdate();
2414		}
2415	}
2416
2417	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2418		if (mOnUpdateBlocklist != null) {
2419			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2420		}
2421	}
2422
2423	public void updateMucRosterUi() {
2424		if (mOnMucRosterUpdate != null) {
2425			mOnMucRosterUpdate.onMucRosterUpdate();
2426		}
2427	}
2428
2429	public void keyStatusUpdated() {
2430		if(mOnKeyStatusUpdated != null) {
2431			mOnKeyStatusUpdated.onKeyStatusUpdated();
2432		}
2433	}
2434
2435	public Account findAccountByJid(final Jid accountJid) {
2436		for (Account account : this.accounts) {
2437			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2438				return account;
2439			}
2440		}
2441		return null;
2442	}
2443
2444	public Conversation findConversationByUuid(String uuid) {
2445		for (Conversation conversation : getConversations()) {
2446			if (conversation.getUuid().equals(uuid)) {
2447				return conversation;
2448			}
2449		}
2450		return null;
2451	}
2452
2453	public void markRead(final Conversation conversation) {
2454		mNotificationService.clear(conversation);
2455		conversation.markRead();
2456		updateUnreadCountBadge();
2457	}
2458
2459	public synchronized void updateUnreadCountBadge() {
2460		int count = unreadCount();
2461		if (unreadCount != count) {
2462			Log.d(Config.LOGTAG, "update unread count to " + count);
2463			if (count > 0) {
2464				ShortcutBadger.with(getApplicationContext()).count(count);
2465			} else {
2466				ShortcutBadger.with(getApplicationContext()).remove();
2467			}
2468			unreadCount = count;
2469		}
2470	}
2471
2472	public void sendReadMarker(final Conversation conversation) {
2473		final Message markable = conversation.getLatestMarkableMessage();
2474		this.markRead(conversation);
2475		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2476			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2477			Account account = conversation.getAccount();
2478			final Jid to = markable.getCounterpart();
2479			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2480			this.sendMessagePacket(conversation.getAccount(), packet);
2481		}
2482		updateConversationUi();
2483	}
2484
2485	public SecureRandom getRNG() {
2486		return this.mRandom;
2487	}
2488
2489	public MemorizingTrustManager getMemorizingTrustManager() {
2490		return this.mMemorizingTrustManager;
2491	}
2492
2493	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2494		this.mMemorizingTrustManager = trustManager;
2495	}
2496
2497	public void updateMemorizingTrustmanager() {
2498		final MemorizingTrustManager tm;
2499		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2500		if (dontTrustSystemCAs) {
2501			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2502		} else {
2503			tm = new MemorizingTrustManager(getApplicationContext());
2504		}
2505		setMemorizingTrustManager(tm);
2506	}
2507
2508	public PowerManager getPowerManager() {
2509		return this.pm;
2510	}
2511
2512	public LruCache<String, Bitmap> getBitmapCache() {
2513		return this.mBitmapCache;
2514	}
2515
2516	public void syncRosterToDisk(final Account account) {
2517		Runnable runnable = new Runnable() {
2518
2519			@Override
2520			public void run() {
2521				databaseBackend.writeRoster(account.getRoster());
2522			}
2523		};
2524		mDatabaseExecutor.execute(runnable);
2525
2526	}
2527
2528	public List<String> getKnownHosts() {
2529		final List<String> hosts = new ArrayList<>();
2530		for (final Account account : getAccounts()) {
2531			if (!hosts.contains(account.getServer().toString())) {
2532				hosts.add(account.getServer().toString());
2533			}
2534			for (final Contact contact : account.getRoster().getContacts()) {
2535				if (contact.showInRoster()) {
2536					final String server = contact.getServer().toString();
2537					if (server != null && !hosts.contains(server)) {
2538						hosts.add(server);
2539					}
2540				}
2541			}
2542		}
2543		return hosts;
2544	}
2545
2546	public List<String> getKnownConferenceHosts() {
2547		final ArrayList<String> mucServers = new ArrayList<>();
2548		for (final Account account : accounts) {
2549			if (account.getXmppConnection() != null) {
2550				final String server = account.getXmppConnection().getMucServer();
2551				if (server != null && !mucServers.contains(server)) {
2552					mucServers.add(server);
2553				}
2554			}
2555		}
2556		return mucServers;
2557	}
2558
2559	public void sendMessagePacket(Account account, MessagePacket packet) {
2560		XmppConnection connection = account.getXmppConnection();
2561		if (connection != null) {
2562			connection.sendMessagePacket(packet);
2563		}
2564	}
2565
2566	public void sendPresencePacket(Account account, PresencePacket packet) {
2567		XmppConnection connection = account.getXmppConnection();
2568		if (connection != null) {
2569			connection.sendPresencePacket(packet);
2570		}
2571	}
2572
2573	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2574		final XmppConnection connection = account.getXmppConnection();
2575		if (connection != null) {
2576			connection.sendIqPacket(packet, callback);
2577		}
2578	}
2579
2580	public void sendPresence(final Account account) {
2581		sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2582	}
2583
2584	public void refreshAllPresences() {
2585		for (Account account : getAccounts()) {
2586			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2587				sendPresence(account);
2588			}
2589		}
2590	}
2591
2592	public void sendOfflinePresence(final Account account) {
2593		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2594	}
2595
2596	public MessageGenerator getMessageGenerator() {
2597		return this.mMessageGenerator;
2598	}
2599
2600	public PresenceGenerator getPresenceGenerator() {
2601		return this.mPresenceGenerator;
2602	}
2603
2604	public IqGenerator getIqGenerator() {
2605		return this.mIqGenerator;
2606	}
2607
2608	public IqParser getIqParser() {
2609		return this.mIqParser;
2610	}
2611
2612	public JingleConnectionManager getJingleConnectionManager() {
2613		return this.mJingleConnectionManager;
2614	}
2615
2616	public MessageArchiveService getMessageArchiveService() {
2617		return this.mMessageArchiveService;
2618	}
2619
2620	public List<Contact> findContacts(Jid jid) {
2621		ArrayList<Contact> contacts = new ArrayList<>();
2622		for (Account account : getAccounts()) {
2623			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2624				Contact contact = account.getRoster().getContactFromRoster(jid);
2625				if (contact != null) {
2626					contacts.add(contact);
2627				}
2628			}
2629		}
2630		return contacts;
2631	}
2632
2633	public NotificationService getNotificationService() {
2634		return this.mNotificationService;
2635	}
2636
2637	public HttpConnectionManager getHttpConnectionManager() {
2638		return this.mHttpConnectionManager;
2639	}
2640
2641	public void resendFailedMessages(final Message message) {
2642		final Collection<Message> messages = new ArrayList<>();
2643		Message current = message;
2644		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2645			messages.add(current);
2646			if (current.mergeable(current.next())) {
2647				current = current.next();
2648			} else {
2649				break;
2650			}
2651		}
2652		for (final Message msg : messages) {
2653			msg.setTime(System.currentTimeMillis());
2654			markMessage(msg, Message.STATUS_WAITING);
2655			this.resendMessage(msg,false);
2656		}
2657	}
2658
2659	public void clearConversationHistory(final Conversation conversation) {
2660		conversation.clearMessages();
2661		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2662		conversation.resetLastMessageTransmitted();
2663		new Thread(new Runnable() {
2664			@Override
2665			public void run() {
2666				databaseBackend.deleteMessagesInConversation(conversation);
2667			}
2668		}).start();
2669	}
2670
2671	public void sendBlockRequest(final Blockable blockable) {
2672		if (blockable != null && blockable.getBlockedJid() != null) {
2673			final Jid jid = blockable.getBlockedJid();
2674			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2675
2676				@Override
2677				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2678					if (packet.getType() == IqPacket.TYPE.RESULT) {
2679						account.getBlocklist().add(jid);
2680						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2681					}
2682				}
2683			});
2684		}
2685	}
2686
2687	public void sendUnblockRequest(final Blockable blockable) {
2688		if (blockable != null && blockable.getJid() != null) {
2689			final Jid jid = blockable.getBlockedJid();
2690			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2691				@Override
2692				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2693					if (packet.getType() == IqPacket.TYPE.RESULT) {
2694						account.getBlocklist().remove(jid);
2695						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2696					}
2697				}
2698			});
2699		}
2700	}
2701
2702	public interface OnMoreMessagesLoaded {
2703		public void onMoreMessagesLoaded(int count, Conversation conversation);
2704
2705		public void informUser(int r);
2706	}
2707
2708	public interface OnAccountPasswordChanged {
2709		public void onPasswordChangeSucceeded();
2710
2711		public void onPasswordChangeFailed();
2712	}
2713
2714	public interface OnAffiliationChanged {
2715		public void onAffiliationChangedSuccessful(Jid jid);
2716
2717		public void onAffiliationChangeFailed(Jid jid, int resId);
2718	}
2719
2720	public interface OnRoleChanged {
2721		public void onRoleChangedSuccessful(String nick);
2722
2723		public void onRoleChangeFailed(String nick, int resid);
2724	}
2725
2726	public interface OnConversationUpdate {
2727		public void onConversationUpdate();
2728	}
2729
2730	public interface OnAccountUpdate {
2731		public void onAccountUpdate();
2732	}
2733
2734	public interface OnRosterUpdate {
2735		public void onRosterUpdate();
2736	}
2737
2738	public interface OnMucRosterUpdate {
2739		public void onMucRosterUpdate();
2740	}
2741
2742	public interface OnConferenceConfigurationFetched {
2743		public void onConferenceConfigurationFetched(Conversation conversation);
2744	}
2745
2746	public interface OnConferenceOptionsPushed {
2747		public void onPushSucceeded();
2748
2749		public void onPushFailed();
2750	}
2751
2752	public interface OnShowErrorToast {
2753		void onShowErrorToast(int resId);
2754	}
2755
2756	public class XmppConnectionBinder extends Binder {
2757		public XmppConnectionService getService() {
2758			return XmppConnectionService.this;
2759		}
2760	}
2761}