XmppConnectionService.java

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