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