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