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