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