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