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