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