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						createAccount(account);
1335						callback.onAccountCreated(account);
1336						if (Config.X509_VERIFICATION) {
1337							try {
1338								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1339							} catch (CertificateException e) {
1340								callback.informUser(R.string.certificate_chain_is_not_trusted);
1341							}
1342						}
1343					} else {
1344						callback.informUser(R.string.account_already_exists);
1345					}
1346				} catch (Exception e) {
1347					e.printStackTrace();
1348					callback.informUser(R.string.unable_to_parse_certificate);
1349				}
1350			}
1351		}).start();
1352
1353	}
1354
1355	public void updateKeyInAccount(final Account account, final String alias) {
1356		Log.d(Config.LOGTAG, "update key in account " + alias);
1357		try {
1358			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1359			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1360			if (account.getJid().toBareJid().equals(info.first)) {
1361				account.setPrivateKeyAlias(alias);
1362				databaseBackend.updateAccount(account);
1363				if (Config.X509_VERIFICATION) {
1364					try {
1365						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1366					} catch (CertificateException e) {
1367						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1368					}
1369					account.getAxolotlService().regenerateKeys(true);
1370				}
1371			} else {
1372				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1373			}
1374		} catch (Exception e) {
1375			e.printStackTrace();
1376		}
1377	}
1378
1379	public void updateAccount(final Account account) {
1380		this.statusListener.onStatusChanged(account);
1381		databaseBackend.updateAccount(account);
1382		reconnectAccountInBackground(account);
1383		updateAccountUi();
1384		getNotificationService().updateErrorNotification();
1385	}
1386
1387	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1388		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1389		sendIqPacket(account, iq, new OnIqPacketReceived() {
1390			@Override
1391			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1392				if (packet.getType() == IqPacket.TYPE.RESULT) {
1393					account.setPassword(newPassword);
1394					databaseBackend.updateAccount(account);
1395					callback.onPasswordChangeSucceeded();
1396				} else {
1397					callback.onPasswordChangeFailed();
1398				}
1399			}
1400		});
1401	}
1402
1403	public void deleteAccount(final Account account) {
1404		synchronized (this.conversations) {
1405			for (final Conversation conversation : conversations) {
1406				if (conversation.getAccount() == account) {
1407					if (conversation.getMode() == Conversation.MODE_MULTI) {
1408						leaveMuc(conversation);
1409					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1410						conversation.endOtrIfNeeded();
1411					}
1412					conversations.remove(conversation);
1413				}
1414			}
1415			if (account.getXmppConnection() != null) {
1416				this.disconnect(account, true);
1417			}
1418			databaseBackend.deleteAccount(account);
1419			this.accounts.remove(account);
1420			updateAccountUi();
1421			getNotificationService().updateErrorNotification();
1422		}
1423	}
1424
1425	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1426		synchronized (this) {
1427			if (checkListeners()) {
1428				switchToForeground();
1429			}
1430			this.mOnConversationUpdate = listener;
1431			this.mNotificationService.setIsInForeground(true);
1432			if (this.convChangedListenerCount < 2) {
1433				this.convChangedListenerCount++;
1434			}
1435		}
1436	}
1437
1438	public void removeOnConversationListChangedListener() {
1439		synchronized (this) {
1440			this.convChangedListenerCount--;
1441			if (this.convChangedListenerCount <= 0) {
1442				this.convChangedListenerCount = 0;
1443				this.mOnConversationUpdate = null;
1444				this.mNotificationService.setIsInForeground(false);
1445				if (checkListeners()) {
1446					switchToBackground();
1447				}
1448			}
1449		}
1450	}
1451
1452	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1453		synchronized (this) {
1454			if (checkListeners()) {
1455				switchToForeground();
1456			}
1457			this.mOnShowErrorToast = onShowErrorToast;
1458			if (this.showErrorToastListenerCount < 2) {
1459				this.showErrorToastListenerCount++;
1460			}
1461		}
1462		this.mOnShowErrorToast = onShowErrorToast;
1463	}
1464
1465	public void removeOnShowErrorToastListener() {
1466		synchronized (this) {
1467			this.showErrorToastListenerCount--;
1468			if (this.showErrorToastListenerCount <= 0) {
1469				this.showErrorToastListenerCount = 0;
1470				this.mOnShowErrorToast = null;
1471				if (checkListeners()) {
1472					switchToBackground();
1473				}
1474			}
1475		}
1476	}
1477
1478	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1479		synchronized (this) {
1480			if (checkListeners()) {
1481				switchToForeground();
1482			}
1483			this.mOnAccountUpdate = listener;
1484			if (this.accountChangedListenerCount < 2) {
1485				this.accountChangedListenerCount++;
1486			}
1487		}
1488	}
1489
1490	public void removeOnAccountListChangedListener() {
1491		synchronized (this) {
1492			this.accountChangedListenerCount--;
1493			if (this.accountChangedListenerCount <= 0) {
1494				this.mOnAccountUpdate = null;
1495				this.accountChangedListenerCount = 0;
1496				if (checkListeners()) {
1497					switchToBackground();
1498				}
1499			}
1500		}
1501	}
1502
1503	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1504		synchronized (this) {
1505			if (checkListeners()) {
1506				switchToForeground();
1507			}
1508			this.mOnCaptchaRequested = listener;
1509			if (this.captchaRequestedListenerCount < 2) {
1510				this.captchaRequestedListenerCount++;
1511			}
1512		}
1513	}
1514
1515	public void removeOnCaptchaRequestedListener() {
1516		synchronized (this) {
1517			this.captchaRequestedListenerCount--;
1518			if (this.captchaRequestedListenerCount <= 0) {
1519				this.mOnCaptchaRequested = null;
1520				this.captchaRequestedListenerCount = 0;
1521				if (checkListeners()) {
1522					switchToBackground();
1523				}
1524			}
1525		}
1526	}
1527
1528	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1529		synchronized (this) {
1530			if (checkListeners()) {
1531				switchToForeground();
1532			}
1533			this.mOnRosterUpdate = listener;
1534			if (this.rosterChangedListenerCount < 2) {
1535				this.rosterChangedListenerCount++;
1536			}
1537		}
1538	}
1539
1540	public void removeOnRosterUpdateListener() {
1541		synchronized (this) {
1542			this.rosterChangedListenerCount--;
1543			if (this.rosterChangedListenerCount <= 0) {
1544				this.rosterChangedListenerCount = 0;
1545				this.mOnRosterUpdate = null;
1546				if (checkListeners()) {
1547					switchToBackground();
1548				}
1549			}
1550		}
1551	}
1552
1553	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1554		synchronized (this) {
1555			if (checkListeners()) {
1556				switchToForeground();
1557			}
1558			this.mOnUpdateBlocklist = listener;
1559			if (this.updateBlocklistListenerCount < 2) {
1560				this.updateBlocklistListenerCount++;
1561			}
1562		}
1563	}
1564
1565	public void removeOnUpdateBlocklistListener() {
1566		synchronized (this) {
1567			this.updateBlocklistListenerCount--;
1568			if (this.updateBlocklistListenerCount <= 0) {
1569				this.updateBlocklistListenerCount = 0;
1570				this.mOnUpdateBlocklist = null;
1571				if (checkListeners()) {
1572					switchToBackground();
1573				}
1574			}
1575		}
1576	}
1577
1578	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1579		synchronized (this) {
1580			if (checkListeners()) {
1581				switchToForeground();
1582			}
1583			this.mOnKeyStatusUpdated = listener;
1584			if (this.keyStatusUpdatedListenerCount < 2) {
1585				this.keyStatusUpdatedListenerCount++;
1586			}
1587		}
1588	}
1589
1590	public void removeOnNewKeysAvailableListener() {
1591		synchronized (this) {
1592			this.keyStatusUpdatedListenerCount--;
1593			if (this.keyStatusUpdatedListenerCount <= 0) {
1594				this.keyStatusUpdatedListenerCount = 0;
1595				this.mOnKeyStatusUpdated = null;
1596				if (checkListeners()) {
1597					switchToBackground();
1598				}
1599			}
1600		}
1601	}
1602
1603	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1604		synchronized (this) {
1605			if (checkListeners()) {
1606				switchToForeground();
1607			}
1608			this.mOnMucRosterUpdate = listener;
1609			if (this.mucRosterChangedListenerCount < 2) {
1610				this.mucRosterChangedListenerCount++;
1611			}
1612		}
1613	}
1614
1615	public void removeOnMucRosterUpdateListener() {
1616		synchronized (this) {
1617			this.mucRosterChangedListenerCount--;
1618			if (this.mucRosterChangedListenerCount <= 0) {
1619				this.mucRosterChangedListenerCount = 0;
1620				this.mOnMucRosterUpdate = null;
1621				if (checkListeners()) {
1622					switchToBackground();
1623				}
1624			}
1625		}
1626	}
1627
1628	private boolean checkListeners() {
1629		return (this.mOnAccountUpdate == null
1630				&& this.mOnConversationUpdate == null
1631				&& this.mOnRosterUpdate == null
1632				&& this.mOnCaptchaRequested == null
1633				&& this.mOnUpdateBlocklist == null
1634				&& this.mOnShowErrorToast == null
1635				&& this.mOnKeyStatusUpdated == null);
1636	}
1637
1638	private void switchToForeground() {
1639		for (Conversation conversation : getConversations()) {
1640			conversation.setIncomingChatState(ChatState.ACTIVE);
1641		}
1642		for (Account account : getAccounts()) {
1643			if (account.getStatus() == Account.State.ONLINE) {
1644				XmppConnection connection = account.getXmppConnection();
1645				if (connection != null && connection.getFeatures().csi()) {
1646					connection.sendActive();
1647				}
1648			}
1649		}
1650		Log.d(Config.LOGTAG, "app switched into foreground");
1651	}
1652
1653	private void switchToBackground() {
1654		for (Account account : getAccounts()) {
1655			if (account.getStatus() == Account.State.ONLINE) {
1656				XmppConnection connection = account.getXmppConnection();
1657				if (connection != null && connection.getFeatures().csi()) {
1658					connection.sendInactive();
1659				}
1660			}
1661		}
1662		this.mNotificationService.setIsInForeground(false);
1663		Log.d(Config.LOGTAG, "app switched into background");
1664	}
1665
1666	private void connectMultiModeConversations(Account account) {
1667		List<Conversation> conversations = getConversations();
1668		for (Conversation conversation : conversations) {
1669			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1670				joinMuc(conversation, true);
1671			}
1672		}
1673	}
1674
1675	public void joinMuc(Conversation conversation) {
1676		joinMuc(conversation, false);
1677	}
1678
1679	private void joinMuc(Conversation conversation, boolean now) {
1680		Account account = conversation.getAccount();
1681		account.pendingConferenceJoins.remove(conversation);
1682		account.pendingConferenceLeaves.remove(conversation);
1683		if (account.getStatus() == Account.State.ONLINE || now) {
1684			conversation.resetMucOptions();
1685			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1686
1687				private void join(Conversation conversation) {
1688					Account account = conversation.getAccount();
1689					final String nick = conversation.getMucOptions().getProposedNick();
1690					final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1691					if (joinJid == null) {
1692						return; //safety net
1693					}
1694					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1695					PresencePacket packet = new PresencePacket();
1696					packet.setFrom(conversation.getAccount().getJid());
1697					packet.setTo(joinJid);
1698					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1699					if (conversation.getMucOptions().getPassword() != null) {
1700						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1701					}
1702
1703					if (conversation.getMucOptions().mamSupport()) {
1704						// Use MAM instead of the limited muc history to get history
1705						x.addChild("history").setAttribute("maxchars", "0");
1706					} else {
1707						// Fallback to muc history
1708						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1709					}
1710					String sig = account.getPgpSignature();
1711					if (sig != null) {
1712						packet.addChild("status").setContent("online");
1713						packet.addChild("x", "jabber:x:signed").setContent(sig);
1714					}
1715					sendPresencePacket(account, packet);
1716					fetchConferenceConfiguration(conversation);
1717					if (!joinJid.equals(conversation.getJid())) {
1718						conversation.setContactJid(joinJid);
1719						databaseBackend.updateConversation(conversation);
1720					}
1721					conversation.setHasMessagesLeftOnServer(false);
1722					if (conversation.getMucOptions().mamSupport()) {
1723						getMessageArchiveService().catchupMUC(conversation);
1724					}
1725				}
1726
1727				@Override
1728				public void onConferenceConfigurationFetched(Conversation conversation) {
1729					join(conversation);
1730				}
1731
1732				@Override
1733				public void onFetchFailed(final Conversation conversation, Element error) {
1734					conversation.getMucOptions().setOnJoinListener(new MucOptions.OnJoinListener() {
1735						@Override
1736						public void onSuccess() {
1737							fetchConferenceConfiguration(conversation);
1738						}
1739
1740						@Override
1741						public void onFailure() {
1742
1743						}
1744					});
1745					join(conversation);
1746				}
1747			});
1748
1749		} else {
1750			account.pendingConferenceJoins.add(conversation);
1751		}
1752	}
1753
1754	public void providePasswordForMuc(Conversation conversation, String password) {
1755		if (conversation.getMode() == Conversation.MODE_MULTI) {
1756			conversation.getMucOptions().setPassword(password);
1757			if (conversation.getBookmark() != null) {
1758				conversation.getBookmark().setAutojoin(true);
1759				pushBookmarks(conversation.getAccount());
1760			}
1761			databaseBackend.updateConversation(conversation);
1762			joinMuc(conversation);
1763		}
1764	}
1765
1766	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1767		final MucOptions options = conversation.getMucOptions();
1768		final Jid joinJid = options.createJoinJid(nick);
1769		if (options.online()) {
1770			Account account = conversation.getAccount();
1771			options.setOnRenameListener(new OnRenameListener() {
1772
1773				@Override
1774				public void onSuccess() {
1775					conversation.setContactJid(joinJid);
1776					databaseBackend.updateConversation(conversation);
1777					Bookmark bookmark = conversation.getBookmark();
1778					if (bookmark != null) {
1779						bookmark.setNick(nick);
1780						pushBookmarks(bookmark.getAccount());
1781					}
1782					callback.success(conversation);
1783				}
1784
1785				@Override
1786				public void onFailure() {
1787					callback.error(R.string.nick_in_use, conversation);
1788				}
1789			});
1790
1791			PresencePacket packet = new PresencePacket();
1792			packet.setTo(joinJid);
1793			packet.setFrom(conversation.getAccount().getJid());
1794
1795			String sig = account.getPgpSignature();
1796			if (sig != null) {
1797				packet.addChild("status").setContent("online");
1798				packet.addChild("x", "jabber:x:signed").setContent(sig);
1799			}
1800			sendPresencePacket(account, packet);
1801		} else {
1802			conversation.setContactJid(joinJid);
1803			databaseBackend.updateConversation(conversation);
1804			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1805				Bookmark bookmark = conversation.getBookmark();
1806				if (bookmark != null) {
1807					bookmark.setNick(nick);
1808					pushBookmarks(bookmark.getAccount());
1809				}
1810				joinMuc(conversation);
1811			}
1812		}
1813	}
1814
1815	public void leaveMuc(Conversation conversation) {
1816		leaveMuc(conversation, false);
1817	}
1818
1819	private void leaveMuc(Conversation conversation, boolean now) {
1820		Account account = conversation.getAccount();
1821		account.pendingConferenceJoins.remove(conversation);
1822		account.pendingConferenceLeaves.remove(conversation);
1823		if (account.getStatus() == Account.State.ONLINE || now) {
1824			PresencePacket packet = new PresencePacket();
1825			packet.setTo(conversation.getJid());
1826			packet.setFrom(conversation.getAccount().getJid());
1827			packet.setAttribute("type", "unavailable");
1828			sendPresencePacket(conversation.getAccount(), packet);
1829			conversation.getMucOptions().setOffline();
1830			conversation.deregisterWithBookmark();
1831			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1832					+ ": leaving muc " + conversation.getJid());
1833		} else {
1834			account.pendingConferenceLeaves.add(conversation);
1835		}
1836	}
1837
1838	private String findConferenceServer(final Account account) {
1839		String server;
1840		if (account.getXmppConnection() != null) {
1841			server = account.getXmppConnection().getMucServer();
1842			if (server != null) {
1843				return server;
1844			}
1845		}
1846		for (Account other : getAccounts()) {
1847			if (other != account && other.getXmppConnection() != null) {
1848				server = other.getXmppConnection().getMucServer();
1849				if (server != null) {
1850					return server;
1851				}
1852			}
1853		}
1854		return null;
1855	}
1856
1857	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1858		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1859		if (account.getStatus() == Account.State.ONLINE) {
1860			try {
1861				String server = findConferenceServer(account);
1862				if (server == null) {
1863					if (callback != null) {
1864						callback.error(R.string.no_conference_server_found, null);
1865					}
1866					return;
1867				}
1868				String name = new BigInteger(75, getRNG()).toString(32);
1869				Jid jid = Jid.fromParts(name, server, null);
1870				final Conversation conversation = findOrCreateConversation(account, jid, true);
1871				joinMuc(conversation);
1872				Bundle options = new Bundle();
1873				options.putString("muc#roomconfig_persistentroom", "1");
1874				options.putString("muc#roomconfig_membersonly", "1");
1875				options.putString("muc#roomconfig_publicroom", "0");
1876				options.putString("muc#roomconfig_whois", "anyone");
1877				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1878					@Override
1879					public void onPushSucceeded() {
1880						for (Jid invite : jids) {
1881							invite(conversation, invite);
1882						}
1883						if (account.countPresences() > 1) {
1884							directInvite(conversation, account.getJid().toBareJid());
1885						}
1886						if (callback != null) {
1887							callback.success(conversation);
1888						}
1889					}
1890
1891					@Override
1892					public void onPushFailed() {
1893						if (callback != null) {
1894							callback.error(R.string.conference_creation_failed, conversation);
1895						}
1896					}
1897				});
1898
1899			} catch (InvalidJidException e) {
1900				if (callback != null) {
1901					callback.error(R.string.conference_creation_failed, null);
1902				}
1903			}
1904		} else {
1905			if (callback != null) {
1906				callback.error(R.string.not_connected_try_again, null);
1907			}
1908		}
1909	}
1910
1911	public void fetchConferenceConfiguration(final Conversation conversation) {
1912		fetchConferenceConfiguration(conversation, null);
1913	}
1914
1915	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1916		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1917		request.setTo(conversation.getJid().toBareJid());
1918		request.query("http://jabber.org/protocol/disco#info");
1919		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1920			@Override
1921			public void onIqPacketReceived(Account account, IqPacket packet) {
1922				if (packet.getType() == IqPacket.TYPE.RESULT) {
1923					ArrayList<String> features = new ArrayList<>();
1924					for (Element child : packet.query().getChildren()) {
1925						if (child != null && child.getName().equals("feature")) {
1926							String var = child.getAttribute("var");
1927							if (var != null) {
1928								features.add(var);
1929							}
1930						}
1931					}
1932					conversation.getMucOptions().updateFeatures(features);
1933					if (callback != null) {
1934						callback.onConferenceConfigurationFetched(conversation);
1935					}
1936					updateConversationUi();
1937				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
1938					if (callback != null) {
1939						callback.onFetchFailed(conversation, packet.getError());
1940					}
1941				}
1942			}
1943		});
1944	}
1945
1946	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1947		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1948		request.setTo(conversation.getJid().toBareJid());
1949		request.query("http://jabber.org/protocol/muc#owner");
1950		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1951			@Override
1952			public void onIqPacketReceived(Account account, IqPacket packet) {
1953				if (packet.getType() == IqPacket.TYPE.RESULT) {
1954					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1955					for (Field field : data.getFields()) {
1956						if (options.containsKey(field.getFieldName())) {
1957							field.setValue(options.getString(field.getFieldName()));
1958						}
1959					}
1960					data.submit();
1961					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1962					set.setTo(conversation.getJid().toBareJid());
1963					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1964					sendIqPacket(account, set, new OnIqPacketReceived() {
1965						@Override
1966						public void onIqPacketReceived(Account account, IqPacket packet) {
1967							if (callback != null) {
1968								if (packet.getType() == IqPacket.TYPE.RESULT) {
1969									callback.onPushSucceeded();
1970								} else {
1971									callback.onPushFailed();
1972								}
1973							}
1974						}
1975					});
1976				} else {
1977					if (callback != null) {
1978						callback.onPushFailed();
1979					}
1980				}
1981			}
1982		});
1983	}
1984
1985	public void pushSubjectToConference(final Conversation conference, final String subject) {
1986		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1987		this.sendMessagePacket(conference.getAccount(), packet);
1988		final MucOptions mucOptions = conference.getMucOptions();
1989		final MucOptions.User self = mucOptions.getSelf();
1990		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1991			Bundle options = new Bundle();
1992			options.putString("muc#roomconfig_persistentroom", "1");
1993			this.pushConferenceConfiguration(conference, options, null);
1994		}
1995	}
1996
1997	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1998		final Jid jid = user.toBareJid();
1999		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2000		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2001			@Override
2002			public void onIqPacketReceived(Account account, IqPacket packet) {
2003				if (packet.getType() == IqPacket.TYPE.RESULT) {
2004					callback.onAffiliationChangedSuccessful(jid);
2005				} else {
2006					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2007				}
2008			}
2009		});
2010	}
2011
2012	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2013		List<Jid> jids = new ArrayList<>();
2014		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2015			if (user.getAffiliation() == before && user.getJid() != null) {
2016				jids.add(user.getJid());
2017			}
2018		}
2019		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2020		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2021	}
2022
2023	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2024		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2025		Log.d(Config.LOGTAG, request.toString());
2026		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2027			@Override
2028			public void onIqPacketReceived(Account account, IqPacket packet) {
2029				Log.d(Config.LOGTAG, packet.toString());
2030				if (packet.getType() == IqPacket.TYPE.RESULT) {
2031					callback.onRoleChangedSuccessful(nick);
2032				} else {
2033					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2034				}
2035			}
2036		});
2037	}
2038
2039	private void disconnect(Account account, boolean force) {
2040		if ((account.getStatus() == Account.State.ONLINE)
2041				|| (account.getStatus() == Account.State.DISABLED)) {
2042			if (!force) {
2043				List<Conversation> conversations = getConversations();
2044				for (Conversation conversation : conversations) {
2045					if (conversation.getAccount() == account) {
2046						if (conversation.getMode() == Conversation.MODE_MULTI) {
2047							leaveMuc(conversation, true);
2048						} else {
2049							if (conversation.endOtrIfNeeded()) {
2050								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2051										+ ": ended otr session with "
2052										+ conversation.getJid());
2053							}
2054						}
2055					}
2056				}
2057				sendOfflinePresence(account);
2058			}
2059			account.getXmppConnection().disconnect(force);
2060		}
2061	}
2062
2063	@Override
2064	public IBinder onBind(Intent intent) {
2065		return mBinder;
2066	}
2067
2068	public void updateMessage(Message message) {
2069		databaseBackend.updateMessage(message);
2070		updateConversationUi();
2071	}
2072
2073	protected void syncDirtyContacts(Account account) {
2074		for (Contact contact : account.getRoster().getContacts()) {
2075			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2076				pushContactToServer(contact);
2077			}
2078			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2079				deleteContactOnServer(contact);
2080			}
2081		}
2082	}
2083
2084	public void createContact(Contact contact) {
2085		SharedPreferences sharedPref = getPreferences();
2086		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
2087		if (autoGrant) {
2088			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2089			contact.setOption(Contact.Options.ASKING);
2090		}
2091		pushContactToServer(contact);
2092	}
2093
2094	public void onOtrSessionEstablished(Conversation conversation) {
2095		final Account account = conversation.getAccount();
2096		final Session otrSession = conversation.getOtrSession();
2097		Log.d(Config.LOGTAG,
2098				account.getJid().toBareJid() + " otr session established with "
2099						+ conversation.getJid() + "/"
2100						+ otrSession.getSessionID().getUserID());
2101		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2102
2103			@Override
2104			public void onMessageFound(Message message) {
2105				SessionID id = otrSession.getSessionID();
2106				try {
2107					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2108				} catch (InvalidJidException e) {
2109					return;
2110				}
2111				if (message.needsUploading()) {
2112					mJingleConnectionManager.createNewConnection(message);
2113				} else {
2114					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2115					if (outPacket != null) {
2116						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2117						message.setStatus(Message.STATUS_SEND);
2118						databaseBackend.updateMessage(message);
2119						sendMessagePacket(account, outPacket);
2120					}
2121				}
2122				updateConversationUi();
2123			}
2124		});
2125	}
2126
2127	public boolean renewSymmetricKey(Conversation conversation) {
2128		Account account = conversation.getAccount();
2129		byte[] symmetricKey = new byte[32];
2130		this.mRandom.nextBytes(symmetricKey);
2131		Session otrSession = conversation.getOtrSession();
2132		if (otrSession != null) {
2133			MessagePacket packet = new MessagePacket();
2134			packet.setType(MessagePacket.TYPE_CHAT);
2135			packet.setFrom(account.getJid());
2136			MessageGenerator.addMessageHints(packet);
2137			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2138					+ otrSession.getSessionID().getUserID());
2139			try {
2140				packet.setBody(otrSession
2141						.transformSending(CryptoHelper.FILETRANSFER
2142								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2143				sendMessagePacket(account, packet);
2144				conversation.setSymmetricKey(symmetricKey);
2145				return true;
2146			} catch (OtrException e) {
2147				return false;
2148			}
2149		}
2150		return false;
2151	}
2152
2153	public void pushContactToServer(final Contact contact) {
2154		contact.resetOption(Contact.Options.DIRTY_DELETE);
2155		contact.setOption(Contact.Options.DIRTY_PUSH);
2156		final Account account = contact.getAccount();
2157		if (account.getStatus() == Account.State.ONLINE) {
2158			final boolean ask = contact.getOption(Contact.Options.ASKING);
2159			final boolean sendUpdates = contact
2160					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2161					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2162			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2163			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2164			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2165			if (sendUpdates) {
2166				sendPresencePacket(account,
2167						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2168			}
2169			if (ask) {
2170				sendPresencePacket(account,
2171						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2172			}
2173		}
2174	}
2175
2176	public void publishAvatar(final Account account,
2177							  final Uri image,
2178							  final UiCallback<Avatar> callback) {
2179		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2180		final int size = Config.AVATAR_SIZE;
2181		final Avatar avatar = getFileBackend()
2182				.getPepAvatar(image, size, format);
2183		if (avatar != null) {
2184			avatar.height = size;
2185			avatar.width = size;
2186			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2187				avatar.type = "image/webp";
2188			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2189				avatar.type = "image/jpeg";
2190			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2191				avatar.type = "image/png";
2192			}
2193			if (!getFileBackend().save(avatar)) {
2194				callback.error(R.string.error_saving_avatar, avatar);
2195				return;
2196			}
2197			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2198			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2199
2200				@Override
2201				public void onIqPacketReceived(Account account, IqPacket result) {
2202					if (result.getType() == IqPacket.TYPE.RESULT) {
2203						final IqPacket packet = XmppConnectionService.this.mIqGenerator
2204								.publishAvatarMetadata(avatar);
2205						sendIqPacket(account, packet, new OnIqPacketReceived() {
2206							@Override
2207							public void onIqPacketReceived(Account account, IqPacket result) {
2208								if (result.getType() == IqPacket.TYPE.RESULT) {
2209									if (account.setAvatar(avatar.getFilename())) {
2210										getAvatarService().clear(account);
2211										databaseBackend.updateAccount(account);
2212									}
2213									callback.success(avatar);
2214								} else {
2215									callback.error(
2216											R.string.error_publish_avatar_server_reject,
2217											avatar);
2218								}
2219							}
2220						});
2221					} else {
2222						callback.error(
2223								R.string.error_publish_avatar_server_reject,
2224								avatar);
2225					}
2226				}
2227			});
2228		} else {
2229			callback.error(R.string.error_publish_avatar_converting, null);
2230		}
2231	}
2232
2233	public void fetchAvatar(Account account, Avatar avatar) {
2234		fetchAvatar(account, avatar, null);
2235	}
2236
2237	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2238		final String KEY = generateFetchKey(account, avatar);
2239		synchronized (this.mInProgressAvatarFetches) {
2240			if (this.mInProgressAvatarFetches.contains(KEY)) {
2241				return;
2242			} else {
2243				switch (avatar.origin) {
2244					case PEP:
2245						this.mInProgressAvatarFetches.add(KEY);
2246						fetchAvatarPep(account, avatar, callback);
2247						break;
2248					case VCARD:
2249						this.mInProgressAvatarFetches.add(KEY);
2250						fetchAvatarVcard(account, avatar, callback);
2251						break;
2252				}
2253			}
2254		}
2255	}
2256
2257	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2258		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2259		sendIqPacket(account, packet, new OnIqPacketReceived() {
2260
2261			@Override
2262			public void onIqPacketReceived(Account account, IqPacket result) {
2263				synchronized (mInProgressAvatarFetches) {
2264					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2265				}
2266				final String ERROR = account.getJid().toBareJid()
2267						+ ": fetching avatar for " + avatar.owner + " failed ";
2268				if (result.getType() == IqPacket.TYPE.RESULT) {
2269					avatar.image = mIqParser.avatarData(result);
2270					if (avatar.image != null) {
2271						if (getFileBackend().save(avatar)) {
2272							if (account.getJid().toBareJid().equals(avatar.owner)) {
2273								if (account.setAvatar(avatar.getFilename())) {
2274									databaseBackend.updateAccount(account);
2275								}
2276								getAvatarService().clear(account);
2277								updateConversationUi();
2278								updateAccountUi();
2279							} else {
2280								Contact contact = account.getRoster()
2281										.getContact(avatar.owner);
2282								contact.setAvatar(avatar);
2283								getAvatarService().clear(contact);
2284								updateConversationUi();
2285								updateRosterUi();
2286							}
2287							if (callback != null) {
2288								callback.success(avatar);
2289							}
2290							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2291									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2292							return;
2293						}
2294					} else {
2295
2296						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2297					}
2298				} else {
2299					Element error = result.findChild("error");
2300					if (error == null) {
2301						Log.d(Config.LOGTAG, ERROR + "(server error)");
2302					} else {
2303						Log.d(Config.LOGTAG, ERROR + error.toString());
2304					}
2305				}
2306				if (callback != null) {
2307					callback.error(0, null);
2308				}
2309
2310			}
2311		});
2312	}
2313
2314	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2315		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2316		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2317			@Override
2318			public void onIqPacketReceived(Account account, IqPacket packet) {
2319				synchronized (mInProgressAvatarFetches) {
2320					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2321				}
2322				if (packet.getType() == IqPacket.TYPE.RESULT) {
2323					Element vCard = packet.findChild("vCard", "vcard-temp");
2324					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2325					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2326					if (image != null) {
2327						avatar.image = image;
2328						if (getFileBackend().save(avatar)) {
2329							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2330									+ ": successfully fetched vCard avatar for " + avatar.owner);
2331							Contact contact = account.getRoster()
2332									.getContact(avatar.owner);
2333							contact.setAvatar(avatar);
2334							getAvatarService().clear(contact);
2335							updateConversationUi();
2336							updateRosterUi();
2337						}
2338					}
2339				}
2340			}
2341		});
2342	}
2343
2344	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2345		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2346		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2347
2348			@Override
2349			public void onIqPacketReceived(Account account, IqPacket packet) {
2350				if (packet.getType() == IqPacket.TYPE.RESULT) {
2351					Element pubsub = packet.findChild("pubsub",
2352							"http://jabber.org/protocol/pubsub");
2353					if (pubsub != null) {
2354						Element items = pubsub.findChild("items");
2355						if (items != null) {
2356							Avatar avatar = Avatar.parseMetadata(items);
2357							if (avatar != null) {
2358								avatar.owner = account.getJid().toBareJid();
2359								if (fileBackend.isAvatarCached(avatar)) {
2360									if (account.setAvatar(avatar.getFilename())) {
2361										databaseBackend.updateAccount(account);
2362									}
2363									getAvatarService().clear(account);
2364									callback.success(avatar);
2365								} else {
2366									fetchAvatarPep(account, avatar, callback);
2367								}
2368								return;
2369							}
2370						}
2371					}
2372				}
2373				callback.error(0, null);
2374			}
2375		});
2376	}
2377
2378	public void deleteContactOnServer(Contact contact) {
2379		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2380		contact.resetOption(Contact.Options.DIRTY_PUSH);
2381		contact.setOption(Contact.Options.DIRTY_DELETE);
2382		Account account = contact.getAccount();
2383		if (account.getStatus() == Account.State.ONLINE) {
2384			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2385			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2386			item.setAttribute("jid", contact.getJid().toString());
2387			item.setAttribute("subscription", "remove");
2388			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2389		}
2390	}
2391
2392	public void updateConversation(Conversation conversation) {
2393		this.databaseBackend.updateConversation(conversation);
2394	}
2395
2396	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2397		synchronized (account) {
2398			if (account.getXmppConnection() != null) {
2399				disconnect(account, force);
2400			}
2401			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2402
2403				synchronized (this.mInProgressAvatarFetches) {
2404					for (Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
2405						final String KEY = iterator.next();
2406						if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
2407							iterator.remove();
2408						}
2409					}
2410				}
2411
2412				if (account.getXmppConnection() == null) {
2413					account.setXmppConnection(createConnection(account));
2414				} else if (!force) {
2415					try {
2416						Log.d(Config.LOGTAG, "wait for disconnect");
2417						Thread.sleep(500); //sleep  wait for disconnect
2418					} catch (InterruptedException e) {
2419						//ignored
2420					}
2421				}
2422				Thread thread = new Thread(account.getXmppConnection());
2423				account.getXmppConnection().setInteractive(interactive);
2424				thread.start();
2425				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2426			} else {
2427				account.getRoster().clearPresences();
2428				account.setXmppConnection(null);
2429			}
2430		}
2431	}
2432
2433	public void reconnectAccountInBackground(final Account account) {
2434		new Thread(new Runnable() {
2435			@Override
2436			public void run() {
2437				reconnectAccount(account, false, true);
2438			}
2439		}).start();
2440	}
2441
2442	public void invite(Conversation conversation, Jid contact) {
2443		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2444		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2445		sendMessagePacket(conversation.getAccount(), packet);
2446	}
2447
2448	public void directInvite(Conversation conversation, Jid jid) {
2449		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2450		sendMessagePacket(conversation.getAccount(), packet);
2451	}
2452
2453	public void resetSendingToWaiting(Account account) {
2454		for (Conversation conversation : getConversations()) {
2455			if (conversation.getAccount() == account) {
2456				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2457
2458					@Override
2459					public void onMessageFound(Message message) {
2460						markMessage(message, Message.STATUS_WAITING);
2461					}
2462				});
2463			}
2464		}
2465	}
2466
2467	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2468		if (uuid == null) {
2469			return null;
2470		}
2471		for (Conversation conversation : getConversations()) {
2472			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2473				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2474				if (message != null) {
2475					markMessage(message, status);
2476				}
2477				return message;
2478			}
2479		}
2480		return null;
2481	}
2482
2483	public boolean markMessage(Conversation conversation, String uuid, int status) {
2484		if (uuid == null) {
2485			return false;
2486		} else {
2487			Message message = conversation.findSentMessageWithUuid(uuid);
2488			if (message != null) {
2489				markMessage(message, status);
2490				return true;
2491			} else {
2492				return false;
2493			}
2494		}
2495	}
2496
2497	public void markMessage(Message message, int status) {
2498		if (status == Message.STATUS_SEND_FAILED
2499				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2500				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2501			return;
2502		}
2503		message.setStatus(status);
2504		databaseBackend.updateMessage(message);
2505		updateConversationUi();
2506	}
2507
2508	public SharedPreferences getPreferences() {
2509		return PreferenceManager
2510				.getDefaultSharedPreferences(getApplicationContext());
2511	}
2512
2513	public boolean forceEncryption() {
2514		return getPreferences().getBoolean("force_encryption", false);
2515	}
2516
2517	public boolean confirmMessages() {
2518		return getPreferences().getBoolean("confirm_messages", true);
2519	}
2520
2521	public boolean sendChatStates() {
2522		return getPreferences().getBoolean("chat_states", false);
2523	}
2524
2525	public boolean saveEncryptedMessages() {
2526		return !getPreferences().getBoolean("dont_save_encrypted", false);
2527	}
2528
2529	public boolean indicateReceived() {
2530		return getPreferences().getBoolean("indicate_received", false);
2531	}
2532
2533	public int unreadCount() {
2534		int count = 0;
2535		for (Conversation conversation : getConversations()) {
2536			count += conversation.unreadCount();
2537		}
2538		return count;
2539	}
2540
2541
2542	public void showErrorToastInUi(int resId) {
2543		if (mOnShowErrorToast != null) {
2544			mOnShowErrorToast.onShowErrorToast(resId);
2545		}
2546	}
2547
2548	public void updateConversationUi() {
2549		if (mOnConversationUpdate != null) {
2550			mOnConversationUpdate.onConversationUpdate();
2551		}
2552	}
2553
2554	public void updateAccountUi() {
2555		if (mOnAccountUpdate != null) {
2556			mOnAccountUpdate.onAccountUpdate();
2557		}
2558	}
2559
2560	public void updateRosterUi() {
2561		if (mOnRosterUpdate != null) {
2562			mOnRosterUpdate.onRosterUpdate();
2563		}
2564	}
2565
2566	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2567		boolean rc = false;
2568		if (mOnCaptchaRequested != null) {
2569			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2570			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2571					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2572
2573			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2574			rc = true;
2575		}
2576
2577		return rc;
2578	}
2579
2580	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2581		if (mOnUpdateBlocklist != null) {
2582			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2583		}
2584	}
2585
2586	public void updateMucRosterUi() {
2587		if (mOnMucRosterUpdate != null) {
2588			mOnMucRosterUpdate.onMucRosterUpdate();
2589		}
2590	}
2591
2592	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2593		if (mOnKeyStatusUpdated != null) {
2594			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2595		}
2596	}
2597
2598	public Account findAccountByJid(final Jid accountJid) {
2599		for (Account account : this.accounts) {
2600			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2601				return account;
2602			}
2603		}
2604		return null;
2605	}
2606
2607	public Conversation findConversationByUuid(String uuid) {
2608		for (Conversation conversation : getConversations()) {
2609			if (conversation.getUuid().equals(uuid)) {
2610				return conversation;
2611			}
2612		}
2613		return null;
2614	}
2615
2616	public void markRead(final Conversation conversation) {
2617		mNotificationService.clear(conversation);
2618		for (Message message : conversation.markRead()) {
2619			databaseBackend.updateMessage(message);
2620		}
2621		updateUnreadCountBadge();
2622	}
2623
2624	public synchronized void updateUnreadCountBadge() {
2625		int count = unreadCount();
2626		if (unreadCount != count) {
2627			Log.d(Config.LOGTAG, "update unread count to " + count);
2628			if (count > 0) {
2629				ShortcutBadger.with(getApplicationContext()).count(count);
2630			} else {
2631				ShortcutBadger.with(getApplicationContext()).remove();
2632			}
2633			unreadCount = count;
2634		}
2635	}
2636
2637	public void sendReadMarker(final Conversation conversation) {
2638		final Message markable = conversation.getLatestMarkableMessage();
2639		this.markRead(conversation);
2640		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2641			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2642			Account account = conversation.getAccount();
2643			final Jid to = markable.getCounterpart();
2644			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2645			this.sendMessagePacket(conversation.getAccount(), packet);
2646		}
2647		updateConversationUi();
2648	}
2649
2650	public SecureRandom getRNG() {
2651		return this.mRandom;
2652	}
2653
2654	public MemorizingTrustManager getMemorizingTrustManager() {
2655		return this.mMemorizingTrustManager;
2656	}
2657
2658	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2659		this.mMemorizingTrustManager = trustManager;
2660	}
2661
2662	public void updateMemorizingTrustmanager() {
2663		final MemorizingTrustManager tm;
2664		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2665		if (dontTrustSystemCAs) {
2666			tm = new MemorizingTrustManager(getApplicationContext(), null);
2667		} else {
2668			tm = new MemorizingTrustManager(getApplicationContext());
2669		}
2670		setMemorizingTrustManager(tm);
2671	}
2672
2673	public PowerManager getPowerManager() {
2674		return this.pm;
2675	}
2676
2677	public LruCache<String, Bitmap> getBitmapCache() {
2678		return this.mBitmapCache;
2679	}
2680
2681	public void syncRosterToDisk(final Account account) {
2682		Runnable runnable = new Runnable() {
2683
2684			@Override
2685			public void run() {
2686				databaseBackend.writeRoster(account.getRoster());
2687			}
2688		};
2689		mDatabaseExecutor.execute(runnable);
2690
2691	}
2692
2693	public List<String> getKnownHosts() {
2694		final List<String> hosts = new ArrayList<>();
2695		for (final Account account : getAccounts()) {
2696			if (!hosts.contains(account.getServer().toString())) {
2697				hosts.add(account.getServer().toString());
2698			}
2699			for (final Contact contact : account.getRoster().getContacts()) {
2700				if (contact.showInRoster()) {
2701					final String server = contact.getServer().toString();
2702					if (server != null && !hosts.contains(server)) {
2703						hosts.add(server);
2704					}
2705				}
2706			}
2707		}
2708		return hosts;
2709	}
2710
2711	public List<String> getKnownConferenceHosts() {
2712		final ArrayList<String> mucServers = new ArrayList<>();
2713		for (final Account account : accounts) {
2714			if (account.getXmppConnection() != null) {
2715				final String server = account.getXmppConnection().getMucServer();
2716				if (server != null && !mucServers.contains(server)) {
2717					mucServers.add(server);
2718				}
2719			}
2720		}
2721		return mucServers;
2722	}
2723
2724	public void sendMessagePacket(Account account, MessagePacket packet) {
2725		XmppConnection connection = account.getXmppConnection();
2726		if (connection != null) {
2727			connection.sendMessagePacket(packet);
2728		}
2729	}
2730
2731	public void sendPresencePacket(Account account, PresencePacket packet) {
2732		XmppConnection connection = account.getXmppConnection();
2733		if (connection != null) {
2734			connection.sendPresencePacket(packet);
2735		}
2736	}
2737
2738	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2739		XmppConnection connection = account.getXmppConnection();
2740		if (connection != null) {
2741			connection.sendCaptchaRegistryRequest(id, data);
2742		}
2743	}
2744
2745	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2746		final XmppConnection connection = account.getXmppConnection();
2747		if (connection != null) {
2748			connection.sendIqPacket(packet, callback);
2749		}
2750	}
2751
2752	public void sendPresence(final Account account) {
2753		sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2754	}
2755
2756	public void refreshAllPresences() {
2757		for (Account account : getAccounts()) {
2758			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2759				sendPresence(account);
2760			}
2761		}
2762	}
2763
2764	public void sendOfflinePresence(final Account account) {
2765		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2766	}
2767
2768	public MessageGenerator getMessageGenerator() {
2769		return this.mMessageGenerator;
2770	}
2771
2772	public PresenceGenerator getPresenceGenerator() {
2773		return this.mPresenceGenerator;
2774	}
2775
2776	public IqGenerator getIqGenerator() {
2777		return this.mIqGenerator;
2778	}
2779
2780	public IqParser getIqParser() {
2781		return this.mIqParser;
2782	}
2783
2784	public JingleConnectionManager getJingleConnectionManager() {
2785		return this.mJingleConnectionManager;
2786	}
2787
2788	public MessageArchiveService getMessageArchiveService() {
2789		return this.mMessageArchiveService;
2790	}
2791
2792	public List<Contact> findContacts(Jid jid) {
2793		ArrayList<Contact> contacts = new ArrayList<>();
2794		for (Account account : getAccounts()) {
2795			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2796				Contact contact = account.getRoster().getContactFromRoster(jid);
2797				if (contact != null) {
2798					contacts.add(contact);
2799				}
2800			}
2801		}
2802		return contacts;
2803	}
2804
2805	public NotificationService getNotificationService() {
2806		return this.mNotificationService;
2807	}
2808
2809	public HttpConnectionManager getHttpConnectionManager() {
2810		return this.mHttpConnectionManager;
2811	}
2812
2813	public void resendFailedMessages(final Message message) {
2814		final Collection<Message> messages = new ArrayList<>();
2815		Message current = message;
2816		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2817			messages.add(current);
2818			if (current.mergeable(current.next())) {
2819				current = current.next();
2820			} else {
2821				break;
2822			}
2823		}
2824		for (final Message msg : messages) {
2825			msg.setTime(System.currentTimeMillis());
2826			markMessage(msg, Message.STATUS_WAITING);
2827			this.resendMessage(msg, false);
2828		}
2829	}
2830
2831	public void clearConversationHistory(final Conversation conversation) {
2832		conversation.clearMessages();
2833		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2834		conversation.resetLastMessageTransmitted();
2835		new Thread(new Runnable() {
2836			@Override
2837			public void run() {
2838				databaseBackend.deleteMessagesInConversation(conversation);
2839			}
2840		}).start();
2841	}
2842
2843	public void sendBlockRequest(final Blockable blockable) {
2844		if (blockable != null && blockable.getBlockedJid() != null) {
2845			final Jid jid = blockable.getBlockedJid();
2846			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2847
2848				@Override
2849				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2850					if (packet.getType() == IqPacket.TYPE.RESULT) {
2851						account.getBlocklist().add(jid);
2852						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2853					}
2854				}
2855			});
2856		}
2857	}
2858
2859	public void sendUnblockRequest(final Blockable blockable) {
2860		if (blockable != null && blockable.getJid() != null) {
2861			final Jid jid = blockable.getBlockedJid();
2862			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2863				@Override
2864				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2865					if (packet.getType() == IqPacket.TYPE.RESULT) {
2866						account.getBlocklist().remove(jid);
2867						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2868					}
2869				}
2870			});
2871		}
2872	}
2873
2874	public interface OnAccountCreated {
2875		void onAccountCreated(Account account);
2876
2877		void informUser(int r);
2878	}
2879
2880	public interface OnMoreMessagesLoaded {
2881		void onMoreMessagesLoaded(int count, Conversation conversation);
2882
2883		void informUser(int r);
2884	}
2885
2886	public interface OnAccountPasswordChanged {
2887		void onPasswordChangeSucceeded();
2888
2889		void onPasswordChangeFailed();
2890	}
2891
2892	public interface OnAffiliationChanged {
2893		void onAffiliationChangedSuccessful(Jid jid);
2894
2895		void onAffiliationChangeFailed(Jid jid, int resId);
2896	}
2897
2898	public interface OnRoleChanged {
2899		void onRoleChangedSuccessful(String nick);
2900
2901		void onRoleChangeFailed(String nick, int resid);
2902	}
2903
2904	public interface OnConversationUpdate {
2905		void onConversationUpdate();
2906	}
2907
2908	public interface OnAccountUpdate {
2909		void onAccountUpdate();
2910	}
2911
2912	public interface OnCaptchaRequested {
2913		void onCaptchaRequested(Account account,
2914								String id,
2915								Data data,
2916								Bitmap captcha);
2917	}
2918
2919	public interface OnRosterUpdate {
2920		void onRosterUpdate();
2921	}
2922
2923	public interface OnMucRosterUpdate {
2924		void onMucRosterUpdate();
2925	}
2926
2927	public interface OnConferenceConfigurationFetched {
2928		void onConferenceConfigurationFetched(Conversation conversation);
2929
2930		void onFetchFailed(Conversation conversation, Element error);
2931	}
2932
2933	public interface OnConferenceOptionsPushed {
2934		void onPushSucceeded();
2935
2936		void onPushFailed();
2937	}
2938
2939	public interface OnShowErrorToast {
2940		void onShowErrorToast(int resId);
2941	}
2942
2943	public class XmppConnectionBinder extends Binder {
2944		public XmppConnectionService getService() {
2945			return XmppConnectionService.this;
2946		}
2947	}
2948}