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