XmppConnectionService.java

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