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