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.registerXmppConnectionService(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() && hasEnabledAccounts()) {
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								|| conversation.getMode() == Conversation.MODE_MULTI
1235								|| message.fixCounterpart()) {
1236							this.sendFileMessage(message, delay);
1237						} else {
1238							break;
1239						}
1240					} else {
1241						packet = mMessageGenerator.generateChat(message);
1242					}
1243					break;
1244				case Message.ENCRYPTION_PGP:
1245				case Message.ENCRYPTION_DECRYPTED:
1246					if (message.needsUploading()) {
1247						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1248								|| conversation.getMode() == Conversation.MODE_MULTI
1249								|| message.fixCounterpart()) {
1250							this.sendFileMessage(message, delay);
1251						} else {
1252							break;
1253						}
1254					} else {
1255						packet = mMessageGenerator.generatePgpChat(message);
1256					}
1257					break;
1258				case Message.ENCRYPTION_OTR:
1259					SessionImpl otrSession = conversation.getOtrSession();
1260					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
1261						try {
1262							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
1263						} catch (InvalidJidException e) {
1264							break;
1265						}
1266						if (message.needsUploading()) {
1267							mJingleConnectionManager.createNewConnection(message);
1268						} else {
1269							packet = mMessageGenerator.generateOtrChat(message);
1270						}
1271					} else if (otrSession == null) {
1272						if (message.fixCounterpart()) {
1273							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
1274						} else {
1275							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fix counterpart for OTR message to contact "+message.getContact().getJid());
1276							break;
1277						}
1278					} else {
1279						Log.d(Config.LOGTAG,account.getJid().toBareJid()+" OTR session with "+message.getContact()+" is in wrong state: "+otrSession.getSessionStatus().toString());
1280					}
1281					break;
1282				case Message.ENCRYPTION_AXOLOTL:
1283					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1284					if (message.needsUploading()) {
1285						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1286								|| conversation.getMode() == Conversation.MODE_MULTI
1287								|| message.fixCounterpart()) {
1288							this.sendFileMessage(message, delay);
1289						} else {
1290							break;
1291						}
1292					} else {
1293						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1294						if (axolotlMessage == null) {
1295							account.getAxolotlService().preparePayloadMessage(message, delay);
1296						} else {
1297							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1298						}
1299					}
1300					break;
1301
1302			}
1303			if (packet != null) {
1304				if (account.getXmppConnection().getFeatures().sm()
1305						|| (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1306					message.setStatus(Message.STATUS_UNSEND);
1307				} else {
1308					message.setStatus(Message.STATUS_SEND);
1309				}
1310			}
1311		} else {
1312			switch (message.getEncryption()) {
1313				case Message.ENCRYPTION_DECRYPTED:
1314					if (!message.needsUploading()) {
1315						String pgpBody = message.getEncryptedBody();
1316						String decryptedBody = message.getBody();
1317						message.setBody(pgpBody);
1318						message.setEncryption(Message.ENCRYPTION_PGP);
1319						if (message.edited()) {
1320							message.setBody(decryptedBody);
1321							message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1322							databaseBackend.updateMessage(message, message.getEditedId());
1323							updateConversationUi();
1324							return;
1325						} else {
1326							databaseBackend.createMessage(message);
1327							saveInDb = false;
1328							message.setBody(decryptedBody);
1329							message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1330						}
1331					}
1332					break;
1333				case Message.ENCRYPTION_OTR:
1334					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
1335						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": create otr session without starting for "+message.getContact().getJid());
1336						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
1337					}
1338					break;
1339				case Message.ENCRYPTION_AXOLOTL:
1340					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1341					break;
1342			}
1343		}
1344
1345		if (resend) {
1346			if (packet != null && addToConversation) {
1347				if (account.getXmppConnection().getFeatures().sm()
1348						|| (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1349					markMessage(message, Message.STATUS_UNSEND);
1350				} else {
1351					markMessage(message, Message.STATUS_SEND);
1352				}
1353			}
1354		} else {
1355			if (addToConversation) {
1356				conversation.add(message);
1357			}
1358			if (saveInDb) {
1359				databaseBackend.createMessage(message);
1360			} else if (message.edited()) {
1361				databaseBackend.updateMessage(message, message.getEditedId());
1362			}
1363			updateConversationUi();
1364		}
1365		if (packet != null) {
1366			if (delay) {
1367				mMessageGenerator.addDelay(packet, message.getTimeSent());
1368			}
1369			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1370				if (this.sendChatStates()) {
1371					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1372				}
1373			}
1374			sendMessagePacket(account, packet);
1375		}
1376	}
1377
1378	private void sendUnsentMessages(final Conversation conversation) {
1379		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
1380
1381			@Override
1382			public void onMessageFound(Message message) {
1383				resendMessage(message, true);
1384			}
1385		});
1386	}
1387
1388	public void resendMessage(final Message message, final boolean delay) {
1389		sendMessage(message, true, delay);
1390	}
1391
1392	public void fetchRosterFromServer(final Account account) {
1393		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1394		if (!"".equals(account.getRosterVersion())) {
1395			Log.d(Config.LOGTAG, account.getJid().toBareJid()
1396					+ ": fetching roster version " + account.getRosterVersion());
1397		} else {
1398			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1399		}
1400		iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1401		sendIqPacket(account, iqPacket, mIqParser);
1402	}
1403
1404	public void fetchBookmarks(final Account account) {
1405		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1406		final Element query = iqPacket.query("jabber:iq:private");
1407		query.addChild("storage", "storage:bookmarks");
1408		final OnIqPacketReceived callback = new OnIqPacketReceived() {
1409
1410			@Override
1411			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1412				if (packet.getType() == IqPacket.TYPE.RESULT) {
1413					final Element query = packet.query();
1414					final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1415					final Element storage = query.findChild("storage", "storage:bookmarks");
1416					final boolean autojoin = respectAutojoin();
1417					if (storage != null) {
1418						for (final Element item : storage.getChildren()) {
1419							if (item.getName().equals("conference")) {
1420								final Bookmark bookmark = Bookmark.parse(item, account);
1421								Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1422								if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1423									bookmark.setBookmarkName(old.getBookmarkName());
1424								}
1425								Conversation conversation = find(bookmark);
1426								if (conversation != null) {
1427									conversation.setBookmark(bookmark);
1428								} else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1429									conversation = findOrCreateConversation(account, bookmark.getJid(), true, true, false);
1430									conversation.setBookmark(bookmark);
1431								}
1432							}
1433						}
1434					}
1435					account.setBookmarks(new ArrayList<>(bookmarks.values()));
1436				} else {
1437					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1438				}
1439			}
1440		};
1441		sendIqPacket(account, iqPacket, callback);
1442	}
1443
1444	public void pushBookmarks(Account account) {
1445		Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1446		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1447		Element query = iqPacket.query("jabber:iq:private");
1448		Element storage = query.addChild("storage", "storage:bookmarks");
1449		for (Bookmark bookmark : account.getBookmarks()) {
1450			storage.addChild(bookmark);
1451		}
1452		sendIqPacket(account, iqPacket, mDefaultIqHandler);
1453	}
1454
1455	private void restoreFromDatabase() {
1456		synchronized (this.conversations) {
1457			final Map<String, Account> accountLookupTable = new Hashtable<>();
1458			for (Account account : this.accounts) {
1459				accountLookupTable.put(account.getUuid(), account);
1460			}
1461			Log.d(Config.LOGTAG,"restoring conversations...");
1462			final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1463			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1464			for(Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext();) {
1465				Conversation conversation = iterator.next();
1466				Account account = accountLookupTable.get(conversation.getAccountUuid());
1467				if (account != null) {
1468					conversation.setAccount(account);
1469				} else {
1470					Log.e(Config.LOGTAG,"unable to restore Conversations with "+conversation.getJid());
1471					iterator.remove();
1472				}
1473			}
1474			long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1475			Log.d(Config.LOGTAG,"finished restoring conversations in "+diffConversationsRestore+"ms");
1476			Runnable runnable = new Runnable() {
1477				@Override
1478				public void run() {
1479					long deletionDate = getAutomaticMessageDeletionDate();
1480					mLastExpiryRun.set(SystemClock.elapsedRealtime());
1481					if (deletionDate > 0) {
1482						Log.d(Config.LOGTAG, "deleting messages that are older than "+AbstractGenerator.getTimestamp(deletionDate));
1483						databaseBackend.expireOldMessages(deletionDate);
1484					}
1485					Log.d(Config.LOGTAG,"restoring roster...");
1486					for (Account account : accounts) {
1487						databaseBackend.readRoster(account.getRoster());
1488						account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1489					}
1490					getBitmapCache().evictAll();
1491					loadPhoneContacts();
1492					Log.d(Config.LOGTAG, "restoring messages...");
1493					final long startMessageRestore = SystemClock.elapsedRealtime();
1494					for (Conversation conversation : conversations) {
1495						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1496						checkDeletedFiles(conversation);
1497						conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
1498
1499							@Override
1500							public void onMessageFound(Message message) {
1501								markMessage(message, Message.STATUS_WAITING);
1502							}
1503						});
1504						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1505							@Override
1506							public void onMessageFound(Message message) {
1507								mNotificationService.pushFromBacklog(message);
1508							}
1509						});
1510					}
1511					mNotificationService.finishBacklog(false);
1512					mRestoredFromDatabase = true;
1513					final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1514					Log.d(Config.LOGTAG, "finished restoring messages in "+diffMessageRestore+"ms");
1515					updateConversationUi();
1516				}
1517			};
1518			mDatabaseExecutor.execute(runnable);
1519		}
1520	}
1521
1522	public void loadPhoneContacts() {
1523		mContactMergerExecutor.execute(new Runnable() {
1524			@Override
1525			public void run() {
1526				PhoneHelper.loadPhoneContacts(XmppConnectionService.this, new OnPhoneContactsLoadedListener() {
1527					@Override
1528					public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
1529						Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1530						for (Account account : accounts) {
1531							List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1532							for (Bundle phoneContact : phoneContacts) {
1533								Jid jid;
1534								try {
1535									jid = Jid.fromString(phoneContact.getString("jid"));
1536								} catch (final InvalidJidException e) {
1537									continue;
1538								}
1539								final Contact contact = account.getRoster().getContact(jid);
1540								String systemAccount = phoneContact.getInt("phoneid")
1541										+ "#"
1542										+ phoneContact.getString("lookup");
1543								contact.setSystemAccount(systemAccount);
1544								boolean needsCacheClean = contact.setPhotoUri(phoneContact.getString("photouri"));
1545								needsCacheClean |= contact.setSystemName(phoneContact.getString("displayname"));
1546								if (needsCacheClean) {
1547									getAvatarService().clear(contact);
1548								}
1549								withSystemAccounts.remove(contact);
1550							}
1551							for (Contact contact : withSystemAccounts) {
1552								contact.setSystemAccount(null);
1553								boolean needsCacheClean = contact.setPhotoUri(null);
1554								needsCacheClean |= contact.setSystemName(null);
1555								if (needsCacheClean) {
1556									getAvatarService().clear(contact);
1557								}
1558							}
1559						}
1560						Log.d(Config.LOGTAG, "finished merging phone contacts");
1561						mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false,true));
1562						updateAccountUi();
1563					}
1564				});
1565			}
1566		});
1567	}
1568
1569	public List<Conversation> getConversations() {
1570		return this.conversations;
1571	}
1572
1573	private void checkDeletedFiles(Conversation conversation) {
1574		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1575
1576			@Override
1577			public void onMessageFound(Message message) {
1578				if (!getFileBackend().isFileAvailable(message)) {
1579					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1580					final int s = message.getStatus();
1581					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1582						markMessage(message, Message.STATUS_SEND_FAILED);
1583					}
1584				}
1585			}
1586		});
1587	}
1588
1589	private void markFileDeleted(final String path) {
1590		Log.d(Config.LOGTAG,"deleted file "+path);
1591		for (Conversation conversation : getConversations()) {
1592			conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1593				@Override
1594				public void onMessageFound(Message message) {
1595					DownloadableFile file = fileBackend.getFile(message);
1596					if (file.getAbsolutePath().equals(path)) {
1597						if (!file.exists()) {
1598							message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1599							final int s = message.getStatus();
1600							if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1601								markMessage(message, Message.STATUS_SEND_FAILED);
1602							} else {
1603								updateConversationUi();
1604							}
1605						} else {
1606							Log.d(Config.LOGTAG,"found matching message for file "+path+" but file still exists");
1607						}
1608					}
1609				}
1610			});
1611		}
1612	}
1613
1614	public void populateWithOrderedConversations(final List<Conversation> list) {
1615		populateWithOrderedConversations(list, true);
1616	}
1617
1618	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1619		list.clear();
1620		if (includeNoFileUpload) {
1621			list.addAll(getConversations());
1622		} else {
1623			for (Conversation conversation : getConversations()) {
1624				if (conversation.getMode() == Conversation.MODE_SINGLE
1625						|| conversation.getAccount().httpUploadAvailable()) {
1626					list.add(conversation);
1627				}
1628			}
1629		}
1630		try {
1631			Collections.sort(list);
1632		} catch (IllegalArgumentException e) {
1633			//ignore
1634		}
1635	}
1636
1637	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1638		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1639			return;
1640		} else if (timestamp == 0) {
1641			return;
1642		}
1643		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1644		Runnable runnable = new Runnable() {
1645			@Override
1646			public void run() {
1647				final Account account = conversation.getAccount();
1648				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1649				if (messages.size() > 0) {
1650					conversation.addAll(0, messages);
1651					checkDeletedFiles(conversation);
1652					callback.onMoreMessagesLoaded(messages.size(), conversation);
1653				} else if (conversation.hasMessagesLeftOnServer()
1654						&& account.isOnlineAndConnected()
1655						&& conversation.getLastClearHistory().getTimestamp() == 0) {
1656					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1657							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1658						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
1659						if (query != null) {
1660							query.setCallback(callback);
1661							callback.informUser(R.string.fetching_history_from_server);
1662						} else {
1663							callback.informUser(R.string.not_fetching_history_retention_period);
1664						}
1665
1666					}
1667				}
1668			}
1669		};
1670		mDatabaseExecutor.execute(runnable);
1671	}
1672
1673	public List<Account> getAccounts() {
1674		return this.accounts;
1675	}
1676
1677	public List<Conversation> findAllConferencesWith(Contact contact) {
1678		ArrayList<Conversation> results = new ArrayList<>();
1679		for(Conversation conversation : conversations) {
1680			if (conversation.getMode() == Conversation.MODE_MULTI
1681					&& conversation.getMucOptions().isContactInRoom(contact)) {
1682				results.add(conversation);
1683			}
1684		}
1685		return results;
1686	}
1687
1688	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1689		for (final Conversation conversation : haystack) {
1690			if (conversation.getContact() == contact) {
1691				return conversation;
1692			}
1693		}
1694		return null;
1695	}
1696
1697	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1698		if (jid == null) {
1699			return null;
1700		}
1701		for (final Conversation conversation : haystack) {
1702			if ((account == null || conversation.getAccount() == account)
1703					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1704				return conversation;
1705			}
1706		}
1707		return null;
1708	}
1709
1710	public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1711		return this.findOrCreateConversation(account,jid,muc,false, async);
1712	}
1713
1714	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1715		return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1716	}
1717
1718	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1719		synchronized (this.conversations) {
1720			Conversation conversation = find(account, jid);
1721			if (conversation != null) {
1722				return conversation;
1723			}
1724			conversation = databaseBackend.findConversation(account, jid);
1725			final boolean loadMessagesFromDb;
1726			if (conversation != null) {
1727				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1728				conversation.setAccount(account);
1729				if (muc) {
1730					conversation.setMode(Conversation.MODE_MULTI);
1731					conversation.setContactJid(jid);
1732				} else {
1733					conversation.setMode(Conversation.MODE_SINGLE);
1734					conversation.setContactJid(jid.toBareJid());
1735				}
1736				databaseBackend.updateConversation(conversation);
1737				loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true,false);
1738			} else {
1739				String conversationName;
1740				Contact contact = account.getRoster().getContact(jid);
1741				if (contact != null) {
1742					conversationName = contact.getDisplayName();
1743				} else {
1744					conversationName = jid.getLocalpart();
1745				}
1746				if (muc) {
1747					conversation = new Conversation(conversationName, account, jid,
1748							Conversation.MODE_MULTI);
1749				} else {
1750					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1751							Conversation.MODE_SINGLE);
1752				}
1753				this.databaseBackend.createConversation(conversation);
1754				loadMessagesFromDb = false;
1755			}
1756			final Conversation c = conversation;
1757			final Runnable runnable = new Runnable() {
1758				@Override
1759				public void run() {
1760					if (loadMessagesFromDb) {
1761						c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1762						updateConversationUi();
1763						c.messagesLoaded.set(true);
1764					}
1765					if (account.getXmppConnection() != null
1766							&& account.getXmppConnection().getFeatures().mam()
1767							&& !muc) {
1768						if (query == null) {
1769							mMessageArchiveService.query(c);
1770						} else {
1771							if (query.getConversation() == null) {
1772								mMessageArchiveService.query(c, query.getStart(),query.isCatchup());
1773							}
1774						}
1775					}
1776					checkDeletedFiles(c);
1777					if (joinAfterCreate) {
1778						joinMuc(c);
1779					}
1780				}
1781			};
1782			if (async) {
1783				mDatabaseExecutor.execute(runnable);
1784			} else {
1785				runnable.run();
1786			}
1787			this.conversations.add(conversation);
1788			updateConversationUi();
1789			return conversation;
1790		}
1791	}
1792
1793	public void archiveConversation(Conversation conversation) {
1794		getNotificationService().clear(conversation);
1795		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1796		synchronized (this.conversations) {
1797			if (conversation.getMode() == Conversation.MODE_MULTI) {
1798				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1799					Bookmark bookmark = conversation.getBookmark();
1800					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1801						bookmark.setAutojoin(false);
1802						pushBookmarks(bookmark.getAccount());
1803					}
1804				}
1805				leaveMuc(conversation);
1806			} else {
1807				conversation.endOtrIfNeeded();
1808				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1809					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1810					sendPresencePacket(
1811							conversation.getAccount(),
1812							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1813					);
1814				}
1815			}
1816			updateConversation(conversation);
1817			this.conversations.remove(conversation);
1818			updateConversationUi();
1819		}
1820	}
1821
1822	public void createAccount(final Account account) {
1823		account.initAccountServices(this);
1824		databaseBackend.createAccount(account);
1825		this.accounts.add(account);
1826		this.reconnectAccountInBackground(account);
1827		updateAccountUi();
1828		toggleForegroundService();
1829	}
1830
1831	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1832		new Thread(new Runnable() {
1833			@Override
1834			public void run() {
1835				try {
1836					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1837					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1838					if (findAccountByJid(info.first) == null) {
1839						Account account = new Account(info.first, "");
1840						account.setPrivateKeyAlias(alias);
1841						account.setOption(Account.OPTION_DISABLED, true);
1842						account.setDisplayName(info.second);
1843						createAccount(account);
1844						callback.onAccountCreated(account);
1845						if (Config.X509_VERIFICATION) {
1846							try {
1847								getMemorizingTrustManager().getNonInteractive(account.getJid().getDomainpart()).checkClientTrusted(chain, "RSA");
1848							} catch (CertificateException e) {
1849								callback.informUser(R.string.certificate_chain_is_not_trusted);
1850							}
1851						}
1852					} else {
1853						callback.informUser(R.string.account_already_exists);
1854					}
1855				} catch (Exception e) {
1856					e.printStackTrace();
1857					callback.informUser(R.string.unable_to_parse_certificate);
1858				}
1859			}
1860		}).start();
1861
1862	}
1863
1864	public void updateKeyInAccount(final Account account, final String alias) {
1865		Log.d(Config.LOGTAG, account.getJid().toBareJid()+": update key in account " + alias);
1866		try {
1867			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1868			Log.d(Config.LOGTAG,account.getJid().toBareJid()+" loaded certificate chain");
1869			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1870			if (account.getJid().toBareJid().equals(info.first)) {
1871				account.setPrivateKeyAlias(alias);
1872				account.setDisplayName(info.second);
1873				databaseBackend.updateAccount(account);
1874				if (Config.X509_VERIFICATION) {
1875					try {
1876						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1877					} catch (CertificateException e) {
1878						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1879					}
1880					account.getAxolotlService().regenerateKeys(true);
1881				}
1882			} else {
1883				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1884			}
1885		} catch (Exception e) {
1886			e.printStackTrace();
1887		}
1888	}
1889
1890	public boolean updateAccount(final Account account) {
1891		if (databaseBackend.updateAccount(account)) {
1892			account.setShowErrorNotification(true);
1893			this.statusListener.onStatusChanged(account);
1894			databaseBackend.updateAccount(account);
1895			reconnectAccountInBackground(account);
1896			updateAccountUi();
1897			getNotificationService().updateErrorNotification();
1898			toggleForegroundService();
1899			return true;
1900		} else {
1901			return false;
1902		}
1903	}
1904
1905	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1906		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1907		sendIqPacket(account, iq, new OnIqPacketReceived() {
1908			@Override
1909			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1910				if (packet.getType() == IqPacket.TYPE.RESULT) {
1911					account.setPassword(newPassword);
1912					account.setOption(Account.OPTION_MAGIC_CREATE, false);
1913					databaseBackend.updateAccount(account);
1914					callback.onPasswordChangeSucceeded();
1915				} else {
1916					callback.onPasswordChangeFailed();
1917				}
1918			}
1919		});
1920	}
1921
1922	public void deleteAccount(final Account account) {
1923		synchronized (this.conversations) {
1924			for (final Conversation conversation : conversations) {
1925				if (conversation.getAccount() == account) {
1926					if (conversation.getMode() == Conversation.MODE_MULTI) {
1927						leaveMuc(conversation);
1928					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1929						conversation.endOtrIfNeeded();
1930					}
1931					conversations.remove(conversation);
1932				}
1933			}
1934			if (account.getXmppConnection() != null) {
1935				new Thread(new Runnable() {
1936					@Override
1937					public void run() {
1938						disconnect(account, true);
1939					}
1940				}).start();
1941			}
1942			Runnable runnable = new Runnable() {
1943				@Override
1944				public void run() {
1945					if (!databaseBackend.deleteAccount(account)) {
1946						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": unable to delete account");
1947					}
1948				}
1949			};
1950			mDatabaseExecutor.execute(runnable);
1951			this.accounts.remove(account);
1952			updateAccountUi();
1953			getNotificationService().updateErrorNotification();
1954		}
1955	}
1956
1957	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1958		synchronized (this) {
1959			this.mLastActivity = System.currentTimeMillis();
1960			if (checkListeners()) {
1961				switchToForeground();
1962			}
1963			this.mOnConversationUpdate = listener;
1964			this.mNotificationService.setIsInForeground(true);
1965			if (this.convChangedListenerCount < 2) {
1966				this.convChangedListenerCount++;
1967			}
1968		}
1969	}
1970
1971	public void removeOnConversationListChangedListener() {
1972		synchronized (this) {
1973			this.convChangedListenerCount--;
1974			if (this.convChangedListenerCount <= 0) {
1975				this.convChangedListenerCount = 0;
1976				this.mOnConversationUpdate = null;
1977				this.mNotificationService.setIsInForeground(false);
1978				if (checkListeners()) {
1979					switchToBackground();
1980				}
1981			}
1982		}
1983	}
1984
1985	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1986		synchronized (this) {
1987			if (checkListeners()) {
1988				switchToForeground();
1989			}
1990			this.mOnShowErrorToast = onShowErrorToast;
1991			if (this.showErrorToastListenerCount < 2) {
1992				this.showErrorToastListenerCount++;
1993			}
1994		}
1995		this.mOnShowErrorToast = onShowErrorToast;
1996	}
1997
1998	public void removeOnShowErrorToastListener() {
1999		synchronized (this) {
2000			this.showErrorToastListenerCount--;
2001			if (this.showErrorToastListenerCount <= 0) {
2002				this.showErrorToastListenerCount = 0;
2003				this.mOnShowErrorToast = null;
2004				if (checkListeners()) {
2005					switchToBackground();
2006				}
2007			}
2008		}
2009	}
2010
2011	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2012		synchronized (this) {
2013			if (checkListeners()) {
2014				switchToForeground();
2015			}
2016			this.mOnAccountUpdate = listener;
2017			if (this.accountChangedListenerCount < 2) {
2018				this.accountChangedListenerCount++;
2019			}
2020		}
2021	}
2022
2023	public void removeOnAccountListChangedListener() {
2024		synchronized (this) {
2025			this.accountChangedListenerCount--;
2026			if (this.accountChangedListenerCount <= 0) {
2027				this.mOnAccountUpdate = null;
2028				this.accountChangedListenerCount = 0;
2029				if (checkListeners()) {
2030					switchToBackground();
2031				}
2032			}
2033		}
2034	}
2035
2036	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2037		synchronized (this) {
2038			if (checkListeners()) {
2039				switchToForeground();
2040			}
2041			this.mOnCaptchaRequested = listener;
2042			if (this.captchaRequestedListenerCount < 2) {
2043				this.captchaRequestedListenerCount++;
2044			}
2045		}
2046	}
2047
2048	public void removeOnCaptchaRequestedListener() {
2049		synchronized (this) {
2050			this.captchaRequestedListenerCount--;
2051			if (this.captchaRequestedListenerCount <= 0) {
2052				this.mOnCaptchaRequested = null;
2053				this.captchaRequestedListenerCount = 0;
2054				if (checkListeners()) {
2055					switchToBackground();
2056				}
2057			}
2058		}
2059	}
2060
2061	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2062		synchronized (this) {
2063			if (checkListeners()) {
2064				switchToForeground();
2065			}
2066			this.mOnRosterUpdate = listener;
2067			if (this.rosterChangedListenerCount < 2) {
2068				this.rosterChangedListenerCount++;
2069			}
2070		}
2071	}
2072
2073	public void removeOnRosterUpdateListener() {
2074		synchronized (this) {
2075			this.rosterChangedListenerCount--;
2076			if (this.rosterChangedListenerCount <= 0) {
2077				this.rosterChangedListenerCount = 0;
2078				this.mOnRosterUpdate = null;
2079				if (checkListeners()) {
2080					switchToBackground();
2081				}
2082			}
2083		}
2084	}
2085
2086	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2087		synchronized (this) {
2088			if (checkListeners()) {
2089				switchToForeground();
2090			}
2091			this.mOnUpdateBlocklist = listener;
2092			if (this.updateBlocklistListenerCount < 2) {
2093				this.updateBlocklistListenerCount++;
2094			}
2095		}
2096	}
2097
2098	public void removeOnUpdateBlocklistListener() {
2099		synchronized (this) {
2100			this.updateBlocklistListenerCount--;
2101			if (this.updateBlocklistListenerCount <= 0) {
2102				this.updateBlocklistListenerCount = 0;
2103				this.mOnUpdateBlocklist = null;
2104				if (checkListeners()) {
2105					switchToBackground();
2106				}
2107			}
2108		}
2109	}
2110
2111	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2112		synchronized (this) {
2113			if (checkListeners()) {
2114				switchToForeground();
2115			}
2116			this.mOnKeyStatusUpdated = listener;
2117			if (this.keyStatusUpdatedListenerCount < 2) {
2118				this.keyStatusUpdatedListenerCount++;
2119			}
2120		}
2121	}
2122
2123	public void removeOnNewKeysAvailableListener() {
2124		synchronized (this) {
2125			this.keyStatusUpdatedListenerCount--;
2126			if (this.keyStatusUpdatedListenerCount <= 0) {
2127				this.keyStatusUpdatedListenerCount = 0;
2128				this.mOnKeyStatusUpdated = null;
2129				if (checkListeners()) {
2130					switchToBackground();
2131				}
2132			}
2133		}
2134	}
2135
2136	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2137		synchronized (this) {
2138			if (checkListeners()) {
2139				switchToForeground();
2140			}
2141			this.mOnMucRosterUpdate = listener;
2142			if (this.mucRosterChangedListenerCount < 2) {
2143				this.mucRosterChangedListenerCount++;
2144			}
2145		}
2146	}
2147
2148	public void removeOnMucRosterUpdateListener() {
2149		synchronized (this) {
2150			this.mucRosterChangedListenerCount--;
2151			if (this.mucRosterChangedListenerCount <= 0) {
2152				this.mucRosterChangedListenerCount = 0;
2153				this.mOnMucRosterUpdate = null;
2154				if (checkListeners()) {
2155					switchToBackground();
2156				}
2157			}
2158		}
2159	}
2160
2161	public boolean checkListeners() {
2162		return (this.mOnAccountUpdate == null
2163				&& this.mOnConversationUpdate == null
2164				&& this.mOnRosterUpdate == null
2165				&& this.mOnCaptchaRequested == null
2166				&& this.mOnUpdateBlocklist == null
2167				&& this.mOnShowErrorToast == null
2168				&& this.mOnKeyStatusUpdated == null);
2169	}
2170
2171	private void switchToForeground() {
2172		final boolean broadcastLastActivity = broadcastLastActivity();
2173		for (Conversation conversation : getConversations()) {
2174			if (conversation.getMode() == Conversation.MODE_MULTI) {
2175				conversation.getMucOptions().resetChatState();
2176			} else {
2177				conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2178			}
2179		}
2180		for (Account account : getAccounts()) {
2181			if (account.getStatus() == Account.State.ONLINE) {
2182				account.deactivateGracePeriod();
2183				final XmppConnection connection = account.getXmppConnection();
2184				if (connection != null ) {
2185					if (connection.getFeatures().csi()) {
2186						connection.sendActive();
2187					}
2188					if (broadcastLastActivity) {
2189						sendPresence(account, false); //send new presence but don't include idle because we are not
2190					}
2191				}
2192			}
2193		}
2194		Log.d(Config.LOGTAG, "app switched into foreground");
2195	}
2196
2197	private void switchToBackground() {
2198		final boolean broadcastLastActivity = broadcastLastActivity();
2199		for (Account account : getAccounts()) {
2200			if (account.getStatus() == Account.State.ONLINE) {
2201				XmppConnection connection = account.getXmppConnection();
2202				if (connection != null) {
2203					if (broadcastLastActivity) {
2204						sendPresence(account, true);
2205					}
2206					if (connection.getFeatures().csi()) {
2207						connection.sendInactive();
2208					}
2209				}
2210			}
2211		}
2212		this.mNotificationService.setIsInForeground(false);
2213		Log.d(Config.LOGTAG, "app switched into background");
2214	}
2215
2216	private void connectMultiModeConversations(Account account) {
2217		List<Conversation> conversations = getConversations();
2218		for (Conversation conversation : conversations) {
2219			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2220				joinMuc(conversation);
2221			}
2222		}
2223	}
2224
2225	public void joinMuc(Conversation conversation) {
2226		joinMuc(conversation,null, false);
2227	}
2228
2229	public void joinMuc(Conversation conversation, boolean followedInvite) {
2230		joinMuc(conversation, null, followedInvite);
2231	}
2232
2233	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2234		joinMuc(conversation,onConferenceJoined,false);
2235	}
2236
2237	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2238		Account account = conversation.getAccount();
2239		account.pendingConferenceJoins.remove(conversation);
2240		account.pendingConferenceLeaves.remove(conversation);
2241		if (account.getStatus() == Account.State.ONLINE) {
2242			conversation.resetMucOptions();
2243			if (onConferenceJoined != null) {
2244				conversation.getMucOptions().flagNoAutoPushConfiguration();
2245			}
2246			conversation.setHasMessagesLeftOnServer(false);
2247			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2248
2249				private void join(Conversation conversation) {
2250					Account account = conversation.getAccount();
2251					final MucOptions mucOptions = conversation.getMucOptions();
2252					final Jid joinJid = mucOptions.getSelf().getFullJid();
2253					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
2254					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2255					packet.setTo(joinJid);
2256					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2257					if (conversation.getMucOptions().getPassword() != null) {
2258						x.addChild("password").setContent(mucOptions.getPassword());
2259					}
2260
2261					if (mucOptions.mamSupport()) {
2262						// Use MAM instead of the limited muc history to get history
2263						x.addChild("history").setAttribute("maxchars", "0");
2264					} else {
2265						// Fallback to muc history
2266						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2267					}
2268					sendPresencePacket(account, packet);
2269					if (onConferenceJoined != null) {
2270						onConferenceJoined.onConferenceJoined(conversation);
2271					}
2272					if (!joinJid.equals(conversation.getJid())) {
2273						conversation.setContactJid(joinJid);
2274						databaseBackend.updateConversation(conversation);
2275					}
2276
2277					if (mucOptions.mamSupport()) {
2278						getMessageArchiveService().catchupMUC(conversation);
2279					}
2280					if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
2281						fetchConferenceMembers(conversation);
2282						if (followedInvite && conversation.getBookmark() == null) {
2283							saveConversationAsBookmark(conversation,null);
2284						}
2285					}
2286					sendUnsentMessages(conversation);
2287				}
2288
2289				@Override
2290				public void onConferenceConfigurationFetched(Conversation conversation) {
2291					join(conversation);
2292				}
2293
2294				@Override
2295				public void onFetchFailed(final Conversation conversation, Element error) {
2296					if (error != null && "remote-server-not-found".equals(error.getName())) {
2297						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2298						updateConversationUi();
2299					} else {
2300						join(conversation);
2301						fetchConferenceConfiguration(conversation);
2302					}
2303				}
2304			});
2305			updateConversationUi();
2306		} else {
2307			account.pendingConferenceJoins.add(conversation);
2308			conversation.resetMucOptions();
2309			conversation.setHasMessagesLeftOnServer(false);
2310			updateConversationUi();
2311		}
2312	}
2313
2314	private void fetchConferenceMembers(final Conversation conversation) {
2315		final Account account = conversation.getAccount();
2316		final String[] affiliations = {"member","admin","owner"};
2317		OnIqPacketReceived callback = new OnIqPacketReceived() {
2318
2319			private int i = 0;
2320			private boolean success = true;
2321
2322			@Override
2323			public void onIqPacketReceived(Account account, IqPacket packet) {
2324
2325				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2326				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2327					for(Element child : query.getChildren()) {
2328						if ("item".equals(child.getName())) {
2329							MucOptions.User user = AbstractParser.parseItem(conversation,child);
2330							if (!user.realJidMatchesAccount()) {
2331								conversation.getMucOptions().updateUser(user);
2332							}
2333						}
2334					}
2335				} else {
2336					success = false;
2337					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
2338				}
2339				++i;
2340				if (i >= affiliations.length) {
2341					List<Jid> members = conversation.getMucOptions().getMembers();
2342					if (success) {
2343						List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2344						boolean changed = false;
2345						for(ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext();) {
2346							Jid jid = iterator.next();
2347							if (!members.contains(jid)) {
2348								iterator.remove();
2349								Log.d(Config.LOGTAG,account.getJid().toBareJid()+": removed "+jid+" from crypto targets of "+conversation.getName());
2350								changed = true;
2351							}
2352						}
2353						if (changed) {
2354							conversation.setAcceptedCryptoTargets(cryptoTargets);
2355							updateConversation(conversation);
2356						}
2357					}
2358					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
2359					getAvatarService().clear(conversation);
2360					updateMucRosterUi();
2361					updateConversationUi();
2362				}
2363			}
2364		};
2365		for(String affiliation : affiliations) {
2366			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2367		}
2368		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
2369	}
2370
2371	public void providePasswordForMuc(Conversation conversation, String password) {
2372		if (conversation.getMode() == Conversation.MODE_MULTI) {
2373			conversation.getMucOptions().setPassword(password);
2374			if (conversation.getBookmark() != null) {
2375				if (respectAutojoin()) {
2376					conversation.getBookmark().setAutojoin(true);
2377				}
2378				pushBookmarks(conversation.getAccount());
2379			}
2380			updateConversation(conversation);
2381			joinMuc(conversation);
2382		}
2383	}
2384
2385	private boolean hasEnabledAccounts() {
2386		for(Account account : this.accounts) {
2387			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2388				return true;
2389			}
2390		}
2391		return false;
2392	}
2393
2394	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2395		final MucOptions options = conversation.getMucOptions();
2396		final Jid joinJid = options.createJoinJid(nick);
2397		if (options.online()) {
2398			Account account = conversation.getAccount();
2399			options.setOnRenameListener(new OnRenameListener() {
2400
2401				@Override
2402				public void onSuccess() {
2403					conversation.setContactJid(joinJid);
2404					databaseBackend.updateConversation(conversation);
2405					Bookmark bookmark = conversation.getBookmark();
2406					if (bookmark != null) {
2407						bookmark.setNick(nick);
2408						pushBookmarks(bookmark.getAccount());
2409					}
2410					callback.success(conversation);
2411				}
2412
2413				@Override
2414				public void onFailure() {
2415					callback.error(R.string.nick_in_use, conversation);
2416				}
2417			});
2418
2419			PresencePacket packet = new PresencePacket();
2420			packet.setTo(joinJid);
2421			packet.setFrom(conversation.getAccount().getJid());
2422
2423			String sig = account.getPgpSignature();
2424			if (sig != null) {
2425				packet.addChild("status").setContent("online");
2426				packet.addChild("x", "jabber:x:signed").setContent(sig);
2427			}
2428			sendPresencePacket(account, packet);
2429		} else {
2430			conversation.setContactJid(joinJid);
2431			databaseBackend.updateConversation(conversation);
2432			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2433				Bookmark bookmark = conversation.getBookmark();
2434				if (bookmark != null) {
2435					bookmark.setNick(nick);
2436					pushBookmarks(bookmark.getAccount());
2437				}
2438				joinMuc(conversation);
2439			}
2440		}
2441	}
2442
2443	public void leaveMuc(Conversation conversation) {
2444		leaveMuc(conversation, false);
2445	}
2446
2447	private void leaveMuc(Conversation conversation, boolean now) {
2448		Account account = conversation.getAccount();
2449		account.pendingConferenceJoins.remove(conversation);
2450		account.pendingConferenceLeaves.remove(conversation);
2451		if (account.getStatus() == Account.State.ONLINE || now) {
2452			PresencePacket packet = new PresencePacket();
2453			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2454			packet.setFrom(conversation.getAccount().getJid());
2455			packet.setAttribute("type", "unavailable");
2456			sendPresencePacket(conversation.getAccount(), packet);
2457			conversation.getMucOptions().setOffline();
2458			conversation.deregisterWithBookmark();
2459			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2460					+ ": leaving muc " + conversation.getJid());
2461		} else {
2462			account.pendingConferenceLeaves.add(conversation);
2463		}
2464	}
2465
2466	public String findConferenceServer(final Account account) {
2467		String server;
2468		if (account.getXmppConnection() != null) {
2469			server = account.getXmppConnection().getMucServer();
2470			if (server != null) {
2471				return server;
2472			}
2473		}
2474		for (Account other : getAccounts()) {
2475			if (other != account && other.getXmppConnection() != null) {
2476				server = other.getXmppConnection().getMucServer();
2477				if (server != null) {
2478					return server;
2479				}
2480			}
2481		}
2482		return null;
2483	}
2484
2485	public boolean createAdhocConference(final Account account,
2486									  final String subject,
2487									  final Iterable<Jid> jids,
2488									  final UiCallback<Conversation> callback) {
2489		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2490		if (account.getStatus() == Account.State.ONLINE) {
2491			try {
2492				String server = findConferenceServer(account);
2493				if (server == null) {
2494					if (callback != null) {
2495						callback.error(R.string.no_conference_server_found, null);
2496					}
2497					return false;
2498				}
2499				final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2500				final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2501				joinMuc(conversation, new OnConferenceJoined() {
2502					@Override
2503					public void onConferenceJoined(final Conversation conversation) {
2504						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConfigurationPushed() {
2505							@Override
2506							public void onPushSucceeded() {
2507								if (subject != null && !subject.trim().isEmpty()) {
2508									pushSubjectToConference(conversation, subject.trim());
2509								}
2510								for (Jid invite : jids) {
2511									invite(conversation, invite);
2512								}
2513								if (account.countPresences() > 1) {
2514									directInvite(conversation, account.getJid().toBareJid());
2515								}
2516								saveConversationAsBookmark(conversation, subject);
2517								if (callback != null) {
2518									callback.success(conversation);
2519								}
2520							}
2521
2522							@Override
2523							public void onPushFailed() {
2524								archiveConversation(conversation);
2525								if (callback != null) {
2526									callback.error(R.string.conference_creation_failed, conversation);
2527								}
2528							}
2529						});
2530					}
2531				});
2532				return true;
2533			} catch (InvalidJidException e) {
2534				if (callback != null) {
2535					callback.error(R.string.conference_creation_failed, null);
2536				}
2537				return false;
2538			}
2539		} else {
2540			if (callback != null) {
2541				callback.error(R.string.not_connected_try_again, null);
2542			}
2543			return false;
2544		}
2545	}
2546
2547	public void fetchConferenceConfiguration(final Conversation conversation) {
2548		fetchConferenceConfiguration(conversation, null);
2549	}
2550
2551	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2552		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2553		request.setTo(conversation.getJid().toBareJid());
2554		request.query("http://jabber.org/protocol/disco#info");
2555		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2556			@Override
2557			public void onIqPacketReceived(Account account, IqPacket packet) {
2558				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2559				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2560					ArrayList<String> features = new ArrayList<>();
2561					for (Element child : query.getChildren()) {
2562						if (child != null && child.getName().equals("feature")) {
2563							String var = child.getAttribute("var");
2564							if (var != null) {
2565								features.add(var);
2566							}
2567						}
2568					}
2569					Element form = query.findChild("x", "jabber:x:data");
2570					if (form != null) {
2571						conversation.getMucOptions().updateFormData(Data.parse(form));
2572					}
2573					conversation.getMucOptions().updateFeatures(features);
2574					if (callback != null) {
2575						callback.onConferenceConfigurationFetched(conversation);
2576					}
2577					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2578					updateConversationUi();
2579				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2580					if (callback != null) {
2581						callback.onFetchFailed(conversation, packet.getError());
2582					}
2583				}
2584			}
2585		});
2586	}
2587
2588	public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2589		pushNodeConfiguration(account,account.getJid().toBareJid(),node,options,callback);
2590	}
2591
2592	public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2593		sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid,node), new OnIqPacketReceived() {
2594			@Override
2595			public void onIqPacketReceived(Account account, IqPacket packet) {
2596				if (packet.getType() == IqPacket.TYPE.RESULT) {
2597					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub#owner");
2598					Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2599					Element x = configuration == null ? null : configuration.findChild("x","jabber:x:data");
2600					if (x != null) {
2601						Data data = Data.parse(x);
2602						data.submit(options);
2603						sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2604							@Override
2605							public void onIqPacketReceived(Account account, IqPacket packet) {
2606								if (packet.getType() == IqPacket.TYPE.RESULT) {
2607									callback.onPushSucceeded();
2608								} else {
2609									Log.d(Config.LOGTAG,packet.toString());
2610								}
2611							}
2612						});
2613					} else {
2614						callback.onPushFailed();
2615					}
2616				} else {
2617					callback.onPushFailed();
2618				}
2619			}
2620		});
2621	}
2622
2623	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2624		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2625		request.setTo(conversation.getJid().toBareJid());
2626		request.query("http://jabber.org/protocol/muc#owner");
2627		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2628			@Override
2629			public void onIqPacketReceived(Account account, IqPacket packet) {
2630				if (packet.getType() == IqPacket.TYPE.RESULT) {
2631					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2632					data.submit(options);
2633					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2634					set.setTo(conversation.getJid().toBareJid());
2635					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2636					sendIqPacket(account, set, new OnIqPacketReceived() {
2637						@Override
2638						public void onIqPacketReceived(Account account, IqPacket packet) {
2639							if (callback != null) {
2640								if (packet.getType() == IqPacket.TYPE.RESULT) {
2641									callback.onPushSucceeded();
2642								} else {
2643									callback.onPushFailed();
2644								}
2645							}
2646						}
2647					});
2648				} else {
2649					if (callback != null) {
2650						callback.onPushFailed();
2651					}
2652				}
2653			}
2654		});
2655	}
2656
2657	public void pushSubjectToConference(final Conversation conference, final String subject) {
2658		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2659		this.sendMessagePacket(conference.getAccount(), packet);
2660		final MucOptions mucOptions = conference.getMucOptions();
2661		final MucOptions.User self = mucOptions.getSelf();
2662		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2663			Bundle options = new Bundle();
2664			options.putString("muc#roomconfig_persistentroom", "1");
2665			this.pushConferenceConfiguration(conference, options, null);
2666		}
2667	}
2668
2669	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2670		final Jid jid = user.toBareJid();
2671		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2672		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2673			@Override
2674			public void onIqPacketReceived(Account account, IqPacket packet) {
2675				if (packet.getType() == IqPacket.TYPE.RESULT) {
2676					conference.getMucOptions().changeAffiliation(jid, affiliation);
2677					getAvatarService().clear(conference);
2678					callback.onAffiliationChangedSuccessful(jid);
2679				} else {
2680					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2681				}
2682			}
2683		});
2684	}
2685
2686	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2687		List<Jid> jids = new ArrayList<>();
2688		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2689			if (user.getAffiliation() == before && user.getRealJid() != null) {
2690				jids.add(user.getRealJid());
2691			}
2692		}
2693		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2694		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2695	}
2696
2697	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2698		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2699		Log.d(Config.LOGTAG, request.toString());
2700		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2701			@Override
2702			public void onIqPacketReceived(Account account, IqPacket packet) {
2703				Log.d(Config.LOGTAG, packet.toString());
2704				if (packet.getType() == IqPacket.TYPE.RESULT) {
2705					callback.onRoleChangedSuccessful(nick);
2706				} else {
2707					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2708				}
2709			}
2710		});
2711	}
2712
2713	private void disconnect(Account account, boolean force) {
2714		if ((account.getStatus() == Account.State.ONLINE)
2715				|| (account.getStatus() == Account.State.DISABLED)) {
2716			final XmppConnection connection = account.getXmppConnection();
2717			if (!force) {
2718				List<Conversation> conversations = getConversations();
2719				for (Conversation conversation : conversations) {
2720					if (conversation.getAccount() == account) {
2721						if (conversation.getMode() == Conversation.MODE_MULTI) {
2722							leaveMuc(conversation, true);
2723						} else {
2724							if (conversation.endOtrIfNeeded()) {
2725								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2726										+ ": ended otr session with "
2727										+ conversation.getJid());
2728							}
2729						}
2730					}
2731				}
2732				sendOfflinePresence(account);
2733			}
2734			connection.disconnect(force);
2735		}
2736	}
2737
2738	@Override
2739	public IBinder onBind(Intent intent) {
2740		return mBinder;
2741	}
2742
2743	public void updateMessage(Message message) {
2744		databaseBackend.updateMessage(message);
2745		updateConversationUi();
2746	}
2747
2748	public void updateMessage(Message message, String uuid) {
2749		databaseBackend.updateMessage(message, uuid);
2750		updateConversationUi();
2751	}
2752
2753	protected void syncDirtyContacts(Account account) {
2754		for (Contact contact : account.getRoster().getContacts()) {
2755			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2756				pushContactToServer(contact);
2757			}
2758			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2759				deleteContactOnServer(contact);
2760			}
2761		}
2762	}
2763
2764	public void createContact(Contact contact) {
2765		boolean autoGrant = getBooleanPreference("grant_new_contacts", R.bool.grant_new_contacts);
2766		if (autoGrant) {
2767			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2768			contact.setOption(Contact.Options.ASKING);
2769		}
2770		pushContactToServer(contact);
2771	}
2772
2773	public void onOtrSessionEstablished(Conversation conversation) {
2774		final Account account = conversation.getAccount();
2775		final Session otrSession = conversation.getOtrSession();
2776		Log.d(Config.LOGTAG,
2777				account.getJid().toBareJid() + " otr session established with "
2778						+ conversation.getJid() + "/"
2779						+ otrSession.getSessionID().getUserID());
2780		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2781
2782			@Override
2783			public void onMessageFound(Message message) {
2784				SessionID id = otrSession.getSessionID();
2785				try {
2786					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2787				} catch (InvalidJidException e) {
2788					return;
2789				}
2790				if (message.needsUploading()) {
2791					mJingleConnectionManager.createNewConnection(message);
2792				} else {
2793					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2794					if (outPacket != null) {
2795						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2796						message.setStatus(Message.STATUS_SEND);
2797						databaseBackend.updateMessage(message);
2798						sendMessagePacket(account, outPacket);
2799					}
2800				}
2801				updateConversationUi();
2802			}
2803		});
2804	}
2805
2806	public boolean renewSymmetricKey(Conversation conversation) {
2807		Account account = conversation.getAccount();
2808		byte[] symmetricKey = new byte[32];
2809		this.mRandom.nextBytes(symmetricKey);
2810		Session otrSession = conversation.getOtrSession();
2811		if (otrSession != null) {
2812			MessagePacket packet = new MessagePacket();
2813			packet.setType(MessagePacket.TYPE_CHAT);
2814			packet.setFrom(account.getJid());
2815			MessageGenerator.addMessageHints(packet);
2816			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2817					+ otrSession.getSessionID().getUserID());
2818			try {
2819				packet.setBody(otrSession
2820						.transformSending(CryptoHelper.FILETRANSFER
2821								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2822				sendMessagePacket(account, packet);
2823				conversation.setSymmetricKey(symmetricKey);
2824				return true;
2825			} catch (OtrException e) {
2826				return false;
2827			}
2828		}
2829		return false;
2830	}
2831
2832	public void pushContactToServer(final Contact contact) {
2833		contact.resetOption(Contact.Options.DIRTY_DELETE);
2834		contact.setOption(Contact.Options.DIRTY_PUSH);
2835		final Account account = contact.getAccount();
2836		if (account.getStatus() == Account.State.ONLINE) {
2837			final boolean ask = contact.getOption(Contact.Options.ASKING);
2838			final boolean sendUpdates = contact
2839					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2840					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2841			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2842			iq.query(Namespace.ROSTER).addChild(contact.asElement());
2843			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2844			if (sendUpdates) {
2845				sendPresencePacket(account,
2846						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2847			}
2848			if (ask) {
2849				sendPresencePacket(account,
2850						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2851			}
2852		}
2853	}
2854
2855	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2856		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2857		final int size = Config.AVATAR_SIZE;
2858		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2859		if (avatar != null) {
2860			avatar.height = size;
2861			avatar.width = size;
2862			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2863				avatar.type = "image/webp";
2864			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2865				avatar.type = "image/jpeg";
2866			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2867				avatar.type = "image/png";
2868			}
2869			if (!getFileBackend().save(avatar)) {
2870				callback.error(R.string.error_saving_avatar, avatar);
2871				return;
2872			}
2873			publishAvatar(account, avatar, callback);
2874		} else {
2875			callback.error(R.string.error_publish_avatar_converting, null);
2876		}
2877	}
2878
2879	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2880		IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2881		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2882
2883			@Override
2884			public void onIqPacketReceived(Account account, IqPacket result) {
2885				if (result.getType() == IqPacket.TYPE.RESULT) {
2886					final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2887					sendIqPacket(account, packet, new OnIqPacketReceived() {
2888						@Override
2889						public void onIqPacketReceived(Account account, IqPacket result) {
2890							if (result.getType() == IqPacket.TYPE.RESULT) {
2891								if (account.setAvatar(avatar.getFilename())) {
2892									getAvatarService().clear(account);
2893									databaseBackend.updateAccount(account);
2894								}
2895								Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar "+(avatar.size/1024)+"KiB");
2896								if (callback != null) {
2897									callback.success(avatar);
2898								}
2899							} else {
2900								if (callback != null) {
2901									callback.error(R.string.error_publish_avatar_server_reject,avatar);
2902								}
2903							}
2904						}
2905					});
2906				} else {
2907					Element error = result.findChild("error");
2908					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server rejected avatar "+(avatar.size/1024)+"KiB "+(error!=null?error.toString():""));
2909					if (callback != null) {
2910						callback.error(R.string.error_publish_avatar_server_reject, avatar);
2911					}
2912				}
2913			}
2914		});
2915	}
2916
2917	public void republishAvatarIfNeeded(Account account) {
2918		if (account.getAxolotlService().isPepBroken()) {
2919			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2920			return;
2921		}
2922		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2923		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2924
2925			private Avatar parseAvatar(IqPacket packet) {
2926				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2927				if (pubsub != null) {
2928					Element items = pubsub.findChild("items");
2929					if (items != null) {
2930						return Avatar.parseMetadata(items);
2931					}
2932				}
2933				return null;
2934			}
2935
2936			private boolean errorIsItemNotFound(IqPacket packet) {
2937				Element error = packet.findChild("error");
2938				return packet.getType() == IqPacket.TYPE.ERROR
2939						&& error != null
2940						&& error.hasChild("item-not-found");
2941			}
2942
2943			@Override
2944			public void onIqPacketReceived(Account account, IqPacket packet) {
2945				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2946					Avatar serverAvatar = parseAvatar(packet);
2947					if (serverAvatar == null && account.getAvatar() != null) {
2948						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2949						if (avatar != null) {
2950							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2951							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2952						} else {
2953							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2954						}
2955					}
2956				}
2957			}
2958		});
2959	}
2960
2961	public void fetchAvatar(Account account, Avatar avatar) {
2962		fetchAvatar(account, avatar, null);
2963	}
2964
2965	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2966		final String KEY = generateFetchKey(account, avatar);
2967		synchronized (this.mInProgressAvatarFetches) {
2968			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2969				switch (avatar.origin) {
2970					case PEP:
2971						this.mInProgressAvatarFetches.add(KEY);
2972						fetchAvatarPep(account, avatar, callback);
2973						break;
2974					case VCARD:
2975						this.mInProgressAvatarFetches.add(KEY);
2976						fetchAvatarVcard(account, avatar, callback);
2977						break;
2978				}
2979			}
2980		}
2981	}
2982
2983	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2984		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2985		sendIqPacket(account, packet, new OnIqPacketReceived() {
2986
2987			@Override
2988			public void onIqPacketReceived(Account account, IqPacket result) {
2989				synchronized (mInProgressAvatarFetches) {
2990					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2991				}
2992				final String ERROR = account.getJid().toBareJid()
2993						+ ": fetching avatar for " + avatar.owner + " failed ";
2994				if (result.getType() == IqPacket.TYPE.RESULT) {
2995					avatar.image = mIqParser.avatarData(result);
2996					if (avatar.image != null) {
2997						if (getFileBackend().save(avatar)) {
2998							if (account.getJid().toBareJid().equals(avatar.owner)) {
2999								if (account.setAvatar(avatar.getFilename())) {
3000									databaseBackend.updateAccount(account);
3001								}
3002								getAvatarService().clear(account);
3003								updateConversationUi();
3004								updateAccountUi();
3005							} else {
3006								Contact contact = account.getRoster()
3007										.getContact(avatar.owner);
3008								contact.setAvatar(avatar);
3009								getAvatarService().clear(contact);
3010								updateConversationUi();
3011								updateRosterUi();
3012							}
3013							if (callback != null) {
3014								callback.success(avatar);
3015							}
3016							Log.d(Config.LOGTAG, account.getJid().toBareJid()
3017									+ ": successfully fetched pep avatar for " + avatar.owner);
3018							return;
3019						}
3020					} else {
3021
3022						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3023					}
3024				} else {
3025					Element error = result.findChild("error");
3026					if (error == null) {
3027						Log.d(Config.LOGTAG, ERROR + "(server error)");
3028					} else {
3029						Log.d(Config.LOGTAG, ERROR + error.toString());
3030					}
3031				}
3032				if (callback != null) {
3033					callback.error(0, null);
3034				}
3035
3036			}
3037		});
3038	}
3039
3040	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3041		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3042		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3043			@Override
3044			public void onIqPacketReceived(Account account, IqPacket packet) {
3045				synchronized (mInProgressAvatarFetches) {
3046					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
3047				}
3048				if (packet.getType() == IqPacket.TYPE.RESULT) {
3049					Element vCard = packet.findChild("vCard", "vcard-temp");
3050					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3051					String image = photo != null ? photo.findChildContent("BINVAL") : null;
3052					if (image != null) {
3053						avatar.image = image;
3054						if (getFileBackend().save(avatar)) {
3055							Log.d(Config.LOGTAG, account.getJid().toBareJid()
3056									+ ": successfully fetched vCard avatar for " + avatar.owner);
3057							if (avatar.owner.isBareJid()) {
3058								if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3059									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": had no avatar. replacing with vcard");
3060									account.setAvatar(avatar.getFilename());
3061									databaseBackend.updateAccount(account);
3062									getAvatarService().clear(account);
3063									updateAccountUi();
3064								} else {
3065									Contact contact = account.getRoster().getContact(avatar.owner);
3066									contact.setAvatar(avatar);
3067									getAvatarService().clear(contact);
3068									updateRosterUi();
3069								}
3070								updateConversationUi();
3071							} else {
3072								Conversation conversation = find(account, avatar.owner.toBareJid());
3073								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3074									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3075									if (user != null) {
3076										if (user.setAvatar(avatar)) {
3077											getAvatarService().clear(user);
3078											updateConversationUi();
3079											updateMucRosterUi();
3080										}
3081									}
3082								}
3083							}
3084						}
3085					}
3086				}
3087			}
3088		});
3089	}
3090
3091	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3092		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3093		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3094
3095			@Override
3096			public void onIqPacketReceived(Account account, IqPacket packet) {
3097				if (packet.getType() == IqPacket.TYPE.RESULT) {
3098					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
3099					if (pubsub != null) {
3100						Element items = pubsub.findChild("items");
3101						if (items != null) {
3102							Avatar avatar = Avatar.parseMetadata(items);
3103							if (avatar != null) {
3104								avatar.owner = account.getJid().toBareJid();
3105								if (fileBackend.isAvatarCached(avatar)) {
3106									if (account.setAvatar(avatar.getFilename())) {
3107										databaseBackend.updateAccount(account);
3108									}
3109									getAvatarService().clear(account);
3110									callback.success(avatar);
3111								} else {
3112									fetchAvatarPep(account, avatar, callback);
3113								}
3114								return;
3115							}
3116						}
3117					}
3118				}
3119				callback.error(0, null);
3120			}
3121		});
3122	}
3123
3124	public void deleteContactOnServer(Contact contact) {
3125		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3126		contact.resetOption(Contact.Options.DIRTY_PUSH);
3127		contact.setOption(Contact.Options.DIRTY_DELETE);
3128		Account account = contact.getAccount();
3129		if (account.getStatus() == Account.State.ONLINE) {
3130			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3131			Element item = iq.query(Namespace.ROSTER).addChild("item");
3132			item.setAttribute("jid", contact.getJid().toString());
3133			item.setAttribute("subscription", "remove");
3134			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3135		}
3136	}
3137
3138	public void updateConversation(final Conversation conversation) {
3139		mDatabaseExecutor.execute(new Runnable() {
3140			@Override
3141			public void run() {
3142				databaseBackend.updateConversation(conversation);
3143			}
3144		});
3145	}
3146
3147	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3148		synchronized (account) {
3149			XmppConnection connection = account.getXmppConnection();
3150			if (connection == null) {
3151				connection = createConnection(account);
3152				account.setXmppConnection(connection);
3153			}
3154			boolean hasInternet = hasInternetConnection();
3155			if (!account.isOptionSet(Account.OPTION_DISABLED) && hasInternet) {
3156				if (!force) {
3157					disconnect(account, false);
3158				}
3159				Thread thread = new Thread(connection);
3160				connection.setInteractive(interactive);
3161				connection.prepareNewConnection();
3162				connection.interrupt();
3163				thread.start();
3164				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3165			} else {
3166				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3167				account.getRoster().clearPresences();
3168				connection.resetEverything();
3169				final AxolotlService axolotlService = account.getAxolotlService();
3170				if (axolotlService != null) {
3171					axolotlService.resetBrokenness();
3172				}
3173				if (!hasInternet) {
3174					account.setStatus(Account.State.NO_INTERNET);
3175				}
3176			}
3177		}
3178	}
3179
3180	public void reconnectAccountInBackground(final Account account) {
3181		new Thread(new Runnable() {
3182			@Override
3183			public void run() {
3184				reconnectAccount(account, false, true);
3185			}
3186		}).start();
3187	}
3188
3189	public void invite(Conversation conversation, Jid contact) {
3190		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
3191		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3192		sendMessagePacket(conversation.getAccount(), packet);
3193	}
3194
3195	public void directInvite(Conversation conversation, Jid jid) {
3196		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3197		sendMessagePacket(conversation.getAccount(), packet);
3198	}
3199
3200	public void resetSendingToWaiting(Account account) {
3201		for (Conversation conversation : getConversations()) {
3202			if (conversation.getAccount() == account) {
3203				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3204
3205					@Override
3206					public void onMessageFound(Message message) {
3207						markMessage(message, Message.STATUS_WAITING);
3208					}
3209				});
3210			}
3211		}
3212	}
3213
3214	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3215		return markMessage(account, recipient, uuid, status, null);
3216	}
3217
3218	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3219		if (uuid == null) {
3220			return null;
3221		}
3222		for (Conversation conversation : getConversations()) {
3223			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
3224				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3225				if (message != null) {
3226					markMessage(message, status, errorMessage);
3227				}
3228				return message;
3229			}
3230		}
3231		return null;
3232	}
3233
3234	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3235		if (uuid == null) {
3236			return false;
3237		} else {
3238			Message message = conversation.findSentMessageWithUuid(uuid);
3239			if (message != null) {
3240				if (message.getServerMsgId() == null) {
3241					message.setServerMsgId(serverMessageId);
3242				}
3243				markMessage(message, status);
3244				return true;
3245			} else {
3246				return false;
3247			}
3248		}
3249	}
3250
3251	public void markMessage(Message message, int status) {
3252		markMessage(message, status, null);
3253	}
3254
3255
3256	public void markMessage(Message message, int status, String errorMessage) {
3257		if (status == Message.STATUS_SEND_FAILED
3258				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
3259				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
3260			return;
3261		}
3262		message.setErrorMessage(errorMessage);
3263		message.setStatus(status);
3264		databaseBackend.updateMessage(message);
3265		updateConversationUi();
3266	}
3267
3268	private SharedPreferences getPreferences() {
3269		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3270	}
3271
3272	public long getAutomaticMessageDeletionDate() {
3273		final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION,R.integer.automatic_message_deletion);
3274		return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3275	}
3276
3277	public long getLongPreference(String name, @IntegerRes int res) {
3278		long defaultValue = getResources().getInteger(res);
3279		try {
3280			return Long.parseLong(getPreferences().getString(name,String.valueOf(defaultValue)));
3281		} catch (NumberFormatException e) {
3282			return defaultValue;
3283		}
3284	}
3285
3286	public boolean getBooleanPreference(String name, @BoolRes int res) {
3287		return getPreferences().getBoolean(name,getResources().getBoolean(res));
3288	}
3289
3290	public boolean confirmMessages() {
3291		return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3292	}
3293
3294	public boolean allowMessageCorrection() {
3295		return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3296	}
3297
3298	public boolean sendChatStates() {
3299		return getBooleanPreference("chat_states", R.bool.chat_states);
3300	}
3301
3302	private boolean respectAutojoin() {
3303		return getBooleanPreference("autojoin", R.bool.autojoin);
3304	}
3305
3306	public boolean indicateReceived() {
3307		return getBooleanPreference("indicate_received", R.bool.indicate_received);
3308	}
3309
3310	public boolean useTorToConnect() {
3311		return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3312	}
3313
3314	public boolean showExtendedConnectionOptions() {
3315		return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3316	}
3317
3318	public boolean broadcastLastActivity() {
3319		return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3320	}
3321
3322	public int unreadCount() {
3323		int count = 0;
3324		for (Conversation conversation : getConversations()) {
3325			count += conversation.unreadCount();
3326		}
3327		return count;
3328	}
3329
3330
3331	public void showErrorToastInUi(int resId) {
3332		if (mOnShowErrorToast != null) {
3333			mOnShowErrorToast.onShowErrorToast(resId);
3334		}
3335	}
3336
3337	public void updateConversationUi() {
3338		if (mOnConversationUpdate != null) {
3339			mOnConversationUpdate.onConversationUpdate();
3340		}
3341	}
3342
3343	public void updateAccountUi() {
3344		if (mOnAccountUpdate != null) {
3345			mOnAccountUpdate.onAccountUpdate();
3346		}
3347	}
3348
3349	public void updateRosterUi() {
3350		if (mOnRosterUpdate != null) {
3351			mOnRosterUpdate.onRosterUpdate();
3352		}
3353	}
3354
3355	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3356		if (mOnCaptchaRequested != null) {
3357			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3358			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3359					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3360
3361			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3362			return true;
3363		}
3364		return false;
3365	}
3366
3367	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3368		if (mOnUpdateBlocklist != null) {
3369			mOnUpdateBlocklist.OnUpdateBlocklist(status);
3370		}
3371	}
3372
3373	public void updateMucRosterUi() {
3374		if (mOnMucRosterUpdate != null) {
3375			mOnMucRosterUpdate.onMucRosterUpdate();
3376		}
3377	}
3378
3379	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3380		if (mOnKeyStatusUpdated != null) {
3381			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3382		}
3383	}
3384
3385	public Account findAccountByJid(final Jid accountJid) {
3386		for (Account account : this.accounts) {
3387			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3388				return account;
3389			}
3390		}
3391		return null;
3392	}
3393
3394	public Conversation findConversationByUuid(String uuid) {
3395		for (Conversation conversation : getConversations()) {
3396			if (conversation.getUuid().equals(uuid)) {
3397				return conversation;
3398			}
3399		}
3400		return null;
3401	}
3402
3403	public boolean markRead(final Conversation conversation) {
3404		return markRead(conversation,true);
3405	}
3406
3407	public boolean markRead(final Conversation conversation, boolean clear) {
3408		if (clear) {
3409			mNotificationService.clear(conversation);
3410		}
3411		final List<Message> readMessages = conversation.markRead();
3412		if (readMessages.size() > 0) {
3413			Runnable runnable = new Runnable() {
3414				@Override
3415				public void run() {
3416					for (Message message : readMessages) {
3417						databaseBackend.updateMessage(message);
3418					}
3419				}
3420			};
3421			mDatabaseExecutor.execute(runnable);
3422			updateUnreadCountBadge();
3423			return true;
3424		} else {
3425			return false;
3426		}
3427	}
3428
3429	public synchronized void updateUnreadCountBadge() {
3430		int count = unreadCount();
3431		if (unreadCount != count) {
3432			Log.d(Config.LOGTAG, "update unread count to " + count);
3433			if (count > 0) {
3434				ShortcutBadger.applyCount(getApplicationContext(), count);
3435			} else {
3436				ShortcutBadger.removeCount(getApplicationContext());
3437			}
3438			unreadCount = count;
3439		}
3440	}
3441
3442	public void sendReadMarker(final Conversation conversation) {
3443		final Message markable = conversation.getLatestMarkableMessage();
3444		if (this.markRead(conversation)) {
3445			updateConversationUi();
3446		}
3447		if (confirmMessages()
3448				&& markable != null
3449				&& markable.trusted()
3450				&& markable.getRemoteMsgId() != null) {
3451			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3452			Account account = conversation.getAccount();
3453			final Jid to = markable.getCounterpart();
3454			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
3455			this.sendMessagePacket(conversation.getAccount(), packet);
3456		}
3457	}
3458
3459	public SecureRandom getRNG() {
3460		return this.mRandom;
3461	}
3462
3463	public MemorizingTrustManager getMemorizingTrustManager() {
3464		return this.mMemorizingTrustManager;
3465	}
3466
3467	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3468		this.mMemorizingTrustManager = trustManager;
3469	}
3470
3471	public void updateMemorizingTrustmanager() {
3472		final MemorizingTrustManager tm;
3473		final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3474		if (dontTrustSystemCAs) {
3475			tm = new MemorizingTrustManager(getApplicationContext(), null);
3476		} else {
3477			tm = new MemorizingTrustManager(getApplicationContext());
3478		}
3479		setMemorizingTrustManager(tm);
3480	}
3481
3482	public PowerManager getPowerManager() {
3483		return this.pm;
3484	}
3485
3486	public LruCache<String, Bitmap> getBitmapCache() {
3487		return this.mBitmapCache;
3488	}
3489
3490	public void syncRosterToDisk(final Account account) {
3491		Runnable runnable = new Runnable() {
3492
3493			@Override
3494			public void run() {
3495				databaseBackend.writeRoster(account.getRoster());
3496			}
3497		};
3498		mDatabaseExecutor.execute(runnable);
3499
3500	}
3501
3502	public List<String> getKnownHosts() {
3503		final List<String> hosts = new ArrayList<>();
3504		for (final Account account : getAccounts()) {
3505			if (!hosts.contains(account.getServer().toString())) {
3506				hosts.add(account.getServer().toString());
3507			}
3508			for (final Contact contact : account.getRoster().getContacts()) {
3509				if (contact.showInRoster()) {
3510					final String server = contact.getServer().toString();
3511					if (server != null && !hosts.contains(server)) {
3512						hosts.add(server);
3513					}
3514				}
3515			}
3516		}
3517		if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3518			hosts.add(Config.DOMAIN_LOCK);
3519		}
3520		if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3521			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3522		}
3523		return hosts;
3524	}
3525
3526	public List<String> getKnownConferenceHosts() {
3527		final ArrayList<String> mucServers = new ArrayList<>();
3528		for (final Account account : accounts) {
3529			if (account.getXmppConnection() != null) {
3530				final String server = account.getXmppConnection().getMucServer();
3531				if (server != null && !mucServers.contains(server)) {
3532					mucServers.add(server);
3533				}
3534				for(Bookmark bookmark : account.getBookmarks()) {
3535					final Jid jid = bookmark.getJid();
3536					final String s = jid == null ? null : jid.getDomainpart();
3537					if (s != null && !mucServers.contains(s)) {
3538						mucServers.add(s);
3539					}
3540				}
3541			}
3542		}
3543		return mucServers;
3544	}
3545
3546	public void sendMessagePacket(Account account, MessagePacket packet) {
3547		XmppConnection connection = account.getXmppConnection();
3548		if (connection != null) {
3549			connection.sendMessagePacket(packet);
3550		}
3551	}
3552
3553	public void sendPresencePacket(Account account, PresencePacket packet) {
3554		XmppConnection connection = account.getXmppConnection();
3555		if (connection != null) {
3556			connection.sendPresencePacket(packet);
3557		}
3558	}
3559
3560	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3561		final XmppConnection connection = account.getXmppConnection();
3562		if (connection != null) {
3563			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3564			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3565		}
3566	}
3567
3568	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3569		final XmppConnection connection = account.getXmppConnection();
3570		if (connection != null) {
3571			connection.sendIqPacket(packet, callback);
3572		}
3573	}
3574
3575	public void sendPresence(final Account account) {
3576		sendPresence(account, checkListeners() && broadcastLastActivity());
3577	}
3578
3579	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3580		PresencePacket packet;
3581		if (manuallyChangePresence()) {
3582			packet =  mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3583			String message = account.getPresenceStatusMessage();
3584			if (message != null && !message.isEmpty()) {
3585				packet.addChild(new Element("status").setContent(message));
3586			}
3587		} else {
3588			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3589		}
3590		if (mLastActivity > 0 && includeIdleTimestamp) {
3591			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3592			packet.addChild("idle",Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3593		}
3594		sendPresencePacket(account, packet);
3595	}
3596
3597	private void deactivateGracePeriod() {
3598		for(Account account : getAccounts()) {
3599			account.deactivateGracePeriod();
3600		}
3601	}
3602
3603	public void refreshAllPresences() {
3604		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3605		for (Account account : getAccounts()) {
3606			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3607				sendPresence(account, includeIdleTimestamp);
3608			}
3609		}
3610	}
3611
3612	private void refreshAllGcmTokens() {
3613		for(Account account : getAccounts()) {
3614			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3615				mPushManagementService.registerPushTokenOnServer(account);
3616			}
3617		}
3618	}
3619
3620	private void sendOfflinePresence(final Account account) {
3621		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending offline presence");
3622		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3623	}
3624
3625	public MessageGenerator getMessageGenerator() {
3626		return this.mMessageGenerator;
3627	}
3628
3629	public PresenceGenerator getPresenceGenerator() {
3630		return this.mPresenceGenerator;
3631	}
3632
3633	public IqGenerator getIqGenerator() {
3634		return this.mIqGenerator;
3635	}
3636
3637	public IqParser getIqParser() {
3638		return this.mIqParser;
3639	}
3640
3641	public JingleConnectionManager getJingleConnectionManager() {
3642		return this.mJingleConnectionManager;
3643	}
3644
3645	public MessageArchiveService getMessageArchiveService() {
3646		return this.mMessageArchiveService;
3647	}
3648
3649	public List<Contact> findContacts(Jid jid, String accountJid) {
3650		ArrayList<Contact> contacts = new ArrayList<>();
3651		for (Account account : getAccounts()) {
3652			if ((!account.isOptionSet(Account.OPTION_DISABLED) || accountJid != null)
3653					&& (accountJid == null || accountJid.equals(account.getJid().toBareJid().toString()))) {
3654				Contact contact = account.getRoster().getContactFromRoster(jid);
3655				if (contact != null) {
3656					contacts.add(contact);
3657				}
3658			}
3659		}
3660		return contacts;
3661	}
3662
3663	public Conversation findFirstMuc(Jid jid) {
3664		for(Conversation conversation : getConversations()) {
3665			if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3666					&& conversation.getMode() == Conversation.MODE_MULTI) {
3667				return conversation;
3668			}
3669		}
3670		return null;
3671	}
3672
3673	public NotificationService getNotificationService() {
3674		return this.mNotificationService;
3675	}
3676
3677	public HttpConnectionManager getHttpConnectionManager() {
3678		return this.mHttpConnectionManager;
3679	}
3680
3681	public void resendFailedMessages(final Message message) {
3682		final Collection<Message> messages = new ArrayList<>();
3683		Message current = message;
3684		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3685			messages.add(current);
3686			if (current.mergeable(current.next())) {
3687				current = current.next();
3688			} else {
3689				break;
3690			}
3691		}
3692		for (final Message msg : messages) {
3693			msg.setTime(System.currentTimeMillis());
3694			markMessage(msg, Message.STATUS_WAITING);
3695			this.resendMessage(msg, false);
3696		}
3697	}
3698
3699	public void clearConversationHistory(final Conversation conversation) {
3700		final long clearDate;
3701		final String reference;
3702		if (conversation.countMessages() > 0) {
3703			Message latestMessage = conversation.getLatestMessage();
3704			clearDate = latestMessage.getTimeSent() + 1000;
3705			reference = latestMessage.getServerMsgId();
3706		} else {
3707			clearDate = System.currentTimeMillis();
3708			reference = null;
3709		}
3710		conversation.clearMessages();
3711		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3712		conversation.setLastClearHistory(clearDate,reference);
3713		Runnable runnable = new Runnable() {
3714			@Override
3715			public void run() {
3716				databaseBackend.deleteMessagesInConversation(conversation);
3717				databaseBackend.updateConversation(conversation);
3718			}
3719		};
3720		mDatabaseExecutor.execute(runnable);
3721	}
3722
3723	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3724		if (blockable != null && blockable.getBlockedJid() != null) {
3725			final Jid jid = blockable.getBlockedJid();
3726			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3727
3728				@Override
3729				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3730					if (packet.getType() == IqPacket.TYPE.RESULT) {
3731						account.getBlocklist().add(jid);
3732						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3733					}
3734				}
3735			});
3736			if (removeBlockedConversations(blockable.getAccount(),jid)) {
3737				updateConversationUi();
3738				return true;
3739			} else {
3740				return false;
3741			}
3742		} else {
3743			return false;
3744		}
3745	}
3746
3747	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3748		boolean removed = false;
3749		synchronized (this.conversations) {
3750			boolean domainJid = blockedJid.isDomainJid();
3751			for(Conversation conversation : this.conversations) {
3752				boolean jidMatches = (domainJid && blockedJid.getDomainpart().equals(conversation.getJid().getDomainpart()))
3753						|| blockedJid.equals(conversation.getJid().toBareJid());
3754				if (conversation.getAccount() == account
3755						&& conversation.getMode() == Conversation.MODE_SINGLE
3756						&& jidMatches) {
3757					this.conversations.remove(conversation);
3758					markRead(conversation);
3759					conversation.setStatus(Conversation.STATUS_ARCHIVED);
3760					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": archiving conversation "+conversation.getJid().toBareJid()+" because jid was blocked");
3761					updateConversation(conversation);
3762					removed = true;
3763				}
3764			}
3765		}
3766		return removed;
3767	}
3768
3769	public void sendUnblockRequest(final Blockable blockable) {
3770		if (blockable != null && blockable.getJid() != null) {
3771			final Jid jid = blockable.getBlockedJid();
3772			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3773				@Override
3774				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3775					if (packet.getType() == IqPacket.TYPE.RESULT) {
3776						account.getBlocklist().remove(jid);
3777						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3778					}
3779				}
3780			});
3781		}
3782	}
3783
3784	public void publishDisplayName(Account account) {
3785		String displayName = account.getDisplayName();
3786		if (displayName != null && !displayName.isEmpty()) {
3787			IqPacket publish = mIqGenerator.publishNick(displayName);
3788			sendIqPacket(account, publish, new OnIqPacketReceived() {
3789				@Override
3790				public void onIqPacketReceived(Account account, IqPacket packet) {
3791					if (packet.getType() == IqPacket.TYPE.ERROR) {
3792						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3793					}
3794				}
3795			});
3796		}
3797	}
3798
3799	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3800		ServiceDiscoveryResult result = discoCache.get(key);
3801		if (result != null) {
3802			return result;
3803		} else {
3804			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3805			if (result != null) {
3806				discoCache.put(key, result);
3807			}
3808			return result;
3809		}
3810	}
3811
3812	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3813		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3814		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3815		if (disco != null) {
3816			presence.setServiceDiscoveryResult(disco);
3817		} else {
3818			if (!account.inProgressDiscoFetches.contains(key)) {
3819				account.inProgressDiscoFetches.add(key);
3820				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3821				request.setTo(jid);
3822				request.query("http://jabber.org/protocol/disco#info");
3823				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3824				sendIqPacket(account, request, new OnIqPacketReceived() {
3825					@Override
3826					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3827						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3828							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3829							if (presence.getVer().equals(disco.getVer())) {
3830								databaseBackend.insertDiscoveryResult(disco);
3831								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3832							} else {
3833								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3834							}
3835						}
3836						account.inProgressDiscoFetches.remove(key);
3837					}
3838				});
3839			}
3840		}
3841	}
3842
3843	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3844		for(Contact contact : roster.getContacts()) {
3845			for(Presence presence : contact.getPresences().getPresences().values()) {
3846				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3847					presence.setServiceDiscoveryResult(disco);
3848				}
3849			}
3850		}
3851	}
3852
3853	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3854		final boolean legacy = account.getXmppConnection().getFeatures().mamLegacy();
3855		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3856		request.addChild("prefs",legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3857		sendIqPacket(account, request, new OnIqPacketReceived() {
3858			@Override
3859			public void onIqPacketReceived(Account account, IqPacket packet) {
3860				Element prefs = packet.findChild("prefs",legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3861				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3862					callback.onPreferencesFetched(prefs);
3863				} else {
3864					callback.onPreferencesFetchFailed();
3865				}
3866			}
3867		});
3868	}
3869
3870	public PushManagementService getPushManagementService() {
3871		return mPushManagementService;
3872	}
3873
3874	public Account getPendingAccount() {
3875		Account pending = null;
3876		for(Account account : getAccounts()) {
3877			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3878				pending = account;
3879			} else {
3880				return null;
3881			}
3882		}
3883		return pending;
3884	}
3885
3886	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3887		if (!statusMessage.isEmpty()) {
3888			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3889		}
3890		changeStatusReal(account, status, statusMessage, send);
3891	}
3892
3893	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3894		account.setPresenceStatus(status);
3895		account.setPresenceStatusMessage(statusMessage);
3896		databaseBackend.updateAccount(account);
3897		if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3898			sendPresence(account);
3899		}
3900	}
3901
3902	public void changeStatus(Presence.Status status, String statusMessage) {
3903		if (!statusMessage.isEmpty()) {
3904			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3905		}
3906		for(Account account : getAccounts()) {
3907			changeStatusReal(account, status, statusMessage, true);
3908		}
3909	}
3910
3911	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3912		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3913		for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3914			if (!templates.contains(template)) {
3915				templates.add(0, template);
3916			}
3917		}
3918		return templates;
3919	}
3920
3921	public void saveConversationAsBookmark(Conversation conversation, String name) {
3922		Account account = conversation.getAccount();
3923		Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3924		if (!conversation.getJid().isBareJid()) {
3925			bookmark.setNick(conversation.getJid().getResourcepart());
3926		}
3927		if (name != null && !name.trim().isEmpty()) {
3928			bookmark.setBookmarkName(name.trim());
3929		}
3930		bookmark.setAutojoin(getPreferences().getBoolean("autojoin",getResources().getBoolean(R.bool.autojoin)));
3931		account.getBookmarks().add(bookmark);
3932		pushBookmarks(account);
3933		conversation.setBookmark(bookmark);
3934	}
3935
3936	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3937		boolean needsRosterWrite = false;
3938		boolean performedVerification = false;
3939		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3940		for(XmppUri.Fingerprint fp : fingerprints) {
3941			if (fp.type == XmppUri.FingerprintType.OTR) {
3942				performedVerification |= contact.addOtrFingerprint(fp.fingerprint);
3943				needsRosterWrite |= performedVerification;
3944			} else if (fp.type == XmppUri.FingerprintType.OMEMO) {
3945				String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3946				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3947				if (fingerprintStatus != null) {
3948					if (!fingerprintStatus.isVerified()) {
3949						performedVerification = true;
3950						axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3951					}
3952				} else {
3953					axolotlService.preVerifyFingerprint(contact,fingerprint);
3954				}
3955			}
3956		}
3957		if (needsRosterWrite) {
3958			syncRosterToDisk(contact.getAccount());
3959		}
3960		return performedVerification;
3961	}
3962
3963	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3964		final AxolotlService axolotlService = account.getAxolotlService();
3965		boolean verifiedSomething = false;
3966		for(XmppUri.Fingerprint fp : fingerprints) {
3967			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3968				String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3969				Log.d(Config.LOGTAG,"trying to verify own fp="+fingerprint);
3970				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3971				if (fingerprintStatus != null) {
3972					if (!fingerprintStatus.isVerified()) {
3973						axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3974						verifiedSomething = true;
3975					}
3976				} else {
3977					axolotlService.preVerifyFingerprint(account,fingerprint);
3978					verifiedSomething = true;
3979				}
3980			}
3981		}
3982		return verifiedSomething;
3983	}
3984
3985	public boolean blindTrustBeforeVerification() {
3986		return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION,R.bool.btbv);
3987	}
3988
3989	public ShortcutService getShortcutService() {
3990		return mShortcutService;
3991	}
3992
3993	public interface OnMamPreferencesFetched {
3994		void onPreferencesFetched(Element prefs);
3995		void onPreferencesFetchFailed();
3996	}
3997
3998	public void pushMamPreferences(Account account, Element prefs) {
3999		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4000		set.addChild(prefs);
4001		sendIqPacket(account, set, null);
4002	}
4003
4004	public interface OnAccountCreated {
4005		void onAccountCreated(Account account);
4006
4007		void informUser(int r);
4008	}
4009
4010	public interface OnMoreMessagesLoaded {
4011		void onMoreMessagesLoaded(int count, Conversation conversation);
4012
4013		void informUser(int r);
4014	}
4015
4016	public interface OnAccountPasswordChanged {
4017		void onPasswordChangeSucceeded();
4018
4019		void onPasswordChangeFailed();
4020	}
4021
4022	public interface OnAffiliationChanged {
4023		void onAffiliationChangedSuccessful(Jid jid);
4024
4025		void onAffiliationChangeFailed(Jid jid, int resId);
4026	}
4027
4028	public interface OnRoleChanged {
4029		void onRoleChangedSuccessful(String nick);
4030
4031		void onRoleChangeFailed(String nick, int resid);
4032	}
4033
4034	public interface OnConversationUpdate {
4035		void onConversationUpdate();
4036	}
4037
4038	public interface OnAccountUpdate {
4039		void onAccountUpdate();
4040	}
4041
4042	public interface OnCaptchaRequested {
4043		void onCaptchaRequested(Account account,
4044								String id,
4045								Data data,
4046								Bitmap captcha);
4047	}
4048
4049	public interface OnRosterUpdate {
4050		void onRosterUpdate();
4051	}
4052
4053	public interface OnMucRosterUpdate {
4054		void onMucRosterUpdate();
4055	}
4056
4057	public interface OnConferenceConfigurationFetched {
4058		void onConferenceConfigurationFetched(Conversation conversation);
4059
4060		void onFetchFailed(Conversation conversation, Element error);
4061	}
4062
4063	public interface OnConferenceJoined {
4064		void onConferenceJoined(Conversation conversation);
4065	}
4066
4067	public interface OnConfigurationPushed {
4068		void onPushSucceeded();
4069
4070		void onPushFailed();
4071	}
4072
4073	public interface OnShowErrorToast {
4074		void onShowErrorToast(int resId);
4075	}
4076
4077	public class XmppConnectionBinder extends Binder {
4078		public XmppConnectionService getService() {
4079			return XmppConnectionService.this;
4080		}
4081	}
4082}