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