XmppConnectionService.java

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