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