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