XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.annotation.SuppressLint;
   4import android.app.AlarmManager;
   5import android.app.PendingIntent;
   6import android.app.Service;
   7import android.content.Context;
   8import android.content.Intent;
   9import android.content.IntentFilter;
  10import android.content.SharedPreferences;
  11import android.database.ContentObserver;
  12import android.graphics.Bitmap;
  13import android.media.AudioManager;
  14import android.net.ConnectivityManager;
  15import android.net.NetworkInfo;
  16import android.net.Uri;
  17import android.os.Binder;
  18import android.os.Build;
  19import android.os.Bundle;
  20import android.os.FileObserver;
  21import android.os.IBinder;
  22import android.os.Looper;
  23import android.os.PowerManager;
  24import android.os.PowerManager.WakeLock;
  25import android.os.SystemClock;
  26import android.preference.PreferenceManager;
  27import android.provider.ContactsContract;
  28import android.security.KeyChain;
  29import android.util.DisplayMetrics;
  30import android.util.Log;
  31import android.util.LruCache;
  32import android.util.Pair;
  33
  34import net.java.otr4j.OtrException;
  35import net.java.otr4j.session.Session;
  36import net.java.otr4j.session.SessionID;
  37import net.java.otr4j.session.SessionImpl;
  38import net.java.otr4j.session.SessionStatus;
  39
  40import org.openintents.openpgp.IOpenPgpService2;
  41import org.openintents.openpgp.util.OpenPgpApi;
  42import org.openintents.openpgp.util.OpenPgpServiceConnection;
  43
  44import java.math.BigInteger;
  45import java.security.SecureRandom;
  46import java.security.cert.CertificateException;
  47import java.security.cert.X509Certificate;
  48import java.util.ArrayList;
  49import java.util.Arrays;
  50import java.util.Collection;
  51import java.util.Collections;
  52import java.util.Comparator;
  53import java.util.HashMap;
  54import java.util.Hashtable;
  55import java.util.Iterator;
  56import java.util.List;
  57import java.util.Locale;
  58import java.util.Map;
  59import java.util.concurrent.CopyOnWriteArrayList;
  60
  61import de.duenndns.ssl.MemorizingTrustManager;
  62import eu.siacs.conversations.Config;
  63import eu.siacs.conversations.R;
  64import eu.siacs.conversations.crypto.PgpEngine;
  65import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  66import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  67import eu.siacs.conversations.entities.Account;
  68import eu.siacs.conversations.entities.Blockable;
  69import eu.siacs.conversations.entities.Bookmark;
  70import eu.siacs.conversations.entities.Contact;
  71import eu.siacs.conversations.entities.Conversation;
  72import eu.siacs.conversations.entities.Message;
  73import eu.siacs.conversations.entities.MucOptions;
  74import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  75import eu.siacs.conversations.entities.Presence;
  76import eu.siacs.conversations.entities.Presences;
  77import eu.siacs.conversations.entities.Roster;
  78import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  79import eu.siacs.conversations.entities.Transferable;
  80import eu.siacs.conversations.entities.TransferablePlaceholder;
  81import eu.siacs.conversations.generator.IqGenerator;
  82import eu.siacs.conversations.generator.MessageGenerator;
  83import eu.siacs.conversations.generator.PresenceGenerator;
  84import eu.siacs.conversations.http.HttpConnectionManager;
  85import eu.siacs.conversations.parser.IqParser;
  86import eu.siacs.conversations.parser.MessageParser;
  87import eu.siacs.conversations.parser.PresenceParser;
  88import eu.siacs.conversations.persistance.DatabaseBackend;
  89import eu.siacs.conversations.persistance.FileBackend;
  90import eu.siacs.conversations.ui.UiCallback;
  91import eu.siacs.conversations.utils.CryptoHelper;
  92import eu.siacs.conversations.utils.ExceptionHelper;
  93import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
  94import eu.siacs.conversations.utils.PRNGFixes;
  95import eu.siacs.conversations.utils.PhoneHelper;
  96import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  97import eu.siacs.conversations.utils.Xmlns;
  98import eu.siacs.conversations.xml.Element;
  99import eu.siacs.conversations.xmpp.OnBindListener;
 100import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 101import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 102import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 103import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
 104import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 105import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 106import eu.siacs.conversations.xmpp.OnStatusChanged;
 107import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 108import eu.siacs.conversations.xmpp.XmppConnection;
 109import eu.siacs.conversations.xmpp.chatstate.ChatState;
 110import eu.siacs.conversations.xmpp.forms.Data;
 111import eu.siacs.conversations.xmpp.forms.Field;
 112import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 113import eu.siacs.conversations.xmpp.jid.Jid;
 114import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 115import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 116import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 117import eu.siacs.conversations.xmpp.pep.Avatar;
 118import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 119import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 120import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 121import me.leolin.shortcutbadger.ShortcutBadger;
 122
 123public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
 124
 125	public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 126	public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
 127	public static final String ACTION_TRY_AGAIN = "try_again";
 128	public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
 129	private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
 130	private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
 131	private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
 132	private final IBinder mBinder = new XmppConnectionBinder();
 133	private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 134	private final IqGenerator mIqGenerator = new IqGenerator(this);
 135	private final List<String> mInProgressAvatarFetches = new ArrayList<>();
 136	public DatabaseBackend databaseBackend;
 137	private ContentObserver contactObserver = new ContentObserver(null) {
 138		@Override
 139		public void onChange(boolean selfChange) {
 140			super.onChange(selfChange);
 141			Intent intent = new Intent(getApplicationContext(),
 142					XmppConnectionService.class);
 143			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 144			startService(intent);
 145		}
 146	};
 147	private FileBackend fileBackend = new FileBackend(this);
 148	private MemorizingTrustManager mMemorizingTrustManager;
 149	private NotificationService mNotificationService = new NotificationService(
 150			this);
 151	private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 152	private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 153	private IqParser mIqParser = new IqParser(this);
 154	private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
 155		@Override
 156		public void onIqPacketReceived(Account account, IqPacket packet) {
 157			if (packet.getType() != IqPacket.TYPE.RESULT) {
 158				Element error = packet.findChild("error");
 159				String text = error != null ? error.findChildContent("text") : null;
 160				if (text != null) {
 161					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
 162				}
 163			}
 164		}
 165	};
 166	private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 167	private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 168	private List<Account> accounts;
 169	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 170			this);
 171	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
 172
 173		@Override
 174		public void onContactStatusChanged(Contact contact, boolean online) {
 175			Conversation conversation = find(getConversations(), contact);
 176			if (conversation != null) {
 177				if (online) {
 178					conversation.endOtrIfNeeded();
 179					if (contact.getPresences().size() == 1) {
 180						sendUnsentMessages(conversation);
 181					}
 182				} else {
 183					if (contact.getPresences().size() >= 1) {
 184						if (conversation.hasValidOtrSession()) {
 185							String otrResource = conversation.getOtrSession().getSessionID().getUserID();
 186							if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
 187								conversation.endOtrIfNeeded();
 188							}
 189						}
 190					} else {
 191						conversation.endOtrIfNeeded();
 192					}
 193				}
 194			}
 195		}
 196	};
 197	private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 198			this);
 199	private AvatarService mAvatarService = new AvatarService(this);
 200	private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 201	private OnConversationUpdate mOnConversationUpdate = null;
 202	private final FileObserver fileObserver = new FileObserver(
 203			FileBackend.getConversationsImageDirectory()) {
 204
 205		@Override
 206		public void onEvent(int event, String path) {
 207			if (event == FileObserver.DELETE) {
 208				markFileDeleted(path.split("\\.")[0]);
 209			}
 210		}
 211	};
 212	private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 213
 214		@Override
 215		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 216			mJingleConnectionManager.deliverPacket(account, packet);
 217		}
 218	};
 219	private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 220
 221		@Override
 222		public void onMessageAcknowledged(Account account, String uuid) {
 223			for (final Conversation conversation : getConversations()) {
 224				if (conversation.getAccount() == account) {
 225					Message message = conversation.findUnsentMessageWithUuid(uuid);
 226					if (message != null) {
 227						markMessage(message, Message.STATUS_SEND);
 228					}
 229				}
 230			}
 231		}
 232	};
 233	private int convChangedListenerCount = 0;
 234	private OnShowErrorToast mOnShowErrorToast = null;
 235	private int showErrorToastListenerCount = 0;
 236	private int unreadCount = -1;
 237	private OnAccountUpdate mOnAccountUpdate = null;
 238	private OnCaptchaRequested mOnCaptchaRequested = null;
 239	private int accountChangedListenerCount = 0;
 240	private int captchaRequestedListenerCount = 0;
 241	private OnRosterUpdate mOnRosterUpdate = null;
 242	private OnUpdateBlocklist mOnUpdateBlocklist = null;
 243	private int updateBlocklistListenerCount = 0;
 244	private int rosterChangedListenerCount = 0;
 245	private OnMucRosterUpdate mOnMucRosterUpdate = null;
 246	private int mucRosterChangedListenerCount = 0;
 247	private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
 248	private int keyStatusUpdatedListenerCount = 0;
 249	private SecureRandom mRandom;
 250	private LruCache<Pair<String,String>,ServiceDiscoveryResult> discoCache = new LruCache<>(20);
 251	private final OnBindListener mOnBindListener = new OnBindListener() {
 252
 253		@Override
 254		public void onBind(final Account account) {
 255			account.getRoster().clearPresences();
 256			mJingleConnectionManager.cancelInTransmission();
 257			fetchRosterFromServer(account);
 258			fetchBookmarks(account);
 259			sendPresence(account);
 260			mMessageArchiveService.executePendingQueries(account);
 261			connectMultiModeConversations(account);
 262			syncDirtyContacts(account);
 263		}
 264	};
 265	private OnStatusChanged statusListener = new OnStatusChanged() {
 266
 267		@Override
 268		public void onStatusChanged(Account account) {
 269			XmppConnection connection = account.getXmppConnection();
 270			if (mOnAccountUpdate != null) {
 271				mOnAccountUpdate.onAccountUpdate();
 272			}
 273			if (account.getStatus() == Account.State.ONLINE) {
 274				if (connection != null && connection.getFeatures().csi()) {
 275					if (checkListeners()) {
 276						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
 277						connection.sendInactive();
 278					} else {
 279						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
 280						connection.sendActive();
 281					}
 282				}
 283				List<Conversation> conversations = getConversations();
 284				for (Conversation conversation : conversations) {
 285					if (conversation.getAccount() == account) {
 286						conversation.startOtrIfNeeded();
 287						sendUnsentMessages(conversation);
 288					}
 289				}
 290				for (Conversation conversation : account.pendingConferenceLeaves) {
 291					leaveMuc(conversation);
 292				}
 293				account.pendingConferenceLeaves.clear();
 294				for (Conversation conversation : account.pendingConferenceJoins) {
 295					joinMuc(conversation);
 296				}
 297				account.pendingConferenceJoins.clear();
 298				scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 299			} else if (account.getStatus() == Account.State.OFFLINE) {
 300				resetSendingToWaiting(account);
 301				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 302					int timeToReconnect = mRandom.nextInt(20) + 10;
 303					scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 304				}
 305			} else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 306				databaseBackend.updateAccount(account);
 307				reconnectAccount(account, true, false);
 308			} else if ((account.getStatus() != Account.State.CONNECTING)
 309					&& (account.getStatus() != Account.State.NO_INTERNET)) {
 310				if (connection != null) {
 311					int next = connection.getTimeToNextAttempt();
 312					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 313							+ ": error connecting account. try again in "
 314							+ next + "s for the "
 315							+ (connection.getAttempt() + 1) + " time");
 316					scheduleWakeUpCall(next, account.getUuid().hashCode());
 317				}
 318			}
 319			getNotificationService().updateErrorNotification();
 320		}
 321	};
 322	private OpenPgpServiceConnection pgpServiceConnection;
 323	private PgpEngine mPgpEngine = null;
 324	private WakeLock wakeLock;
 325	private PowerManager pm;
 326	private LruCache<String, Bitmap> mBitmapCache;
 327	private Thread mPhoneContactMergerThread;
 328	private EventReceiver mEventReceiver = new EventReceiver();
 329
 330	private boolean mRestoredFromDatabase = false;
 331
 332	private static String generateFetchKey(Account account, final Avatar avatar) {
 333		return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 334	}
 335
 336	public boolean areMessagesInitialized() {
 337		return this.mRestoredFromDatabase;
 338	}
 339
 340	public PgpEngine getPgpEngine() {
 341		if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 342			if (this.mPgpEngine == null) {
 343				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 344						getApplicationContext(),
 345						pgpServiceConnection.getService()), this);
 346			}
 347			return mPgpEngine;
 348		} else {
 349			return null;
 350		}
 351
 352	}
 353
 354	public FileBackend getFileBackend() {
 355		return this.fileBackend;
 356	}
 357
 358	public AvatarService getAvatarService() {
 359		return this.mAvatarService;
 360	}
 361
 362	public void attachLocationToConversation(final Conversation conversation,
 363											 final Uri uri,
 364											 final UiCallback<Message> callback) {
 365		int encryption = conversation.getNextEncryption();
 366		if (encryption == Message.ENCRYPTION_PGP) {
 367			encryption = Message.ENCRYPTION_DECRYPTED;
 368		}
 369		Message message = new Message(conversation, uri.toString(), encryption);
 370		if (conversation.getNextCounterpart() != null) {
 371			message.setCounterpart(conversation.getNextCounterpart());
 372		}
 373		if (encryption == Message.ENCRYPTION_DECRYPTED) {
 374			getPgpEngine().encrypt(message, callback);
 375		} else {
 376			callback.success(message);
 377		}
 378	}
 379
 380	public void attachFileToConversation(final Conversation conversation,
 381										 final Uri uri,
 382										 final UiCallback<Message> callback) {
 383		final Message message;
 384		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 385			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 386		} else {
 387			message = new Message(conversation, "", conversation.getNextEncryption());
 388		}
 389		message.setCounterpart(conversation.getNextCounterpart());
 390		message.setType(Message.TYPE_FILE);
 391		String path = getFileBackend().getOriginalPath(uri);
 392		if (path != null) {
 393			message.setRelativeFilePath(path);
 394			getFileBackend().updateFileParams(message);
 395			if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 396				getPgpEngine().encrypt(message, callback);
 397			} else {
 398				callback.success(message);
 399			}
 400		} else {
 401			mFileAddingExecutor.execute(new Runnable() {
 402				@Override
 403				public void run() {
 404					try {
 405						getFileBackend().copyFileToPrivateStorage(message, uri);
 406						getFileBackend().updateFileParams(message);
 407						if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 408							getPgpEngine().encrypt(message, callback);
 409						} else {
 410							callback.success(message);
 411						}
 412					} catch (FileBackend.FileCopyException e) {
 413						callback.error(e.getResId(), message);
 414					}
 415				}
 416			});
 417		}
 418	}
 419
 420	public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 421		final String compressPictures = getCompressPicturesPreference();
 422		if ("never".equals(compressPictures)
 423				|| ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))) {
 424			Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+ ": not compressing picture. sending as file");
 425			attachFileToConversation(conversation, uri, callback);
 426			return;
 427		}
 428		final Message message;
 429		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 430			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 431		} else {
 432			message = new Message(conversation, "", conversation.getNextEncryption());
 433		}
 434		message.setCounterpart(conversation.getNextCounterpart());
 435		message.setType(Message.TYPE_IMAGE);
 436		mFileAddingExecutor.execute(new Runnable() {
 437
 438			@Override
 439			public void run() {
 440				try {
 441					getFileBackend().copyImageToPrivateStorage(message, uri);
 442					if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 443						getPgpEngine().encrypt(message, callback);
 444					} else {
 445						callback.success(message);
 446					}
 447				} catch (final FileBackend.FileCopyException e) {
 448					callback.error(e.getResId(), message);
 449				}
 450			}
 451		});
 452	}
 453
 454	public Conversation find(Bookmark bookmark) {
 455		return find(bookmark.getAccount(), bookmark.getJid());
 456	}
 457
 458	public Conversation find(final Account account, final Jid jid) {
 459		return find(getConversations(), account, jid);
 460	}
 461
 462	@Override
 463	public int onStartCommand(Intent intent, int flags, int startId) {
 464		final String action = intent == null ? null : intent.getAction();
 465		boolean interactive = false;
 466		if (action != null) {
 467			switch (action) {
 468				case ConnectivityManager.CONNECTIVITY_ACTION:
 469					if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 470						resetAllAttemptCounts(true);
 471					}
 472					break;
 473				case ACTION_MERGE_PHONE_CONTACTS:
 474					if (mRestoredFromDatabase) {
 475						loadPhoneContacts();
 476					}
 477					return START_STICKY;
 478				case Intent.ACTION_SHUTDOWN:
 479					logoutAndSave();
 480					return START_NOT_STICKY;
 481				case ACTION_CLEAR_NOTIFICATION:
 482					mNotificationService.clear();
 483					break;
 484				case ACTION_DISABLE_FOREGROUND:
 485					getPreferences().edit().putBoolean("keep_foreground_service", false).commit();
 486					toggleForegroundService();
 487					break;
 488				case ACTION_TRY_AGAIN:
 489					resetAllAttemptCounts(false);
 490					interactive = true;
 491					break;
 492				case ACTION_DISABLE_ACCOUNT:
 493					try {
 494						String jid = intent.getStringExtra("account");
 495						Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
 496						if (account != null) {
 497							account.setOption(Account.OPTION_DISABLED, true);
 498							updateAccount(account);
 499						}
 500					} catch (final InvalidJidException ignored) {
 501						break;
 502					}
 503					break;
 504				case AudioManager.RINGER_MODE_CHANGED_ACTION:
 505					if (xaOnSilentMode()) {
 506						refreshAllPresences();
 507					}
 508					break;
 509				case Intent.ACTION_SCREEN_OFF:
 510				case Intent.ACTION_SCREEN_ON:
 511					if (awayWhenScreenOff()) {
 512						refreshAllPresences();
 513					}
 514					break;
 515			}
 516		}
 517		this.wakeLock.acquire();
 518
 519		for (Account account : accounts) {
 520			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 521				if (!hasInternetConnection()) {
 522					account.setStatus(Account.State.NO_INTERNET);
 523					if (statusListener != null) {
 524						statusListener.onStatusChanged(account);
 525					}
 526				} else {
 527					if (account.getStatus() == Account.State.NO_INTERNET) {
 528						account.setStatus(Account.State.OFFLINE);
 529						if (statusListener != null) {
 530							statusListener.onStatusChanged(account);
 531						}
 532					}
 533					if (account.getStatus() == Account.State.ONLINE) {
 534						long lastReceived = account.getXmppConnection().getLastPacketReceived();
 535						long lastSent = account.getXmppConnection().getLastPingSent();
 536						long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 537						long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 538						long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
 539						if (lastSent > lastReceived) {
 540							if (pingTimeoutIn < 0) {
 541								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
 542								this.reconnectAccount(account, true, interactive);
 543							} else {
 544								int secs = (int) (pingTimeoutIn / 1000);
 545								this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
 546							}
 547						} else if (msToNextPing <= 0) {
 548							account.getXmppConnection().sendPing();
 549							Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping");
 550							this.scheduleWakeUpCall(Config.PING_TIMEOUT, account.getUuid().hashCode());
 551						} else {
 552							this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 553						}
 554					} else if (account.getStatus() == Account.State.OFFLINE) {
 555						reconnectAccount(account, true, interactive);
 556					} else if (account.getStatus() == Account.State.CONNECTING) {
 557						long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
 558						long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
 559						long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
 560						long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
 561						if (timeout < 0) {
 562							Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
 563							reconnectAccount(account, true, interactive);
 564						} else if (discoTimeout < 0) {
 565							account.getXmppConnection().sendDiscoTimeout();
 566							scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
 567						} else {
 568							scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
 569						}
 570					} else {
 571						if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 572							reconnectAccount(account, true, interactive);
 573						}
 574					}
 575
 576				}
 577				if (mOnAccountUpdate != null) {
 578					mOnAccountUpdate.onAccountUpdate();
 579				}
 580			}
 581		}
 582		if (wakeLock.isHeld()) {
 583			try {
 584				wakeLock.release();
 585			} catch (final RuntimeException ignored) {
 586			}
 587		}
 588		return START_STICKY;
 589	}
 590
 591	private boolean xaOnSilentMode() {
 592		return getPreferences().getBoolean("xa_on_silent_mode", false);
 593	}
 594
 595	private boolean awayWhenScreenOff() {
 596		return getPreferences().getBoolean("away_when_screen_off", false);
 597	}
 598
 599	private String getCompressPicturesPreference() {
 600		return getPreferences().getString("picture_compression", "auto");
 601	}
 602
 603	private Presence.Status getTargetPresence() {
 604		if (xaOnSilentMode() && isPhoneSilenced()) {
 605			return Presence.Status.XA;
 606		} else if (awayWhenScreenOff() && !isInteractive()) {
 607			return Presence.Status.AWAY;
 608		} else {
 609			return Presence.Status.ONLINE;
 610		}
 611	}
 612
 613	@SuppressLint("NewApi")
 614	@SuppressWarnings("deprecation")
 615	public boolean isInteractive() {
 616		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 617
 618		final boolean isScreenOn;
 619		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 620			isScreenOn = pm.isScreenOn();
 621		} else {
 622			isScreenOn = pm.isInteractive();
 623		}
 624		return isScreenOn;
 625	}
 626
 627	private boolean isPhoneSilenced() {
 628		AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
 629		return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
 630	}
 631
 632	private void resetAllAttemptCounts(boolean reallyAll) {
 633		Log.d(Config.LOGTAG, "resetting all attepmt counts");
 634		for (Account account : accounts) {
 635			if (account.hasErrorStatus() || reallyAll) {
 636				final XmppConnection connection = account.getXmppConnection();
 637				if (connection != null) {
 638					connection.resetAttemptCount();
 639				}
 640			}
 641		}
 642	}
 643
 644	public boolean hasInternetConnection() {
 645		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 646				.getSystemService(Context.CONNECTIVITY_SERVICE);
 647		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 648		return activeNetwork != null && activeNetwork.isConnected();
 649	}
 650
 651	@SuppressLint("TrulyRandom")
 652	@Override
 653	public void onCreate() {
 654		ExceptionHelper.init(getApplicationContext());
 655		PRNGFixes.apply();
 656		this.mRandom = new SecureRandom();
 657		updateMemorizingTrustmanager();
 658		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 659		final int cacheSize = maxMemory / 8;
 660		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 661			@Override
 662			protected int sizeOf(final String key, final Bitmap bitmap) {
 663				return bitmap.getByteCount() / 1024;
 664			}
 665		};
 666
 667		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 668		this.accounts = databaseBackend.getAccounts();
 669
 670		restoreFromDatabase();
 671
 672		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 673		this.fileObserver.startWatching();
 674
 675		this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
 676			@Override
 677			public void onBound(IOpenPgpService2 service) {
 678				for (Account account : accounts) {
 679					if (account.getPgpDecryptionService() != null) {
 680						account.getPgpDecryptionService().onOpenPgpServiceBound();
 681					}
 682				}
 683			}
 684
 685			@Override
 686			public void onError(Exception e) { }
 687		});
 688		this.pgpServiceConnection.bindToService();
 689
 690		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 691		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
 692		toggleForegroundService();
 693		updateUnreadCountBadge();
 694		toggleScreenEventReceiver();
 695	}
 696
 697	@Override
 698	public void onTrimMemory(int level) {
 699		super.onTrimMemory(level);
 700		if (level >= TRIM_MEMORY_COMPLETE) {
 701			Log.d(Config.LOGTAG, "clear cache due to low memory");
 702			getBitmapCache().evictAll();
 703		}
 704	}
 705
 706	@Override
 707	public void onDestroy() {
 708		try {
 709			unregisterReceiver(this.mEventReceiver);
 710		} catch (IllegalArgumentException e) {
 711			//ignored
 712		}
 713		super.onDestroy();
 714	}
 715
 716	public void toggleScreenEventReceiver() {
 717		if (awayWhenScreenOff()) {
 718			final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
 719			filter.addAction(Intent.ACTION_SCREEN_OFF);
 720			registerReceiver(this.mEventReceiver, filter);
 721		} else {
 722			try {
 723				unregisterReceiver(this.mEventReceiver);
 724			} catch (IllegalArgumentException e) {
 725				//ignored
 726			}
 727		}
 728	}
 729
 730	public void toggleForegroundService() {
 731		if (getPreferences().getBoolean("keep_foreground_service", false)) {
 732			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 733		} else {
 734			stopForeground(true);
 735		}
 736	}
 737
 738	@Override
 739	public void onTaskRemoved(final Intent rootIntent) {
 740		super.onTaskRemoved(rootIntent);
 741		if (!getPreferences().getBoolean("keep_foreground_service", false)) {
 742			this.logoutAndSave();
 743		}
 744	}
 745
 746	private void logoutAndSave() {
 747		for (final Account account : accounts) {
 748			databaseBackend.writeRoster(account.getRoster());
 749			if (account.getXmppConnection() != null) {
 750				new Thread(new Runnable() {
 751					@Override
 752					public void run() {
 753						disconnect(account, false);
 754					}
 755				}).start();
 756
 757			}
 758		}
 759		Context context = getApplicationContext();
 760		AlarmManager alarmManager = (AlarmManager) context
 761				.getSystemService(Context.ALARM_SERVICE);
 762		Intent intent = new Intent(context, EventReceiver.class);
 763		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 764		Log.d(Config.LOGTAG, "good bye");
 765		stopSelf();
 766	}
 767
 768	public void scheduleWakeUpCall(int seconds, int requestCode) {
 769		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
 770
 771		Context context = getApplicationContext();
 772		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 773
 774		Intent intent = new Intent(context, EventReceiver.class);
 775		intent.setAction("ping");
 776		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
 777		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 778	}
 779
 780	public XmppConnection createConnection(final Account account) {
 781		final SharedPreferences sharedPref = getPreferences();
 782		account.setResource(sharedPref.getString("resource", "mobile")
 783				.toLowerCase(Locale.getDefault()));
 784		final XmppConnection connection = new XmppConnection(account, this);
 785		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 786		connection.setOnStatusChangedListener(this.statusListener);
 787		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 788		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 789		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 790		connection.setOnBindListener(this.mOnBindListener);
 791		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 792		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 793		AxolotlService axolotlService = account.getAxolotlService();
 794		if (axolotlService != null) {
 795			connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
 796		}
 797		return connection;
 798	}
 799
 800	public void sendChatState(Conversation conversation) {
 801		if (sendChatStates()) {
 802			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
 803			sendMessagePacket(conversation.getAccount(), packet);
 804		}
 805	}
 806
 807	private void sendFileMessage(final Message message, final boolean delay) {
 808		Log.d(Config.LOGTAG, "send file message");
 809		final Account account = message.getConversation().getAccount();
 810		final XmppConnection connection = account.getXmppConnection();
 811		if (connection != null && connection.getFeatures().httpUpload()) {
 812			mHttpConnectionManager.createNewUploadConnection(message, delay);
 813		} else {
 814			mJingleConnectionManager.createNewConnection(message);
 815		}
 816	}
 817
 818	public void sendMessage(final Message message) {
 819		sendMessage(message, false, false);
 820	}
 821
 822	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
 823		final Account account = message.getConversation().getAccount();
 824		final Conversation conversation = message.getConversation();
 825		account.deactivateGracePeriod();
 826		MessagePacket packet = null;
 827		final boolean addToConversation = conversation.getMode() != Conversation.MODE_MULTI
 828				|| account.getServerIdentity() != XmppConnection.Identity.SLACK;
 829		boolean saveInDb = addToConversation;
 830		message.setStatus(Message.STATUS_WAITING);
 831
 832		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
 833			message.getConversation().endOtrIfNeeded();
 834			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
 835					new Conversation.OnMessageFound() {
 836						@Override
 837						public void onMessageFound(Message message) {
 838							markMessage(message, Message.STATUS_SEND_FAILED);
 839						}
 840					});
 841		}
 842
 843		if (account.isOnlineAndConnected()) {
 844			switch (message.getEncryption()) {
 845				case Message.ENCRYPTION_NONE:
 846					if (message.needsUploading()) {
 847						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 848							this.sendFileMessage(message, delay);
 849						} else {
 850							break;
 851						}
 852					} else {
 853						packet = mMessageGenerator.generateChat(message);
 854					}
 855					break;
 856				case Message.ENCRYPTION_PGP:
 857				case Message.ENCRYPTION_DECRYPTED:
 858					if (message.needsUploading()) {
 859						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 860							this.sendFileMessage(message, delay);
 861						} else {
 862							break;
 863						}
 864					} else {
 865						packet = mMessageGenerator.generatePgpChat(message);
 866					}
 867					break;
 868				case Message.ENCRYPTION_OTR:
 869					SessionImpl otrSession = conversation.getOtrSession();
 870					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
 871						try {
 872							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
 873						} catch (InvalidJidException e) {
 874							break;
 875						}
 876						if (message.needsUploading()) {
 877							mJingleConnectionManager.createNewConnection(message);
 878						} else {
 879							packet = mMessageGenerator.generateOtrChat(message);
 880						}
 881					} else if (otrSession == null) {
 882						if (message.fixCounterpart()) {
 883							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
 884						} else {
 885							break;
 886						}
 887					}
 888					break;
 889				case Message.ENCRYPTION_AXOLOTL:
 890					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 891					if (message.needsUploading()) {
 892						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 893							this.sendFileMessage(message, delay);
 894						} else {
 895							break;
 896						}
 897					} else {
 898						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
 899						if (axolotlMessage == null) {
 900							account.getAxolotlService().preparePayloadMessage(message, delay);
 901						} else {
 902							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
 903						}
 904					}
 905					break;
 906
 907			}
 908			if (packet != null) {
 909				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 910					message.setStatus(Message.STATUS_UNSEND);
 911				} else {
 912					message.setStatus(Message.STATUS_SEND);
 913				}
 914			}
 915		} else {
 916			switch (message.getEncryption()) {
 917				case Message.ENCRYPTION_DECRYPTED:
 918					if (!message.needsUploading()) {
 919						String pgpBody = message.getEncryptedBody();
 920						String decryptedBody = message.getBody();
 921						message.setBody(pgpBody);
 922						message.setEncryption(Message.ENCRYPTION_PGP);
 923						databaseBackend.createMessage(message);
 924						saveInDb = false;
 925						message.setBody(decryptedBody);
 926						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 927					}
 928					break;
 929				case Message.ENCRYPTION_OTR:
 930					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
 931						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
 932					}
 933					break;
 934				case Message.ENCRYPTION_AXOLOTL:
 935					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 936					break;
 937			}
 938		}
 939
 940		if (resend) {
 941			if (packet != null && addToConversation) {
 942				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 943					markMessage(message, Message.STATUS_UNSEND);
 944				} else {
 945					markMessage(message, Message.STATUS_SEND);
 946				}
 947			}
 948		} else {
 949			if (addToConversation) {
 950				conversation.add(message);
 951			}
 952			if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
 953				databaseBackend.createMessage(message);
 954			}
 955			updateConversationUi();
 956		}
 957		if (packet != null) {
 958			if (delay) {
 959				mMessageGenerator.addDelay(packet, message.getTimeSent());
 960			}
 961			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 962				if (this.sendChatStates()) {
 963					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
 964				}
 965			}
 966			sendMessagePacket(account, packet);
 967		}
 968	}
 969
 970	private void sendUnsentMessages(final Conversation conversation) {
 971		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 972
 973			@Override
 974			public void onMessageFound(Message message) {
 975				resendMessage(message, true);
 976			}
 977		});
 978	}
 979
 980	public void resendMessage(final Message message, final boolean delay) {
 981		sendMessage(message, true, delay);
 982	}
 983
 984	public void fetchRosterFromServer(final Account account) {
 985		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 986		if (!"".equals(account.getRosterVersion())) {
 987			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 988					+ ": fetching roster version " + account.getRosterVersion());
 989		} else {
 990			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 991		}
 992		iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
 993		sendIqPacket(account, iqPacket, mIqParser);
 994	}
 995
 996	public void fetchBookmarks(final Account account) {
 997		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 998		final Element query = iqPacket.query("jabber:iq:private");
 999		query.addChild("storage", "storage:bookmarks");
1000		final OnIqPacketReceived callback = new OnIqPacketReceived() {
1001
1002			@Override
1003			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1004				if (packet.getType() == IqPacket.TYPE.RESULT) {
1005					final Element query = packet.query();
1006					final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1007					final Element storage = query.findChild("storage", "storage:bookmarks");
1008					final boolean autojoin = respectAutojoin();
1009					if (storage != null) {
1010						for (final Element item : storage.getChildren()) {
1011							if (item.getName().equals("conference")) {
1012								final Bookmark bookmark = Bookmark.parse(item, account);
1013								Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1014								if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1015									bookmark.setBookmarkName(old.getBookmarkName());
1016								}
1017								Conversation conversation = find(bookmark);
1018								if (conversation != null) {
1019									conversation.setBookmark(bookmark);
1020								} else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1021									conversation = findOrCreateConversation(
1022											account, bookmark.getJid(), true);
1023									conversation.setBookmark(bookmark);
1024									joinMuc(conversation);
1025								}
1026							}
1027						}
1028					}
1029					account.setBookmarks(new ArrayList<>(bookmarks.values()));
1030				} else {
1031					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1032				}
1033			}
1034		};
1035		sendIqPacket(account, iqPacket, callback);
1036	}
1037
1038	public void pushBookmarks(Account account) {
1039		Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1040		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1041		Element query = iqPacket.query("jabber:iq:private");
1042		Element storage = query.addChild("storage", "storage:bookmarks");
1043		for (Bookmark bookmark : account.getBookmarks()) {
1044			storage.addChild(bookmark);
1045		}
1046		sendIqPacket(account, iqPacket, mDefaultIqHandler);
1047	}
1048
1049	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
1050		if (mPhoneContactMergerThread != null) {
1051			mPhoneContactMergerThread.interrupt();
1052		}
1053		mPhoneContactMergerThread = new Thread(new Runnable() {
1054			@Override
1055			public void run() {
1056				Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1057				for (Account account : accounts) {
1058					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1059					for (Bundle phoneContact : phoneContacts) {
1060						if (Thread.interrupted()) {
1061							Log.d(Config.LOGTAG, "interrupted merging phone contacts");
1062							return;
1063						}
1064						Jid jid;
1065						try {
1066							jid = Jid.fromString(phoneContact.getString("jid"));
1067						} catch (final InvalidJidException e) {
1068							continue;
1069						}
1070						final Contact contact = account.getRoster().getContact(jid);
1071						String systemAccount = phoneContact.getInt("phoneid")
1072								+ "#"
1073								+ phoneContact.getString("lookup");
1074						contact.setSystemAccount(systemAccount);
1075						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1076							getAvatarService().clear(contact);
1077						}
1078						contact.setSystemName(phoneContact.getString("displayname"));
1079						withSystemAccounts.remove(contact);
1080					}
1081					for (Contact contact : withSystemAccounts) {
1082						contact.setSystemAccount(null);
1083						contact.setSystemName(null);
1084						if (contact.setPhotoUri(null)) {
1085							getAvatarService().clear(contact);
1086						}
1087					}
1088				}
1089				Log.d(Config.LOGTAG, "finished merging phone contacts");
1090				updateAccountUi();
1091			}
1092		});
1093		mPhoneContactMergerThread.start();
1094	}
1095
1096	private void restoreFromDatabase() {
1097		synchronized (this.conversations) {
1098			final Map<String, Account> accountLookupTable = new Hashtable<>();
1099			for (Account account : this.accounts) {
1100				accountLookupTable.put(account.getUuid(), account);
1101			}
1102			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1103			for (Conversation conversation : this.conversations) {
1104				Account account = accountLookupTable.get(conversation.getAccountUuid());
1105				conversation.setAccount(account);
1106			}
1107			Runnable runnable = new Runnable() {
1108				@Override
1109				public void run() {
1110					Log.d(Config.LOGTAG, "restoring roster");
1111					for (Account account : accounts) {
1112						databaseBackend.readRoster(account.getRoster());
1113						account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1114					}
1115					getBitmapCache().evictAll();
1116					Looper.prepare();
1117					loadPhoneContacts();
1118					Log.d(Config.LOGTAG, "restoring messages");
1119					for (Conversation conversation : conversations) {
1120						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1121						checkDeletedFiles(conversation);
1122						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1123							@Override
1124							public void onMessageFound(Message message) {
1125								mNotificationService.pushFromBacklog(message);
1126							}
1127						});
1128					}
1129					mNotificationService.finishBacklog(false);
1130					mRestoredFromDatabase = true;
1131					Log.d(Config.LOGTAG, "restored all messages");
1132					updateConversationUi();
1133				}
1134			};
1135			mDatabaseExecutor.execute(runnable);
1136		}
1137	}
1138
1139	public void loadPhoneContacts() {
1140		PhoneHelper.loadPhoneContacts(getApplicationContext(),
1141				new CopyOnWriteArrayList<Bundle>(),
1142				XmppConnectionService.this);
1143	}
1144
1145	public List<Conversation> getConversations() {
1146		return this.conversations;
1147	}
1148
1149	private void checkDeletedFiles(Conversation conversation) {
1150		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1151
1152			@Override
1153			public void onMessageFound(Message message) {
1154				if (!getFileBackend().isFileAvailable(message)) {
1155					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1156					final int s = message.getStatus();
1157					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1158						markMessage(message, Message.STATUS_SEND_FAILED);
1159					}
1160				}
1161			}
1162		});
1163	}
1164
1165	private void markFileDeleted(String uuid) {
1166		for (Conversation conversation : getConversations()) {
1167			Message message = conversation.findMessageWithFileAndUuid(uuid);
1168			if (message != null) {
1169				if (!getFileBackend().isFileAvailable(message)) {
1170					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1171					final int s = message.getStatus();
1172					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1173						markMessage(message, Message.STATUS_SEND_FAILED);
1174					} else {
1175						updateConversationUi();
1176					}
1177				}
1178				return;
1179			}
1180		}
1181	}
1182
1183	public void populateWithOrderedConversations(final List<Conversation> list) {
1184		populateWithOrderedConversations(list, true);
1185	}
1186
1187	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1188		list.clear();
1189		if (includeNoFileUpload) {
1190			list.addAll(getConversations());
1191		} else {
1192			for (Conversation conversation : getConversations()) {
1193				if (conversation.getMode() == Conversation.MODE_SINGLE
1194						|| conversation.getAccount().httpUploadAvailable()) {
1195					list.add(conversation);
1196				}
1197			}
1198		}
1199		Collections.sort(list, new Comparator<Conversation>() {
1200			@Override
1201			public int compare(Conversation lhs, Conversation rhs) {
1202				Message left = lhs.getLatestMessage();
1203				Message right = rhs.getLatestMessage();
1204				if (left.getTimeSent() > right.getTimeSent()) {
1205					return -1;
1206				} else if (left.getTimeSent() < right.getTimeSent()) {
1207					return 1;
1208				} else {
1209					return 0;
1210				}
1211			}
1212		});
1213	}
1214
1215	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1216		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1217			return;
1218		} else if (timestamp == 0) {
1219			return;
1220		}
1221		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1222		Runnable runnable = new Runnable() {
1223			@Override
1224			public void run() {
1225				final Account account = conversation.getAccount();
1226				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1227				if (messages.size() > 0) {
1228					conversation.addAll(0, messages);
1229					checkDeletedFiles(conversation);
1230					callback.onMoreMessagesLoaded(messages.size(), conversation);
1231				} else if (conversation.hasMessagesLeftOnServer()
1232						&& account.isOnlineAndConnected()
1233						&& conversation.getLastClearHistory() == 0) {
1234					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1235							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1236						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1237						if (query != null) {
1238							query.setCallback(callback);
1239						}
1240						callback.informUser(R.string.fetching_history_from_server);
1241					}
1242				}
1243			}
1244		};
1245		mDatabaseExecutor.execute(runnable);
1246	}
1247
1248	public List<Account> getAccounts() {
1249		return this.accounts;
1250	}
1251
1252	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1253		for (final Conversation conversation : haystack) {
1254			if (conversation.getContact() == contact) {
1255				return conversation;
1256			}
1257		}
1258		return null;
1259	}
1260
1261	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1262		if (jid == null) {
1263			return null;
1264		}
1265		for (final Conversation conversation : haystack) {
1266			if ((account == null || conversation.getAccount() == account)
1267					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1268				return conversation;
1269			}
1270		}
1271		return null;
1272	}
1273
1274	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1275		return this.findOrCreateConversation(account, jid, muc, null);
1276	}
1277
1278	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1279		synchronized (this.conversations) {
1280			Conversation conversation = find(account, jid);
1281			if (conversation != null) {
1282				return conversation;
1283			}
1284			conversation = databaseBackend.findConversation(account, jid);
1285			if (conversation != null) {
1286				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1287				conversation.setAccount(account);
1288				if (muc) {
1289					conversation.setMode(Conversation.MODE_MULTI);
1290					conversation.setContactJid(jid);
1291				} else {
1292					conversation.setMode(Conversation.MODE_SINGLE);
1293					conversation.setContactJid(jid.toBareJid());
1294				}
1295				conversation.setNextEncryption(-1);
1296				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1297				this.databaseBackend.updateConversation(conversation);
1298			} else {
1299				String conversationName;
1300				Contact contact = account.getRoster().getContact(jid);
1301				if (contact != null) {
1302					conversationName = contact.getDisplayName();
1303				} else {
1304					conversationName = jid.getLocalpart();
1305				}
1306				if (muc) {
1307					conversation = new Conversation(conversationName, account, jid,
1308							Conversation.MODE_MULTI);
1309				} else {
1310					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1311							Conversation.MODE_SINGLE);
1312				}
1313				this.databaseBackend.createConversation(conversation);
1314			}
1315			if (account.getXmppConnection() != null
1316					&& account.getXmppConnection().getFeatures().mam()
1317					&& !muc) {
1318				if (query == null) {
1319					this.mMessageArchiveService.query(conversation);
1320				} else {
1321					if (query.getConversation() == null) {
1322						this.mMessageArchiveService.query(conversation, query.getStart());
1323					}
1324				}
1325			}
1326			checkDeletedFiles(conversation);
1327			this.conversations.add(conversation);
1328			updateConversationUi();
1329			return conversation;
1330		}
1331	}
1332
1333	public void archiveConversation(Conversation conversation) {
1334		getNotificationService().clear(conversation);
1335		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1336		conversation.setNextEncryption(-1);
1337		synchronized (this.conversations) {
1338			if (conversation.getMode() == Conversation.MODE_MULTI) {
1339				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1340					Bookmark bookmark = conversation.getBookmark();
1341					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1342						bookmark.setAutojoin(false);
1343						pushBookmarks(bookmark.getAccount());
1344					}
1345				}
1346				leaveMuc(conversation);
1347			} else {
1348				conversation.endOtrIfNeeded();
1349				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1350					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1351					sendPresencePacket(
1352							conversation.getAccount(),
1353							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1354					);
1355				}
1356			}
1357			this.databaseBackend.updateConversation(conversation);
1358			this.conversations.remove(conversation);
1359			updateConversationUi();
1360		}
1361	}
1362
1363	public void createAccount(final Account account) {
1364		account.initAccountServices(this);
1365		databaseBackend.createAccount(account);
1366		this.accounts.add(account);
1367		this.reconnectAccountInBackground(account);
1368		updateAccountUi();
1369	}
1370
1371	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1372		new Thread(new Runnable() {
1373			@Override
1374			public void run() {
1375				try {
1376					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1377					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1378					if (findAccountByJid(info.first) == null) {
1379						Account account = new Account(info.first, "");
1380						account.setPrivateKeyAlias(alias);
1381						account.setOption(Account.OPTION_DISABLED, true);
1382						account.setDisplayName(info.second);
1383						createAccount(account);
1384						callback.onAccountCreated(account);
1385						if (Config.X509_VERIFICATION) {
1386							try {
1387								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1388							} catch (CertificateException e) {
1389								callback.informUser(R.string.certificate_chain_is_not_trusted);
1390							}
1391						}
1392					} else {
1393						callback.informUser(R.string.account_already_exists);
1394					}
1395				} catch (Exception e) {
1396					e.printStackTrace();
1397					callback.informUser(R.string.unable_to_parse_certificate);
1398				}
1399			}
1400		}).start();
1401
1402	}
1403
1404	public void updateKeyInAccount(final Account account, final String alias) {
1405		Log.d(Config.LOGTAG, "update key in account " + alias);
1406		try {
1407			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1408			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1409			if (account.getJid().toBareJid().equals(info.first)) {
1410				account.setPrivateKeyAlias(alias);
1411				account.setDisplayName(info.second);
1412				databaseBackend.updateAccount(account);
1413				if (Config.X509_VERIFICATION) {
1414					try {
1415						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1416					} catch (CertificateException e) {
1417						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1418					}
1419					account.getAxolotlService().regenerateKeys(true);
1420				}
1421			} else {
1422				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1423			}
1424		} catch (Exception e) {
1425			e.printStackTrace();
1426		}
1427	}
1428
1429	public void updateAccount(final Account account) {
1430		this.statusListener.onStatusChanged(account);
1431		databaseBackend.updateAccount(account);
1432		reconnectAccountInBackground(account);
1433		updateAccountUi();
1434		getNotificationService().updateErrorNotification();
1435	}
1436
1437	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1438		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1439		sendIqPacket(account, iq, new OnIqPacketReceived() {
1440			@Override
1441			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1442				if (packet.getType() == IqPacket.TYPE.RESULT) {
1443					account.setPassword(newPassword);
1444					databaseBackend.updateAccount(account);
1445					callback.onPasswordChangeSucceeded();
1446				} else {
1447					callback.onPasswordChangeFailed();
1448				}
1449			}
1450		});
1451	}
1452
1453	public void deleteAccount(final Account account) {
1454		synchronized (this.conversations) {
1455			for (final Conversation conversation : conversations) {
1456				if (conversation.getAccount() == account) {
1457					if (conversation.getMode() == Conversation.MODE_MULTI) {
1458						leaveMuc(conversation);
1459					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1460						conversation.endOtrIfNeeded();
1461					}
1462					conversations.remove(conversation);
1463				}
1464			}
1465			if (account.getXmppConnection() != null) {
1466				this.disconnect(account, true);
1467			}
1468			Runnable runnable = new Runnable() {
1469				@Override
1470				public void run() {
1471					databaseBackend.deleteAccount(account);
1472				}
1473			};
1474			mDatabaseExecutor.execute(runnable);
1475			this.accounts.remove(account);
1476			updateAccountUi();
1477			getNotificationService().updateErrorNotification();
1478		}
1479	}
1480
1481	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1482		synchronized (this) {
1483			if (checkListeners()) {
1484				switchToForeground();
1485			}
1486			this.mOnConversationUpdate = listener;
1487			this.mNotificationService.setIsInForeground(true);
1488			if (this.convChangedListenerCount < 2) {
1489				this.convChangedListenerCount++;
1490			}
1491		}
1492	}
1493
1494	public void removeOnConversationListChangedListener() {
1495		synchronized (this) {
1496			this.convChangedListenerCount--;
1497			if (this.convChangedListenerCount <= 0) {
1498				this.convChangedListenerCount = 0;
1499				this.mOnConversationUpdate = null;
1500				this.mNotificationService.setIsInForeground(false);
1501				if (checkListeners()) {
1502					switchToBackground();
1503				}
1504			}
1505		}
1506	}
1507
1508	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1509		synchronized (this) {
1510			if (checkListeners()) {
1511				switchToForeground();
1512			}
1513			this.mOnShowErrorToast = onShowErrorToast;
1514			if (this.showErrorToastListenerCount < 2) {
1515				this.showErrorToastListenerCount++;
1516			}
1517		}
1518		this.mOnShowErrorToast = onShowErrorToast;
1519	}
1520
1521	public void removeOnShowErrorToastListener() {
1522		synchronized (this) {
1523			this.showErrorToastListenerCount--;
1524			if (this.showErrorToastListenerCount <= 0) {
1525				this.showErrorToastListenerCount = 0;
1526				this.mOnShowErrorToast = null;
1527				if (checkListeners()) {
1528					switchToBackground();
1529				}
1530			}
1531		}
1532	}
1533
1534	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1535		synchronized (this) {
1536			if (checkListeners()) {
1537				switchToForeground();
1538			}
1539			this.mOnAccountUpdate = listener;
1540			if (this.accountChangedListenerCount < 2) {
1541				this.accountChangedListenerCount++;
1542			}
1543		}
1544	}
1545
1546	public void removeOnAccountListChangedListener() {
1547		synchronized (this) {
1548			this.accountChangedListenerCount--;
1549			if (this.accountChangedListenerCount <= 0) {
1550				this.mOnAccountUpdate = null;
1551				this.accountChangedListenerCount = 0;
1552				if (checkListeners()) {
1553					switchToBackground();
1554				}
1555			}
1556		}
1557	}
1558
1559	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1560		synchronized (this) {
1561			if (checkListeners()) {
1562				switchToForeground();
1563			}
1564			this.mOnCaptchaRequested = listener;
1565			if (this.captchaRequestedListenerCount < 2) {
1566				this.captchaRequestedListenerCount++;
1567			}
1568		}
1569	}
1570
1571	public void removeOnCaptchaRequestedListener() {
1572		synchronized (this) {
1573			this.captchaRequestedListenerCount--;
1574			if (this.captchaRequestedListenerCount <= 0) {
1575				this.mOnCaptchaRequested = null;
1576				this.captchaRequestedListenerCount = 0;
1577				if (checkListeners()) {
1578					switchToBackground();
1579				}
1580			}
1581		}
1582	}
1583
1584	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1585		synchronized (this) {
1586			if (checkListeners()) {
1587				switchToForeground();
1588			}
1589			this.mOnRosterUpdate = listener;
1590			if (this.rosterChangedListenerCount < 2) {
1591				this.rosterChangedListenerCount++;
1592			}
1593		}
1594	}
1595
1596	public void removeOnRosterUpdateListener() {
1597		synchronized (this) {
1598			this.rosterChangedListenerCount--;
1599			if (this.rosterChangedListenerCount <= 0) {
1600				this.rosterChangedListenerCount = 0;
1601				this.mOnRosterUpdate = null;
1602				if (checkListeners()) {
1603					switchToBackground();
1604				}
1605			}
1606		}
1607	}
1608
1609	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1610		synchronized (this) {
1611			if (checkListeners()) {
1612				switchToForeground();
1613			}
1614			this.mOnUpdateBlocklist = listener;
1615			if (this.updateBlocklistListenerCount < 2) {
1616				this.updateBlocklistListenerCount++;
1617			}
1618		}
1619	}
1620
1621	public void removeOnUpdateBlocklistListener() {
1622		synchronized (this) {
1623			this.updateBlocklistListenerCount--;
1624			if (this.updateBlocklistListenerCount <= 0) {
1625				this.updateBlocklistListenerCount = 0;
1626				this.mOnUpdateBlocklist = null;
1627				if (checkListeners()) {
1628					switchToBackground();
1629				}
1630			}
1631		}
1632	}
1633
1634	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1635		synchronized (this) {
1636			if (checkListeners()) {
1637				switchToForeground();
1638			}
1639			this.mOnKeyStatusUpdated = listener;
1640			if (this.keyStatusUpdatedListenerCount < 2) {
1641				this.keyStatusUpdatedListenerCount++;
1642			}
1643		}
1644	}
1645
1646	public void removeOnNewKeysAvailableListener() {
1647		synchronized (this) {
1648			this.keyStatusUpdatedListenerCount--;
1649			if (this.keyStatusUpdatedListenerCount <= 0) {
1650				this.keyStatusUpdatedListenerCount = 0;
1651				this.mOnKeyStatusUpdated = null;
1652				if (checkListeners()) {
1653					switchToBackground();
1654				}
1655			}
1656		}
1657	}
1658
1659	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1660		synchronized (this) {
1661			if (checkListeners()) {
1662				switchToForeground();
1663			}
1664			this.mOnMucRosterUpdate = listener;
1665			if (this.mucRosterChangedListenerCount < 2) {
1666				this.mucRosterChangedListenerCount++;
1667			}
1668		}
1669	}
1670
1671	public void removeOnMucRosterUpdateListener() {
1672		synchronized (this) {
1673			this.mucRosterChangedListenerCount--;
1674			if (this.mucRosterChangedListenerCount <= 0) {
1675				this.mucRosterChangedListenerCount = 0;
1676				this.mOnMucRosterUpdate = null;
1677				if (checkListeners()) {
1678					switchToBackground();
1679				}
1680			}
1681		}
1682	}
1683
1684	private boolean checkListeners() {
1685		return (this.mOnAccountUpdate == null
1686				&& this.mOnConversationUpdate == null
1687				&& this.mOnRosterUpdate == null
1688				&& this.mOnCaptchaRequested == null
1689				&& this.mOnUpdateBlocklist == null
1690				&& this.mOnShowErrorToast == null
1691				&& this.mOnKeyStatusUpdated == null);
1692	}
1693
1694	private void switchToForeground() {
1695		for (Conversation conversation : getConversations()) {
1696			conversation.setIncomingChatState(ChatState.ACTIVE);
1697		}
1698		for (Account account : getAccounts()) {
1699			if (account.getStatus() == Account.State.ONLINE) {
1700				XmppConnection connection = account.getXmppConnection();
1701				if (connection != null && connection.getFeatures().csi()) {
1702					connection.sendActive();
1703				}
1704			}
1705		}
1706		Log.d(Config.LOGTAG, "app switched into foreground");
1707	}
1708
1709	private void switchToBackground() {
1710		for (Account account : getAccounts()) {
1711			if (account.getStatus() == Account.State.ONLINE) {
1712				XmppConnection connection = account.getXmppConnection();
1713				if (connection != null && connection.getFeatures().csi()) {
1714					connection.sendInactive();
1715				}
1716			}
1717		}
1718		this.mNotificationService.setIsInForeground(false);
1719		Log.d(Config.LOGTAG, "app switched into background");
1720	}
1721
1722	private void connectMultiModeConversations(Account account) {
1723		List<Conversation> conversations = getConversations();
1724		for (Conversation conversation : conversations) {
1725			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1726				joinMuc(conversation, true, null);
1727			}
1728		}
1729	}
1730
1731	public void joinMuc(Conversation conversation) {
1732		joinMuc(conversation, false, null);
1733	}
1734
1735	private void joinMuc(Conversation conversation, boolean now, final OnConferenceJoined onConferenceJoined) {
1736		Account account = conversation.getAccount();
1737		account.pendingConferenceJoins.remove(conversation);
1738		account.pendingConferenceLeaves.remove(conversation);
1739		if (account.getStatus() == Account.State.ONLINE || now) {
1740			conversation.resetMucOptions();
1741			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1742
1743				private void join(Conversation conversation) {
1744					Account account = conversation.getAccount();
1745					final String nick = conversation.getMucOptions().getProposedNick();
1746					final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1747					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1748					PresencePacket packet = new PresencePacket();
1749					packet.setFrom(conversation.getAccount().getJid());
1750					packet.setTo(joinJid);
1751					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1752					if (conversation.getMucOptions().getPassword() != null) {
1753						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1754					}
1755
1756					if (conversation.getMucOptions().mamSupport()) {
1757						// Use MAM instead of the limited muc history to get history
1758						x.addChild("history").setAttribute("maxchars", "0");
1759					} else {
1760						// Fallback to muc history
1761						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1762					}
1763					String sig = account.getPgpSignature();
1764					if (sig != null) {
1765						packet.addChild("x", "jabber:x:signed").setContent(sig);
1766					}
1767					sendPresencePacket(account, packet);
1768					if (onConferenceJoined != null) {
1769						onConferenceJoined.onConferenceJoined(conversation);
1770					}
1771					if (!joinJid.equals(conversation.getJid())) {
1772						conversation.setContactJid(joinJid);
1773						databaseBackend.updateConversation(conversation);
1774					}
1775					conversation.setHasMessagesLeftOnServer(false);
1776					if (conversation.getMucOptions().mamSupport()) {
1777						getMessageArchiveService().catchupMUC(conversation);
1778					}
1779				}
1780
1781				@Override
1782				public void onConferenceConfigurationFetched(Conversation conversation) {
1783					join(conversation);
1784				}
1785
1786				@Override
1787				public void onFetchFailed(final Conversation conversation, Element error) {
1788					join(conversation);
1789					fetchConferenceConfiguration(conversation);
1790				}
1791			});
1792
1793		} else {
1794			account.pendingConferenceJoins.add(conversation);
1795		}
1796	}
1797
1798	public void providePasswordForMuc(Conversation conversation, String password) {
1799		if (conversation.getMode() == Conversation.MODE_MULTI) {
1800			conversation.getMucOptions().setPassword(password);
1801			if (conversation.getBookmark() != null) {
1802				if (respectAutojoin()) {
1803					conversation.getBookmark().setAutojoin(true);
1804				}
1805				pushBookmarks(conversation.getAccount());
1806			}
1807			databaseBackend.updateConversation(conversation);
1808			joinMuc(conversation);
1809		}
1810	}
1811
1812	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1813		final MucOptions options = conversation.getMucOptions();
1814		final Jid joinJid = options.createJoinJid(nick);
1815		if (options.online()) {
1816			Account account = conversation.getAccount();
1817			options.setOnRenameListener(new OnRenameListener() {
1818
1819				@Override
1820				public void onSuccess() {
1821					conversation.setContactJid(joinJid);
1822					databaseBackend.updateConversation(conversation);
1823					Bookmark bookmark = conversation.getBookmark();
1824					if (bookmark != null) {
1825						bookmark.setNick(nick);
1826						pushBookmarks(bookmark.getAccount());
1827					}
1828					callback.success(conversation);
1829				}
1830
1831				@Override
1832				public void onFailure() {
1833					callback.error(R.string.nick_in_use, conversation);
1834				}
1835			});
1836
1837			PresencePacket packet = new PresencePacket();
1838			packet.setTo(joinJid);
1839			packet.setFrom(conversation.getAccount().getJid());
1840
1841			String sig = account.getPgpSignature();
1842			if (sig != null) {
1843				packet.addChild("status").setContent("online");
1844				packet.addChild("x", "jabber:x:signed").setContent(sig);
1845			}
1846			sendPresencePacket(account, packet);
1847		} else {
1848			conversation.setContactJid(joinJid);
1849			databaseBackend.updateConversation(conversation);
1850			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1851				Bookmark bookmark = conversation.getBookmark();
1852				if (bookmark != null) {
1853					bookmark.setNick(nick);
1854					pushBookmarks(bookmark.getAccount());
1855				}
1856				joinMuc(conversation);
1857			}
1858		}
1859	}
1860
1861	public void leaveMuc(Conversation conversation) {
1862		leaveMuc(conversation, false);
1863	}
1864
1865	private void leaveMuc(Conversation conversation, boolean now) {
1866		Account account = conversation.getAccount();
1867		account.pendingConferenceJoins.remove(conversation);
1868		account.pendingConferenceLeaves.remove(conversation);
1869		if (account.getStatus() == Account.State.ONLINE || now) {
1870			PresencePacket packet = new PresencePacket();
1871			packet.setTo(conversation.getJid());
1872			packet.setFrom(conversation.getAccount().getJid());
1873			packet.setAttribute("type", "unavailable");
1874			sendPresencePacket(conversation.getAccount(), packet);
1875			conversation.getMucOptions().setOffline();
1876			conversation.deregisterWithBookmark();
1877			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1878					+ ": leaving muc " + conversation.getJid());
1879		} else {
1880			account.pendingConferenceLeaves.add(conversation);
1881		}
1882	}
1883
1884	private String findConferenceServer(final Account account) {
1885		String server;
1886		if (account.getXmppConnection() != null) {
1887			server = account.getXmppConnection().getMucServer();
1888			if (server != null) {
1889				return server;
1890			}
1891		}
1892		for (Account other : getAccounts()) {
1893			if (other != account && other.getXmppConnection() != null) {
1894				server = other.getXmppConnection().getMucServer();
1895				if (server != null) {
1896					return server;
1897				}
1898			}
1899		}
1900		return null;
1901	}
1902
1903	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1904		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1905		if (account.getStatus() == Account.State.ONLINE) {
1906			try {
1907				String server = findConferenceServer(account);
1908				if (server == null) {
1909					if (callback != null) {
1910						callback.error(R.string.no_conference_server_found, null);
1911					}
1912					return;
1913				}
1914				String name = new BigInteger(75, getRNG()).toString(32);
1915				Jid jid = Jid.fromParts(name, server, null);
1916				final Conversation conversation = findOrCreateConversation(account, jid, true);
1917				joinMuc(conversation, true, new OnConferenceJoined() {
1918					@Override
1919					public void onConferenceJoined(final Conversation conversation) {
1920						Bundle options = new Bundle();
1921						options.putString("muc#roomconfig_persistentroom", "1");
1922						options.putString("muc#roomconfig_membersonly", "1");
1923						options.putString("muc#roomconfig_publicroom", "0");
1924						options.putString("muc#roomconfig_whois", "anyone");
1925						pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1926							@Override
1927							public void onPushSucceeded() {
1928								for (Jid invite : jids) {
1929									invite(conversation, invite);
1930								}
1931								if (account.countPresences() > 1) {
1932									directInvite(conversation, account.getJid().toBareJid());
1933								}
1934								if (callback != null) {
1935									callback.success(conversation);
1936								}
1937							}
1938
1939							@Override
1940							public void onPushFailed() {
1941								if (callback != null) {
1942									callback.error(R.string.conference_creation_failed, conversation);
1943								}
1944							}
1945						});
1946					}
1947				});
1948			} catch (InvalidJidException e) {
1949				if (callback != null) {
1950					callback.error(R.string.conference_creation_failed, null);
1951				}
1952			}
1953		} else {
1954			if (callback != null) {
1955				callback.error(R.string.not_connected_try_again, null);
1956			}
1957		}
1958	}
1959
1960	public void fetchConferenceConfiguration(final Conversation conversation) {
1961		fetchConferenceConfiguration(conversation, null);
1962	}
1963
1964	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1965		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1966		request.setTo(conversation.getJid().toBareJid());
1967		request.query("http://jabber.org/protocol/disco#info");
1968		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1969			@Override
1970			public void onIqPacketReceived(Account account, IqPacket packet) {
1971				if (packet.getType() == IqPacket.TYPE.RESULT) {
1972					ArrayList<String> features = new ArrayList<>();
1973					Element query = packet.query();
1974					for (Element child : query.getChildren()) {
1975						if (child != null && child.getName().equals("feature")) {
1976							String var = child.getAttribute("var");
1977							if (var != null) {
1978								features.add(var);
1979							}
1980						}
1981					}
1982					Element form = query.findChild("x", "jabber:x:data");
1983					if (form != null) {
1984						conversation.getMucOptions().updateFormData(Data.parse(form));
1985					}
1986					conversation.getMucOptions().updateFeatures(features);
1987					if (callback != null) {
1988						callback.onConferenceConfigurationFetched(conversation);
1989					}
1990					updateConversationUi();
1991				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
1992					if (callback != null) {
1993						callback.onFetchFailed(conversation, packet.getError());
1994					}
1995				}
1996			}
1997		});
1998	}
1999
2000	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2001		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2002		request.setTo(conversation.getJid().toBareJid());
2003		request.query("http://jabber.org/protocol/muc#owner");
2004		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2005			@Override
2006			public void onIqPacketReceived(Account account, IqPacket packet) {
2007				if (packet.getType() == IqPacket.TYPE.RESULT) {
2008					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2009					for (Field field : data.getFields()) {
2010						if (options.containsKey(field.getFieldName())) {
2011							field.setValue(options.getString(field.getFieldName()));
2012						}
2013					}
2014					data.submit();
2015					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2016					set.setTo(conversation.getJid().toBareJid());
2017					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2018					sendIqPacket(account, set, new OnIqPacketReceived() {
2019						@Override
2020						public void onIqPacketReceived(Account account, IqPacket packet) {
2021							if (callback != null) {
2022								if (packet.getType() == IqPacket.TYPE.RESULT) {
2023									callback.onPushSucceeded();
2024								} else {
2025									callback.onPushFailed();
2026								}
2027							}
2028						}
2029					});
2030				} else {
2031					if (callback != null) {
2032						callback.onPushFailed();
2033					}
2034				}
2035			}
2036		});
2037	}
2038
2039	public void pushSubjectToConference(final Conversation conference, final String subject) {
2040		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2041		this.sendMessagePacket(conference.getAccount(), packet);
2042		final MucOptions mucOptions = conference.getMucOptions();
2043		final MucOptions.User self = mucOptions.getSelf();
2044		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2045			Bundle options = new Bundle();
2046			options.putString("muc#roomconfig_persistentroom", "1");
2047			this.pushConferenceConfiguration(conference, options, null);
2048		}
2049	}
2050
2051	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2052		final Jid jid = user.toBareJid();
2053		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2054		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2055			@Override
2056			public void onIqPacketReceived(Account account, IqPacket packet) {
2057				if (packet.getType() == IqPacket.TYPE.RESULT) {
2058					callback.onAffiliationChangedSuccessful(jid);
2059				} else {
2060					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2061				}
2062			}
2063		});
2064	}
2065
2066	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2067		List<Jid> jids = new ArrayList<>();
2068		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2069			if (user.getAffiliation() == before && user.getJid() != null) {
2070				jids.add(user.getJid());
2071			}
2072		}
2073		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2074		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2075	}
2076
2077	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2078		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2079		Log.d(Config.LOGTAG, request.toString());
2080		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2081			@Override
2082			public void onIqPacketReceived(Account account, IqPacket packet) {
2083				Log.d(Config.LOGTAG, packet.toString());
2084				if (packet.getType() == IqPacket.TYPE.RESULT) {
2085					callback.onRoleChangedSuccessful(nick);
2086				} else {
2087					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2088				}
2089			}
2090		});
2091	}
2092
2093	private void disconnect(Account account, boolean force) {
2094		if ((account.getStatus() == Account.State.ONLINE)
2095				|| (account.getStatus() == Account.State.DISABLED)) {
2096			if (!force) {
2097				List<Conversation> conversations = getConversations();
2098				for (Conversation conversation : conversations) {
2099					if (conversation.getAccount() == account) {
2100						if (conversation.getMode() == Conversation.MODE_MULTI) {
2101							leaveMuc(conversation, true);
2102						} else {
2103							if (conversation.endOtrIfNeeded()) {
2104								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2105										+ ": ended otr session with "
2106										+ conversation.getJid());
2107							}
2108						}
2109					}
2110				}
2111				sendOfflinePresence(account);
2112			}
2113			account.getXmppConnection().disconnect(force);
2114		}
2115	}
2116
2117	@Override
2118	public IBinder onBind(Intent intent) {
2119		return mBinder;
2120	}
2121
2122	public void updateMessage(Message message) {
2123		databaseBackend.updateMessage(message);
2124		updateConversationUi();
2125	}
2126
2127	protected void syncDirtyContacts(Account account) {
2128		for (Contact contact : account.getRoster().getContacts()) {
2129			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2130				pushContactToServer(contact);
2131			}
2132			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2133				deleteContactOnServer(contact);
2134			}
2135		}
2136	}
2137
2138	public void createContact(Contact contact) {
2139		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2140		if (autoGrant) {
2141			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2142			contact.setOption(Contact.Options.ASKING);
2143		}
2144		pushContactToServer(contact);
2145	}
2146
2147	public void onOtrSessionEstablished(Conversation conversation) {
2148		final Account account = conversation.getAccount();
2149		final Session otrSession = conversation.getOtrSession();
2150		Log.d(Config.LOGTAG,
2151				account.getJid().toBareJid() + " otr session established with "
2152						+ conversation.getJid() + "/"
2153						+ otrSession.getSessionID().getUserID());
2154		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2155
2156			@Override
2157			public void onMessageFound(Message message) {
2158				SessionID id = otrSession.getSessionID();
2159				try {
2160					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2161				} catch (InvalidJidException e) {
2162					return;
2163				}
2164				if (message.needsUploading()) {
2165					mJingleConnectionManager.createNewConnection(message);
2166				} else {
2167					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2168					if (outPacket != null) {
2169						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2170						message.setStatus(Message.STATUS_SEND);
2171						databaseBackend.updateMessage(message);
2172						sendMessagePacket(account, outPacket);
2173					}
2174				}
2175				updateConversationUi();
2176			}
2177		});
2178	}
2179
2180	public boolean renewSymmetricKey(Conversation conversation) {
2181		Account account = conversation.getAccount();
2182		byte[] symmetricKey = new byte[32];
2183		this.mRandom.nextBytes(symmetricKey);
2184		Session otrSession = conversation.getOtrSession();
2185		if (otrSession != null) {
2186			MessagePacket packet = new MessagePacket();
2187			packet.setType(MessagePacket.TYPE_CHAT);
2188			packet.setFrom(account.getJid());
2189			MessageGenerator.addMessageHints(packet);
2190			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2191					+ otrSession.getSessionID().getUserID());
2192			try {
2193				packet.setBody(otrSession
2194						.transformSending(CryptoHelper.FILETRANSFER
2195								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2196				sendMessagePacket(account, packet);
2197				conversation.setSymmetricKey(symmetricKey);
2198				return true;
2199			} catch (OtrException e) {
2200				return false;
2201			}
2202		}
2203		return false;
2204	}
2205
2206	public void pushContactToServer(final Contact contact) {
2207		contact.resetOption(Contact.Options.DIRTY_DELETE);
2208		contact.setOption(Contact.Options.DIRTY_PUSH);
2209		final Account account = contact.getAccount();
2210		if (account.getStatus() == Account.State.ONLINE) {
2211			final boolean ask = contact.getOption(Contact.Options.ASKING);
2212			final boolean sendUpdates = contact
2213					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2214					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2215			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2216			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2217			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2218			if (sendUpdates) {
2219				sendPresencePacket(account,
2220						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2221			}
2222			if (ask) {
2223				sendPresencePacket(account,
2224						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2225			}
2226		}
2227	}
2228
2229	public void publishAvatar(final Account account,
2230							  final Uri image,
2231							  final UiCallback<Avatar> callback) {
2232		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2233		final int size = Config.AVATAR_SIZE;
2234		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2235		if (avatar != null) {
2236			avatar.height = size;
2237			avatar.width = size;
2238			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2239				avatar.type = "image/webp";
2240			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2241				avatar.type = "image/jpeg";
2242			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2243				avatar.type = "image/png";
2244			}
2245			if (!getFileBackend().save(avatar)) {
2246				callback.error(R.string.error_saving_avatar, avatar);
2247				return;
2248			}
2249			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2250			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2251
2252				@Override
2253				public void onIqPacketReceived(Account account, IqPacket result) {
2254					if (result.getType() == IqPacket.TYPE.RESULT) {
2255						final IqPacket packet = XmppConnectionService.this.mIqGenerator
2256								.publishAvatarMetadata(avatar);
2257						sendIqPacket(account, packet, new OnIqPacketReceived() {
2258							@Override
2259							public void onIqPacketReceived(Account account, IqPacket result) {
2260								if (result.getType() == IqPacket.TYPE.RESULT) {
2261									if (account.setAvatar(avatar.getFilename())) {
2262										getAvatarService().clear(account);
2263										databaseBackend.updateAccount(account);
2264									}
2265									callback.success(avatar);
2266								} else {
2267									callback.error(
2268											R.string.error_publish_avatar_server_reject,
2269											avatar);
2270								}
2271							}
2272						});
2273					} else {
2274						callback.error(
2275								R.string.error_publish_avatar_server_reject,
2276								avatar);
2277					}
2278				}
2279			});
2280		} else {
2281			callback.error(R.string.error_publish_avatar_converting, null);
2282		}
2283	}
2284
2285	public void fetchAvatar(Account account, Avatar avatar) {
2286		fetchAvatar(account, avatar, null);
2287	}
2288
2289	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2290		final String KEY = generateFetchKey(account, avatar);
2291		synchronized (this.mInProgressAvatarFetches) {
2292			if (this.mInProgressAvatarFetches.contains(KEY)) {
2293				return;
2294			} else {
2295				switch (avatar.origin) {
2296					case PEP:
2297						this.mInProgressAvatarFetches.add(KEY);
2298						fetchAvatarPep(account, avatar, callback);
2299						break;
2300					case VCARD:
2301						this.mInProgressAvatarFetches.add(KEY);
2302						fetchAvatarVcard(account, avatar, callback);
2303						break;
2304				}
2305			}
2306		}
2307	}
2308
2309	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2310		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2311		sendIqPacket(account, packet, new OnIqPacketReceived() {
2312
2313			@Override
2314			public void onIqPacketReceived(Account account, IqPacket result) {
2315				synchronized (mInProgressAvatarFetches) {
2316					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2317				}
2318				final String ERROR = account.getJid().toBareJid()
2319						+ ": fetching avatar for " + avatar.owner + " failed ";
2320				if (result.getType() == IqPacket.TYPE.RESULT) {
2321					avatar.image = mIqParser.avatarData(result);
2322					if (avatar.image != null) {
2323						if (getFileBackend().save(avatar)) {
2324							if (account.getJid().toBareJid().equals(avatar.owner)) {
2325								if (account.setAvatar(avatar.getFilename())) {
2326									databaseBackend.updateAccount(account);
2327								}
2328								getAvatarService().clear(account);
2329								updateConversationUi();
2330								updateAccountUi();
2331							} else {
2332								Contact contact = account.getRoster()
2333										.getContact(avatar.owner);
2334								contact.setAvatar(avatar);
2335								getAvatarService().clear(contact);
2336								updateConversationUi();
2337								updateRosterUi();
2338							}
2339							if (callback != null) {
2340								callback.success(avatar);
2341							}
2342							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2343									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2344							return;
2345						}
2346					} else {
2347
2348						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2349					}
2350				} else {
2351					Element error = result.findChild("error");
2352					if (error == null) {
2353						Log.d(Config.LOGTAG, ERROR + "(server error)");
2354					} else {
2355						Log.d(Config.LOGTAG, ERROR + error.toString());
2356					}
2357				}
2358				if (callback != null) {
2359					callback.error(0, null);
2360				}
2361
2362			}
2363		});
2364	}
2365
2366	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2367		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2368		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2369			@Override
2370			public void onIqPacketReceived(Account account, IqPacket packet) {
2371				synchronized (mInProgressAvatarFetches) {
2372					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2373				}
2374				if (packet.getType() == IqPacket.TYPE.RESULT) {
2375					Element vCard = packet.findChild("vCard", "vcard-temp");
2376					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2377					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2378					if (image != null) {
2379						avatar.image = image;
2380						if (getFileBackend().save(avatar)) {
2381							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2382									+ ": successfully fetched vCard avatar for " + avatar.owner);
2383							if (avatar.owner.isBareJid()) {
2384								Contact contact = account.getRoster()
2385										.getContact(avatar.owner);
2386								contact.setAvatar(avatar);
2387								getAvatarService().clear(contact);
2388								updateConversationUi();
2389								updateRosterUi();
2390							} else {
2391								Conversation conversation = find(account, avatar.owner.toBareJid());
2392								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2393									MucOptions.User user = conversation.getMucOptions().findUser(avatar.owner.getResourcepart());
2394									if (user != null) {
2395										if (user.setAvatar(avatar)) {
2396											getAvatarService().clear(user);
2397											updateConversationUi();
2398											updateMucRosterUi();
2399										}
2400									}
2401								}
2402							}
2403						}
2404					}
2405				}
2406			}
2407		});
2408	}
2409
2410	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2411		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2412		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2413
2414			@Override
2415			public void onIqPacketReceived(Account account, IqPacket packet) {
2416				if (packet.getType() == IqPacket.TYPE.RESULT) {
2417					Element pubsub = packet.findChild("pubsub",
2418							"http://jabber.org/protocol/pubsub");
2419					if (pubsub != null) {
2420						Element items = pubsub.findChild("items");
2421						if (items != null) {
2422							Avatar avatar = Avatar.parseMetadata(items);
2423							if (avatar != null) {
2424								avatar.owner = account.getJid().toBareJid();
2425								if (fileBackend.isAvatarCached(avatar)) {
2426									if (account.setAvatar(avatar.getFilename())) {
2427										databaseBackend.updateAccount(account);
2428									}
2429									getAvatarService().clear(account);
2430									callback.success(avatar);
2431								} else {
2432									fetchAvatarPep(account, avatar, callback);
2433								}
2434								return;
2435							}
2436						}
2437					}
2438				}
2439				callback.error(0, null);
2440			}
2441		});
2442	}
2443
2444	public void deleteContactOnServer(Contact contact) {
2445		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2446		contact.resetOption(Contact.Options.DIRTY_PUSH);
2447		contact.setOption(Contact.Options.DIRTY_DELETE);
2448		Account account = contact.getAccount();
2449		if (account.getStatus() == Account.State.ONLINE) {
2450			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2451			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2452			item.setAttribute("jid", contact.getJid().toString());
2453			item.setAttribute("subscription", "remove");
2454			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2455		}
2456	}
2457
2458	public void updateConversation(Conversation conversation) {
2459		this.databaseBackend.updateConversation(conversation);
2460	}
2461
2462	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2463		synchronized (account) {
2464			XmppConnection connection = account.getXmppConnection();
2465			if (connection != null) {
2466				disconnect(account, force);
2467			} else {
2468				connection = createConnection(account);
2469				account.setXmppConnection(connection);
2470			}
2471			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2472				synchronized (this.mInProgressAvatarFetches) {
2473					for (Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
2474						final String KEY = iterator.next();
2475						if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
2476							iterator.remove();
2477						}
2478					}
2479				}
2480				if (!force) {
2481					try {
2482						Log.d(Config.LOGTAG, "wait for disconnect");
2483						Thread.sleep(500); //sleep  wait for disconnect
2484					} catch (InterruptedException e) {
2485						//ignored
2486					}
2487				}
2488				Thread thread = new Thread(connection);
2489				connection.setInteractive(interactive);
2490				thread.start();
2491				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2492			} else {
2493				account.getRoster().clearPresences();
2494				connection.resetEverything();
2495			}
2496		}
2497	}
2498
2499	public void reconnectAccountInBackground(final Account account) {
2500		new Thread(new Runnable() {
2501			@Override
2502			public void run() {
2503				reconnectAccount(account, false, true);
2504			}
2505		}).start();
2506	}
2507
2508	public void invite(Conversation conversation, Jid contact) {
2509		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2510		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2511		sendMessagePacket(conversation.getAccount(), packet);
2512	}
2513
2514	public void directInvite(Conversation conversation, Jid jid) {
2515		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2516		sendMessagePacket(conversation.getAccount(), packet);
2517	}
2518
2519	public void resetSendingToWaiting(Account account) {
2520		for (Conversation conversation : getConversations()) {
2521			if (conversation.getAccount() == account) {
2522				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2523
2524					@Override
2525					public void onMessageFound(Message message) {
2526						markMessage(message, Message.STATUS_WAITING);
2527					}
2528				});
2529			}
2530		}
2531	}
2532
2533	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2534		if (uuid == null) {
2535			return null;
2536		}
2537		for (Conversation conversation : getConversations()) {
2538			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2539				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2540				if (message != null) {
2541					markMessage(message, status);
2542				}
2543				return message;
2544			}
2545		}
2546		return null;
2547	}
2548
2549	public boolean markMessage(Conversation conversation, String uuid, int status) {
2550		if (uuid == null) {
2551			return false;
2552		} else {
2553			Message message = conversation.findSentMessageWithUuid(uuid);
2554			if (message != null) {
2555				markMessage(message, status);
2556				return true;
2557			} else {
2558				return false;
2559			}
2560		}
2561	}
2562
2563	public void markMessage(Message message, int status) {
2564		if (status == Message.STATUS_SEND_FAILED
2565				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2566				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2567			return;
2568		}
2569		message.setStatus(status);
2570		databaseBackend.updateMessage(message);
2571		updateConversationUi();
2572	}
2573
2574	public SharedPreferences getPreferences() {
2575		return PreferenceManager
2576				.getDefaultSharedPreferences(getApplicationContext());
2577	}
2578
2579	public boolean confirmMessages() {
2580		return getPreferences().getBoolean("confirm_messages", true);
2581	}
2582
2583	public boolean sendChatStates() {
2584		return getPreferences().getBoolean("chat_states", false);
2585	}
2586
2587	public boolean saveEncryptedMessages() {
2588		return !getPreferences().getBoolean("dont_save_encrypted", false);
2589	}
2590
2591	private boolean respectAutojoin() {
2592		return getPreferences().getBoolean("autojoin", true);
2593	}
2594
2595	public boolean indicateReceived() {
2596		return getPreferences().getBoolean("indicate_received", false);
2597	}
2598
2599	public boolean useTorToConnect() {
2600		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2601	}
2602
2603	public boolean showExtendedConnectionOptions() {
2604		return getPreferences().getBoolean("show_connection_options", false);
2605	}
2606
2607	public int unreadCount() {
2608		int count = 0;
2609		for (Conversation conversation : getConversations()) {
2610			count += conversation.unreadCount();
2611		}
2612		return count;
2613	}
2614
2615
2616	public void showErrorToastInUi(int resId) {
2617		if (mOnShowErrorToast != null) {
2618			mOnShowErrorToast.onShowErrorToast(resId);
2619		}
2620	}
2621
2622	public void updateConversationUi() {
2623		if (mOnConversationUpdate != null) {
2624			mOnConversationUpdate.onConversationUpdate();
2625		}
2626	}
2627
2628	public void updateAccountUi() {
2629		if (mOnAccountUpdate != null) {
2630			mOnAccountUpdate.onAccountUpdate();
2631		}
2632	}
2633
2634	public void updateRosterUi() {
2635		if (mOnRosterUpdate != null) {
2636			mOnRosterUpdate.onRosterUpdate();
2637		}
2638	}
2639
2640	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2641		boolean rc = false;
2642		if (mOnCaptchaRequested != null) {
2643			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2644			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2645					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2646
2647			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2648			rc = true;
2649		}
2650
2651		return rc;
2652	}
2653
2654	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2655		if (mOnUpdateBlocklist != null) {
2656			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2657		}
2658	}
2659
2660	public void updateMucRosterUi() {
2661		if (mOnMucRosterUpdate != null) {
2662			mOnMucRosterUpdate.onMucRosterUpdate();
2663		}
2664	}
2665
2666	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2667		if (mOnKeyStatusUpdated != null) {
2668			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2669		}
2670	}
2671
2672	public Account findAccountByJid(final Jid accountJid) {
2673		for (Account account : this.accounts) {
2674			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2675				return account;
2676			}
2677		}
2678		return null;
2679	}
2680
2681	public Conversation findConversationByUuid(String uuid) {
2682		for (Conversation conversation : getConversations()) {
2683			if (conversation.getUuid().equals(uuid)) {
2684				return conversation;
2685			}
2686		}
2687		return null;
2688	}
2689
2690	public void markRead(final Conversation conversation) {
2691		mNotificationService.clear(conversation);
2692		final List<Message> readMessages = conversation.markRead();
2693		if (readMessages.size() > 0) {
2694			Runnable runnable = new Runnable() {
2695				@Override
2696				public void run() {
2697					for (Message message : readMessages) {
2698						databaseBackend.updateMessage(message);
2699					}
2700				}
2701			};
2702			mDatabaseExecutor.execute(runnable);
2703		}
2704		updateUnreadCountBadge();
2705	}
2706
2707	public synchronized void updateUnreadCountBadge() {
2708		int count = unreadCount();
2709		if (unreadCount != count) {
2710			Log.d(Config.LOGTAG, "update unread count to " + count);
2711			if (count > 0) {
2712				ShortcutBadger.with(getApplicationContext()).count(count);
2713			} else {
2714				ShortcutBadger.with(getApplicationContext()).remove();
2715			}
2716			unreadCount = count;
2717		}
2718	}
2719
2720	public void sendReadMarker(final Conversation conversation) {
2721		final Message markable = conversation.getLatestMarkableMessage();
2722		this.markRead(conversation);
2723		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2724			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2725			Account account = conversation.getAccount();
2726			final Jid to = markable.getCounterpart();
2727			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2728			this.sendMessagePacket(conversation.getAccount(), packet);
2729		}
2730		updateConversationUi();
2731	}
2732
2733	public SecureRandom getRNG() {
2734		return this.mRandom;
2735	}
2736
2737	public MemorizingTrustManager getMemorizingTrustManager() {
2738		return this.mMemorizingTrustManager;
2739	}
2740
2741	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2742		this.mMemorizingTrustManager = trustManager;
2743	}
2744
2745	public void updateMemorizingTrustmanager() {
2746		final MemorizingTrustManager tm;
2747		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2748		if (dontTrustSystemCAs) {
2749			tm = new MemorizingTrustManager(getApplicationContext(), null);
2750		} else {
2751			tm = new MemorizingTrustManager(getApplicationContext());
2752		}
2753		setMemorizingTrustManager(tm);
2754	}
2755
2756	public PowerManager getPowerManager() {
2757		return this.pm;
2758	}
2759
2760	public LruCache<String, Bitmap> getBitmapCache() {
2761		return this.mBitmapCache;
2762	}
2763
2764	public void syncRosterToDisk(final Account account) {
2765		Runnable runnable = new Runnable() {
2766
2767			@Override
2768			public void run() {
2769				databaseBackend.writeRoster(account.getRoster());
2770			}
2771		};
2772		mDatabaseExecutor.execute(runnable);
2773
2774	}
2775
2776	public List<String> getKnownHosts() {
2777		final List<String> hosts = new ArrayList<>();
2778		for (final Account account : getAccounts()) {
2779			if (!hosts.contains(account.getServer().toString())) {
2780				hosts.add(account.getServer().toString());
2781			}
2782			for (final Contact contact : account.getRoster().getContacts()) {
2783				if (contact.showInRoster()) {
2784					final String server = contact.getServer().toString();
2785					if (server != null && !hosts.contains(server)) {
2786						hosts.add(server);
2787					}
2788				}
2789			}
2790		}
2791		return hosts;
2792	}
2793
2794	public List<String> getKnownConferenceHosts() {
2795		final ArrayList<String> mucServers = new ArrayList<>();
2796		for (final Account account : accounts) {
2797			if (account.getXmppConnection() != null) {
2798				final String server = account.getXmppConnection().getMucServer();
2799				if (server != null && !mucServers.contains(server)) {
2800					mucServers.add(server);
2801				}
2802			}
2803		}
2804		return mucServers;
2805	}
2806
2807	public void sendMessagePacket(Account account, MessagePacket packet) {
2808		XmppConnection connection = account.getXmppConnection();
2809		if (connection != null) {
2810			connection.sendMessagePacket(packet);
2811		}
2812	}
2813
2814	public void sendPresencePacket(Account account, PresencePacket packet) {
2815		XmppConnection connection = account.getXmppConnection();
2816		if (connection != null) {
2817			connection.sendPresencePacket(packet);
2818		}
2819	}
2820
2821	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2822		XmppConnection connection = account.getXmppConnection();
2823		if (connection != null) {
2824			connection.sendCaptchaRegistryRequest(id, data);
2825		}
2826	}
2827
2828	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2829		final XmppConnection connection = account.getXmppConnection();
2830		if (connection != null) {
2831			connection.sendIqPacket(packet, callback);
2832		}
2833	}
2834
2835	public void sendPresence(final Account account) {
2836		sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2837	}
2838
2839	public void refreshAllPresences() {
2840		for (Account account : getAccounts()) {
2841			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2842				sendPresence(account);
2843			}
2844		}
2845	}
2846
2847	public void sendOfflinePresence(final Account account) {
2848		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2849	}
2850
2851	public MessageGenerator getMessageGenerator() {
2852		return this.mMessageGenerator;
2853	}
2854
2855	public PresenceGenerator getPresenceGenerator() {
2856		return this.mPresenceGenerator;
2857	}
2858
2859	public IqGenerator getIqGenerator() {
2860		return this.mIqGenerator;
2861	}
2862
2863	public IqParser getIqParser() {
2864		return this.mIqParser;
2865	}
2866
2867	public JingleConnectionManager getJingleConnectionManager() {
2868		return this.mJingleConnectionManager;
2869	}
2870
2871	public MessageArchiveService getMessageArchiveService() {
2872		return this.mMessageArchiveService;
2873	}
2874
2875	public List<Contact> findContacts(Jid jid) {
2876		ArrayList<Contact> contacts = new ArrayList<>();
2877		for (Account account : getAccounts()) {
2878			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2879				Contact contact = account.getRoster().getContactFromRoster(jid);
2880				if (contact != null) {
2881					contacts.add(contact);
2882				}
2883			}
2884		}
2885		return contacts;
2886	}
2887
2888	public NotificationService getNotificationService() {
2889		return this.mNotificationService;
2890	}
2891
2892	public HttpConnectionManager getHttpConnectionManager() {
2893		return this.mHttpConnectionManager;
2894	}
2895
2896	public void resendFailedMessages(final Message message) {
2897		final Collection<Message> messages = new ArrayList<>();
2898		Message current = message;
2899		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2900			messages.add(current);
2901			if (current.mergeable(current.next())) {
2902				current = current.next();
2903			} else {
2904				break;
2905			}
2906		}
2907		for (final Message msg : messages) {
2908			msg.setTime(System.currentTimeMillis());
2909			markMessage(msg, Message.STATUS_WAITING);
2910			this.resendMessage(msg, false);
2911		}
2912	}
2913
2914	public void clearConversationHistory(final Conversation conversation) {
2915		conversation.clearMessages();
2916		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2917		conversation.setLastClearHistory(System.currentTimeMillis());
2918		Runnable runnable = new Runnable() {
2919			@Override
2920			public void run() {
2921				databaseBackend.deleteMessagesInConversation(conversation);
2922			}
2923		};
2924		mDatabaseExecutor.execute(runnable);
2925	}
2926
2927	public void sendBlockRequest(final Blockable blockable) {
2928		if (blockable != null && blockable.getBlockedJid() != null) {
2929			final Jid jid = blockable.getBlockedJid();
2930			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2931
2932				@Override
2933				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2934					if (packet.getType() == IqPacket.TYPE.RESULT) {
2935						account.getBlocklist().add(jid);
2936						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2937					}
2938				}
2939			});
2940		}
2941	}
2942
2943	public void sendUnblockRequest(final Blockable blockable) {
2944		if (blockable != null && blockable.getJid() != null) {
2945			final Jid jid = blockable.getBlockedJid();
2946			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2947				@Override
2948				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2949					if (packet.getType() == IqPacket.TYPE.RESULT) {
2950						account.getBlocklist().remove(jid);
2951						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2952					}
2953				}
2954			});
2955		}
2956	}
2957
2958	public void publishDisplayName(Account account) {
2959		String displayName = account.getDisplayName();
2960		if (displayName != null && !displayName.isEmpty()) {
2961			IqPacket publish = mIqGenerator.publishNick(displayName);
2962			sendIqPacket(account, publish, new OnIqPacketReceived() {
2963				@Override
2964				public void onIqPacketReceived(Account account, IqPacket packet) {
2965					if (packet.getType() == IqPacket.TYPE.ERROR) {
2966						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
2967					}
2968				}
2969			});
2970		}
2971	}
2972
2973	private ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String,String> key) {
2974		ServiceDiscoveryResult result = discoCache.get(key);
2975		if (result != null) {
2976			return result;
2977		} else {
2978			result = databaseBackend.findDiscoveryResult(key.first, key.second);
2979			if (result != null) {
2980				discoCache.put(key, result);
2981			}
2982			return result;
2983		}
2984	}
2985
2986	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
2987		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
2988		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
2989		if (disco != null) {
2990			presence.setServiceDiscoveryResult(disco);
2991		} else {
2992			if (!account.inProgressDiscoFetches.contains(key)) {
2993				account.inProgressDiscoFetches.add(key);
2994				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2995				request.setTo(jid);
2996				request.query("http://jabber.org/protocol/disco#info");
2997				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
2998				sendIqPacket(account, request, new OnIqPacketReceived() {
2999					@Override
3000					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3001						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3002							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3003							if (presence.getVer().equals(disco.getVer())) {
3004								databaseBackend.insertDiscoveryResult(disco);
3005								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3006							} else {
3007								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid+" "+presence.getVer()+" vs "+disco.getVer());
3008							}
3009						}
3010						account.inProgressDiscoFetches.remove(key);
3011					}
3012				});
3013			}
3014		}
3015	}
3016
3017	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3018		for(Contact contact : roster.getContacts()) {
3019			for(Presence presence : contact.getPresences().getPresences().values()) {
3020				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3021					presence.setServiceDiscoveryResult(disco);
3022				}
3023			}
3024		}
3025	}
3026
3027	public interface OnAccountCreated {
3028		void onAccountCreated(Account account);
3029
3030		void informUser(int r);
3031	}
3032
3033	public interface OnMoreMessagesLoaded {
3034		void onMoreMessagesLoaded(int count, Conversation conversation);
3035
3036		void informUser(int r);
3037	}
3038
3039	public interface OnAccountPasswordChanged {
3040		void onPasswordChangeSucceeded();
3041
3042		void onPasswordChangeFailed();
3043	}
3044
3045	public interface OnAffiliationChanged {
3046		void onAffiliationChangedSuccessful(Jid jid);
3047
3048		void onAffiliationChangeFailed(Jid jid, int resId);
3049	}
3050
3051	public interface OnRoleChanged {
3052		void onRoleChangedSuccessful(String nick);
3053
3054		void onRoleChangeFailed(String nick, int resid);
3055	}
3056
3057	public interface OnConversationUpdate {
3058		void onConversationUpdate();
3059	}
3060
3061	public interface OnAccountUpdate {
3062		void onAccountUpdate();
3063	}
3064
3065	public interface OnCaptchaRequested {
3066		void onCaptchaRequested(Account account,
3067								String id,
3068								Data data,
3069								Bitmap captcha);
3070	}
3071
3072	public interface OnRosterUpdate {
3073		void onRosterUpdate();
3074	}
3075
3076	public interface OnMucRosterUpdate {
3077		void onMucRosterUpdate();
3078	}
3079
3080	public interface OnConferenceConfigurationFetched {
3081		void onConferenceConfigurationFetched(Conversation conversation);
3082
3083		void onFetchFailed(Conversation conversation, Element error);
3084	}
3085
3086	public interface OnConferenceJoined {
3087		void onConferenceJoined(Conversation conversation);
3088	}
3089
3090	public interface OnConferenceOptionsPushed {
3091		void onPushSucceeded();
3092
3093		void onPushFailed();
3094	}
3095
3096	public interface OnShowErrorToast {
3097		void onShowErrorToast(int resId);
3098	}
3099
3100	public class XmppConnectionBinder extends Binder {
3101		public XmppConnectionService getService() {
3102			return XmppConnectionService.this;
3103		}
3104	}
3105}