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