XmppConnectionService.java

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