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