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		}
1219		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1220		Runnable runnable = new Runnable() {
1221			@Override
1222			public void run() {
1223				final Account account = conversation.getAccount();
1224				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1225				if (messages.size() > 0) {
1226					conversation.addAll(0, messages);
1227					checkDeletedFiles(conversation);
1228					callback.onMoreMessagesLoaded(messages.size(), conversation);
1229				} else if (conversation.hasMessagesLeftOnServer()
1230						&& account.isOnlineAndConnected()) {
1231					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1232							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1233						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1234						if (query != null) {
1235							query.setCallback(callback);
1236						}
1237						callback.informUser(R.string.fetching_history_from_server);
1238					}
1239				}
1240			}
1241		};
1242		mDatabaseExecutor.execute(runnable);
1243	}
1244
1245	public List<Account> getAccounts() {
1246		return this.accounts;
1247	}
1248
1249	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1250		for (final Conversation conversation : haystack) {
1251			if (conversation.getContact() == contact) {
1252				return conversation;
1253			}
1254		}
1255		return null;
1256	}
1257
1258	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1259		if (jid == null) {
1260			return null;
1261		}
1262		for (final Conversation conversation : haystack) {
1263			if ((account == null || conversation.getAccount() == account)
1264					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1265				return conversation;
1266			}
1267		}
1268		return null;
1269	}
1270
1271	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1272		return this.findOrCreateConversation(account, jid, muc, null);
1273	}
1274
1275	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1276		synchronized (this.conversations) {
1277			Conversation conversation = find(account, jid);
1278			if (conversation != null) {
1279				return conversation;
1280			}
1281			conversation = databaseBackend.findConversation(account, jid);
1282			if (conversation != null) {
1283				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1284				conversation.setAccount(account);
1285				if (muc) {
1286					conversation.setMode(Conversation.MODE_MULTI);
1287					conversation.setContactJid(jid);
1288				} else {
1289					conversation.setMode(Conversation.MODE_SINGLE);
1290					conversation.setContactJid(jid.toBareJid());
1291				}
1292				conversation.setNextEncryption(-1);
1293				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1294				this.databaseBackend.updateConversation(conversation);
1295			} else {
1296				String conversationName;
1297				Contact contact = account.getRoster().getContact(jid);
1298				if (contact != null) {
1299					conversationName = contact.getDisplayName();
1300				} else {
1301					conversationName = jid.getLocalpart();
1302				}
1303				if (muc) {
1304					conversation = new Conversation(conversationName, account, jid,
1305							Conversation.MODE_MULTI);
1306				} else {
1307					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1308							Conversation.MODE_SINGLE);
1309				}
1310				this.databaseBackend.createConversation(conversation);
1311			}
1312			if (account.getXmppConnection() != null
1313					&& account.getXmppConnection().getFeatures().mam()
1314					&& !muc) {
1315				if (query == null) {
1316					this.mMessageArchiveService.query(conversation);
1317				} else {
1318					if (query.getConversation() == null) {
1319						this.mMessageArchiveService.query(conversation, query.getStart());
1320					}
1321				}
1322			}
1323			checkDeletedFiles(conversation);
1324			this.conversations.add(conversation);
1325			updateConversationUi();
1326			return conversation;
1327		}
1328	}
1329
1330	public void archiveConversation(Conversation conversation) {
1331		getNotificationService().clear(conversation);
1332		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1333		conversation.setNextEncryption(-1);
1334		synchronized (this.conversations) {
1335			if (conversation.getMode() == Conversation.MODE_MULTI) {
1336				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1337					Bookmark bookmark = conversation.getBookmark();
1338					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1339						bookmark.setAutojoin(false);
1340						pushBookmarks(bookmark.getAccount());
1341					}
1342				}
1343				leaveMuc(conversation);
1344			} else {
1345				conversation.endOtrIfNeeded();
1346				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1347					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1348					sendPresencePacket(
1349							conversation.getAccount(),
1350							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1351					);
1352				}
1353			}
1354			this.databaseBackend.updateConversation(conversation);
1355			this.conversations.remove(conversation);
1356			updateConversationUi();
1357		}
1358	}
1359
1360	public void createAccount(final Account account) {
1361		account.initAccountServices(this);
1362		databaseBackend.createAccount(account);
1363		this.accounts.add(account);
1364		this.reconnectAccountInBackground(account);
1365		updateAccountUi();
1366	}
1367
1368	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1369		new Thread(new Runnable() {
1370			@Override
1371			public void run() {
1372				try {
1373					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1374					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1375					if (findAccountByJid(info.first) == null) {
1376						Account account = new Account(info.first, "");
1377						account.setPrivateKeyAlias(alias);
1378						account.setOption(Account.OPTION_DISABLED, true);
1379						account.setDisplayName(info.second);
1380						createAccount(account);
1381						callback.onAccountCreated(account);
1382						if (Config.X509_VERIFICATION) {
1383							try {
1384								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1385							} catch (CertificateException e) {
1386								callback.informUser(R.string.certificate_chain_is_not_trusted);
1387							}
1388						}
1389					} else {
1390						callback.informUser(R.string.account_already_exists);
1391					}
1392				} catch (Exception e) {
1393					e.printStackTrace();
1394					callback.informUser(R.string.unable_to_parse_certificate);
1395				}
1396			}
1397		}).start();
1398
1399	}
1400
1401	public void updateKeyInAccount(final Account account, final String alias) {
1402		Log.d(Config.LOGTAG, "update key in account " + alias);
1403		try {
1404			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1405			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1406			if (account.getJid().toBareJid().equals(info.first)) {
1407				account.setPrivateKeyAlias(alias);
1408				account.setDisplayName(info.second);
1409				databaseBackend.updateAccount(account);
1410				if (Config.X509_VERIFICATION) {
1411					try {
1412						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1413					} catch (CertificateException e) {
1414						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1415					}
1416					account.getAxolotlService().regenerateKeys(true);
1417				}
1418			} else {
1419				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1420			}
1421		} catch (Exception e) {
1422			e.printStackTrace();
1423		}
1424	}
1425
1426	public void updateAccount(final Account account) {
1427		this.statusListener.onStatusChanged(account);
1428		databaseBackend.updateAccount(account);
1429		reconnectAccountInBackground(account);
1430		updateAccountUi();
1431		getNotificationService().updateErrorNotification();
1432	}
1433
1434	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1435		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1436		sendIqPacket(account, iq, new OnIqPacketReceived() {
1437			@Override
1438			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1439				if (packet.getType() == IqPacket.TYPE.RESULT) {
1440					account.setPassword(newPassword);
1441					databaseBackend.updateAccount(account);
1442					callback.onPasswordChangeSucceeded();
1443				} else {
1444					callback.onPasswordChangeFailed();
1445				}
1446			}
1447		});
1448	}
1449
1450	public void deleteAccount(final Account account) {
1451		synchronized (this.conversations) {
1452			for (final Conversation conversation : conversations) {
1453				if (conversation.getAccount() == account) {
1454					if (conversation.getMode() == Conversation.MODE_MULTI) {
1455						leaveMuc(conversation);
1456					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1457						conversation.endOtrIfNeeded();
1458					}
1459					conversations.remove(conversation);
1460				}
1461			}
1462			if (account.getXmppConnection() != null) {
1463				this.disconnect(account, true);
1464			}
1465			Runnable runnable = new Runnable() {
1466				@Override
1467				public void run() {
1468					databaseBackend.deleteAccount(account);
1469				}
1470			};
1471			mDatabaseExecutor.execute(runnable);
1472			this.accounts.remove(account);
1473			updateAccountUi();
1474			getNotificationService().updateErrorNotification();
1475		}
1476	}
1477
1478	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1479		synchronized (this) {
1480			if (checkListeners()) {
1481				switchToForeground();
1482			}
1483			this.mOnConversationUpdate = listener;
1484			this.mNotificationService.setIsInForeground(true);
1485			if (this.convChangedListenerCount < 2) {
1486				this.convChangedListenerCount++;
1487			}
1488		}
1489	}
1490
1491	public void removeOnConversationListChangedListener() {
1492		synchronized (this) {
1493			this.convChangedListenerCount--;
1494			if (this.convChangedListenerCount <= 0) {
1495				this.convChangedListenerCount = 0;
1496				this.mOnConversationUpdate = null;
1497				this.mNotificationService.setIsInForeground(false);
1498				if (checkListeners()) {
1499					switchToBackground();
1500				}
1501			}
1502		}
1503	}
1504
1505	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1506		synchronized (this) {
1507			if (checkListeners()) {
1508				switchToForeground();
1509			}
1510			this.mOnShowErrorToast = onShowErrorToast;
1511			if (this.showErrorToastListenerCount < 2) {
1512				this.showErrorToastListenerCount++;
1513			}
1514		}
1515		this.mOnShowErrorToast = onShowErrorToast;
1516	}
1517
1518	public void removeOnShowErrorToastListener() {
1519		synchronized (this) {
1520			this.showErrorToastListenerCount--;
1521			if (this.showErrorToastListenerCount <= 0) {
1522				this.showErrorToastListenerCount = 0;
1523				this.mOnShowErrorToast = null;
1524				if (checkListeners()) {
1525					switchToBackground();
1526				}
1527			}
1528		}
1529	}
1530
1531	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1532		synchronized (this) {
1533			if (checkListeners()) {
1534				switchToForeground();
1535			}
1536			this.mOnAccountUpdate = listener;
1537			if (this.accountChangedListenerCount < 2) {
1538				this.accountChangedListenerCount++;
1539			}
1540		}
1541	}
1542
1543	public void removeOnAccountListChangedListener() {
1544		synchronized (this) {
1545			this.accountChangedListenerCount--;
1546			if (this.accountChangedListenerCount <= 0) {
1547				this.mOnAccountUpdate = null;
1548				this.accountChangedListenerCount = 0;
1549				if (checkListeners()) {
1550					switchToBackground();
1551				}
1552			}
1553		}
1554	}
1555
1556	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1557		synchronized (this) {
1558			if (checkListeners()) {
1559				switchToForeground();
1560			}
1561			this.mOnCaptchaRequested = listener;
1562			if (this.captchaRequestedListenerCount < 2) {
1563				this.captchaRequestedListenerCount++;
1564			}
1565		}
1566	}
1567
1568	public void removeOnCaptchaRequestedListener() {
1569		synchronized (this) {
1570			this.captchaRequestedListenerCount--;
1571			if (this.captchaRequestedListenerCount <= 0) {
1572				this.mOnCaptchaRequested = null;
1573				this.captchaRequestedListenerCount = 0;
1574				if (checkListeners()) {
1575					switchToBackground();
1576				}
1577			}
1578		}
1579	}
1580
1581	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1582		synchronized (this) {
1583			if (checkListeners()) {
1584				switchToForeground();
1585			}
1586			this.mOnRosterUpdate = listener;
1587			if (this.rosterChangedListenerCount < 2) {
1588				this.rosterChangedListenerCount++;
1589			}
1590		}
1591	}
1592
1593	public void removeOnRosterUpdateListener() {
1594		synchronized (this) {
1595			this.rosterChangedListenerCount--;
1596			if (this.rosterChangedListenerCount <= 0) {
1597				this.rosterChangedListenerCount = 0;
1598				this.mOnRosterUpdate = null;
1599				if (checkListeners()) {
1600					switchToBackground();
1601				}
1602			}
1603		}
1604	}
1605
1606	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1607		synchronized (this) {
1608			if (checkListeners()) {
1609				switchToForeground();
1610			}
1611			this.mOnUpdateBlocklist = listener;
1612			if (this.updateBlocklistListenerCount < 2) {
1613				this.updateBlocklistListenerCount++;
1614			}
1615		}
1616	}
1617
1618	public void removeOnUpdateBlocklistListener() {
1619		synchronized (this) {
1620			this.updateBlocklistListenerCount--;
1621			if (this.updateBlocklistListenerCount <= 0) {
1622				this.updateBlocklistListenerCount = 0;
1623				this.mOnUpdateBlocklist = null;
1624				if (checkListeners()) {
1625					switchToBackground();
1626				}
1627			}
1628		}
1629	}
1630
1631	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1632		synchronized (this) {
1633			if (checkListeners()) {
1634				switchToForeground();
1635			}
1636			this.mOnKeyStatusUpdated = listener;
1637			if (this.keyStatusUpdatedListenerCount < 2) {
1638				this.keyStatusUpdatedListenerCount++;
1639			}
1640		}
1641	}
1642
1643	public void removeOnNewKeysAvailableListener() {
1644		synchronized (this) {
1645			this.keyStatusUpdatedListenerCount--;
1646			if (this.keyStatusUpdatedListenerCount <= 0) {
1647				this.keyStatusUpdatedListenerCount = 0;
1648				this.mOnKeyStatusUpdated = null;
1649				if (checkListeners()) {
1650					switchToBackground();
1651				}
1652			}
1653		}
1654	}
1655
1656	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1657		synchronized (this) {
1658			if (checkListeners()) {
1659				switchToForeground();
1660			}
1661			this.mOnMucRosterUpdate = listener;
1662			if (this.mucRosterChangedListenerCount < 2) {
1663				this.mucRosterChangedListenerCount++;
1664			}
1665		}
1666	}
1667
1668	public void removeOnMucRosterUpdateListener() {
1669		synchronized (this) {
1670			this.mucRosterChangedListenerCount--;
1671			if (this.mucRosterChangedListenerCount <= 0) {
1672				this.mucRosterChangedListenerCount = 0;
1673				this.mOnMucRosterUpdate = null;
1674				if (checkListeners()) {
1675					switchToBackground();
1676				}
1677			}
1678		}
1679	}
1680
1681	private boolean checkListeners() {
1682		return (this.mOnAccountUpdate == null
1683				&& this.mOnConversationUpdate == null
1684				&& this.mOnRosterUpdate == null
1685				&& this.mOnCaptchaRequested == null
1686				&& this.mOnUpdateBlocklist == null
1687				&& this.mOnShowErrorToast == null
1688				&& this.mOnKeyStatusUpdated == null);
1689	}
1690
1691	private void switchToForeground() {
1692		for (Conversation conversation : getConversations()) {
1693			conversation.setIncomingChatState(ChatState.ACTIVE);
1694		}
1695		for (Account account : getAccounts()) {
1696			if (account.getStatus() == Account.State.ONLINE) {
1697				XmppConnection connection = account.getXmppConnection();
1698				if (connection != null && connection.getFeatures().csi()) {
1699					connection.sendActive();
1700				}
1701			}
1702		}
1703		Log.d(Config.LOGTAG, "app switched into foreground");
1704	}
1705
1706	private void switchToBackground() {
1707		for (Account account : getAccounts()) {
1708			if (account.getStatus() == Account.State.ONLINE) {
1709				XmppConnection connection = account.getXmppConnection();
1710				if (connection != null && connection.getFeatures().csi()) {
1711					connection.sendInactive();
1712				}
1713			}
1714		}
1715		this.mNotificationService.setIsInForeground(false);
1716		Log.d(Config.LOGTAG, "app switched into background");
1717	}
1718
1719	private void connectMultiModeConversations(Account account) {
1720		List<Conversation> conversations = getConversations();
1721		for (Conversation conversation : conversations) {
1722			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1723				joinMuc(conversation, true, null);
1724			}
1725		}
1726	}
1727
1728	public void joinMuc(Conversation conversation) {
1729		joinMuc(conversation, false, null);
1730	}
1731
1732	private void joinMuc(Conversation conversation, boolean now, final OnConferenceJoined onConferenceJoined) {
1733		Account account = conversation.getAccount();
1734		account.pendingConferenceJoins.remove(conversation);
1735		account.pendingConferenceLeaves.remove(conversation);
1736		if (account.getStatus() == Account.State.ONLINE || now) {
1737			conversation.resetMucOptions();
1738			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1739
1740				private void join(Conversation conversation) {
1741					Account account = conversation.getAccount();
1742					final String nick = conversation.getMucOptions().getProposedNick();
1743					final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1744					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1745					PresencePacket packet = new PresencePacket();
1746					packet.setFrom(conversation.getAccount().getJid());
1747					packet.setTo(joinJid);
1748					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1749					if (conversation.getMucOptions().getPassword() != null) {
1750						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1751					}
1752
1753					if (conversation.getMucOptions().mamSupport()) {
1754						// Use MAM instead of the limited muc history to get history
1755						x.addChild("history").setAttribute("maxchars", "0");
1756					} else {
1757						// Fallback to muc history
1758						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1759					}
1760					String sig = account.getPgpSignature();
1761					if (sig != null) {
1762						packet.addChild("x", "jabber:x:signed").setContent(sig);
1763					}
1764					sendPresencePacket(account, packet);
1765					if (onConferenceJoined != null) {
1766						onConferenceJoined.onConferenceJoined(conversation);
1767					}
1768					if (!joinJid.equals(conversation.getJid())) {
1769						conversation.setContactJid(joinJid);
1770						databaseBackend.updateConversation(conversation);
1771					}
1772					conversation.setHasMessagesLeftOnServer(false);
1773					if (conversation.getMucOptions().mamSupport()) {
1774						getMessageArchiveService().catchupMUC(conversation);
1775					}
1776				}
1777
1778				@Override
1779				public void onConferenceConfigurationFetched(Conversation conversation) {
1780					join(conversation);
1781				}
1782
1783				@Override
1784				public void onFetchFailed(final Conversation conversation, Element error) {
1785					join(conversation);
1786					fetchConferenceConfiguration(conversation);
1787				}
1788			});
1789
1790		} else {
1791			account.pendingConferenceJoins.add(conversation);
1792		}
1793	}
1794
1795	public void providePasswordForMuc(Conversation conversation, String password) {
1796		if (conversation.getMode() == Conversation.MODE_MULTI) {
1797			conversation.getMucOptions().setPassword(password);
1798			if (conversation.getBookmark() != null) {
1799				if (respectAutojoin()) {
1800					conversation.getBookmark().setAutojoin(true);
1801				}
1802				pushBookmarks(conversation.getAccount());
1803			}
1804			databaseBackend.updateConversation(conversation);
1805			joinMuc(conversation);
1806		}
1807	}
1808
1809	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1810		final MucOptions options = conversation.getMucOptions();
1811		final Jid joinJid = options.createJoinJid(nick);
1812		if (options.online()) {
1813			Account account = conversation.getAccount();
1814			options.setOnRenameListener(new OnRenameListener() {
1815
1816				@Override
1817				public void onSuccess() {
1818					conversation.setContactJid(joinJid);
1819					databaseBackend.updateConversation(conversation);
1820					Bookmark bookmark = conversation.getBookmark();
1821					if (bookmark != null) {
1822						bookmark.setNick(nick);
1823						pushBookmarks(bookmark.getAccount());
1824					}
1825					callback.success(conversation);
1826				}
1827
1828				@Override
1829				public void onFailure() {
1830					callback.error(R.string.nick_in_use, conversation);
1831				}
1832			});
1833
1834			PresencePacket packet = new PresencePacket();
1835			packet.setTo(joinJid);
1836			packet.setFrom(conversation.getAccount().getJid());
1837
1838			String sig = account.getPgpSignature();
1839			if (sig != null) {
1840				packet.addChild("status").setContent("online");
1841				packet.addChild("x", "jabber:x:signed").setContent(sig);
1842			}
1843			sendPresencePacket(account, packet);
1844		} else {
1845			conversation.setContactJid(joinJid);
1846			databaseBackend.updateConversation(conversation);
1847			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1848				Bookmark bookmark = conversation.getBookmark();
1849				if (bookmark != null) {
1850					bookmark.setNick(nick);
1851					pushBookmarks(bookmark.getAccount());
1852				}
1853				joinMuc(conversation);
1854			}
1855		}
1856	}
1857
1858	public void leaveMuc(Conversation conversation) {
1859		leaveMuc(conversation, false);
1860	}
1861
1862	private void leaveMuc(Conversation conversation, boolean now) {
1863		Account account = conversation.getAccount();
1864		account.pendingConferenceJoins.remove(conversation);
1865		account.pendingConferenceLeaves.remove(conversation);
1866		if (account.getStatus() == Account.State.ONLINE || now) {
1867			PresencePacket packet = new PresencePacket();
1868			packet.setTo(conversation.getJid());
1869			packet.setFrom(conversation.getAccount().getJid());
1870			packet.setAttribute("type", "unavailable");
1871			sendPresencePacket(conversation.getAccount(), packet);
1872			conversation.getMucOptions().setOffline();
1873			conversation.deregisterWithBookmark();
1874			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1875					+ ": leaving muc " + conversation.getJid());
1876		} else {
1877			account.pendingConferenceLeaves.add(conversation);
1878		}
1879	}
1880
1881	private String findConferenceServer(final Account account) {
1882		String server;
1883		if (account.getXmppConnection() != null) {
1884			server = account.getXmppConnection().getMucServer();
1885			if (server != null) {
1886				return server;
1887			}
1888		}
1889		for (Account other : getAccounts()) {
1890			if (other != account && other.getXmppConnection() != null) {
1891				server = other.getXmppConnection().getMucServer();
1892				if (server != null) {
1893					return server;
1894				}
1895			}
1896		}
1897		return null;
1898	}
1899
1900	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1901		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1902		if (account.getStatus() == Account.State.ONLINE) {
1903			try {
1904				String server = findConferenceServer(account);
1905				if (server == null) {
1906					if (callback != null) {
1907						callback.error(R.string.no_conference_server_found, null);
1908					}
1909					return;
1910				}
1911				String name = new BigInteger(75, getRNG()).toString(32);
1912				Jid jid = Jid.fromParts(name, server, null);
1913				final Conversation conversation = findOrCreateConversation(account, jid, true);
1914				joinMuc(conversation, true, new OnConferenceJoined() {
1915					@Override
1916					public void onConferenceJoined(final Conversation conversation) {
1917						Bundle options = new Bundle();
1918						options.putString("muc#roomconfig_persistentroom", "1");
1919						options.putString("muc#roomconfig_membersonly", "1");
1920						options.putString("muc#roomconfig_publicroom", "0");
1921						options.putString("muc#roomconfig_whois", "anyone");
1922						pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1923							@Override
1924							public void onPushSucceeded() {
1925								for (Jid invite : jids) {
1926									invite(conversation, invite);
1927								}
1928								if (account.countPresences() > 1) {
1929									directInvite(conversation, account.getJid().toBareJid());
1930								}
1931								if (callback != null) {
1932									callback.success(conversation);
1933								}
1934							}
1935
1936							@Override
1937							public void onPushFailed() {
1938								if (callback != null) {
1939									callback.error(R.string.conference_creation_failed, conversation);
1940								}
1941							}
1942						});
1943					}
1944				});
1945			} catch (InvalidJidException e) {
1946				if (callback != null) {
1947					callback.error(R.string.conference_creation_failed, null);
1948				}
1949			}
1950		} else {
1951			if (callback != null) {
1952				callback.error(R.string.not_connected_try_again, null);
1953			}
1954		}
1955	}
1956
1957	public void fetchConferenceConfiguration(final Conversation conversation) {
1958		fetchConferenceConfiguration(conversation, null);
1959	}
1960
1961	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1962		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1963		request.setTo(conversation.getJid().toBareJid());
1964		request.query("http://jabber.org/protocol/disco#info");
1965		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1966			@Override
1967			public void onIqPacketReceived(Account account, IqPacket packet) {
1968				if (packet.getType() == IqPacket.TYPE.RESULT) {
1969					ArrayList<String> features = new ArrayList<>();
1970					Element query = packet.query();
1971					for (Element child : query.getChildren()) {
1972						if (child != null && child.getName().equals("feature")) {
1973							String var = child.getAttribute("var");
1974							if (var != null) {
1975								features.add(var);
1976							}
1977						}
1978					}
1979					Element form = query.findChild("x", "jabber:x:data");
1980					if (form != null) {
1981						conversation.getMucOptions().updateFormData(Data.parse(form));
1982					}
1983					conversation.getMucOptions().updateFeatures(features);
1984					if (callback != null) {
1985						callback.onConferenceConfigurationFetched(conversation);
1986					}
1987					updateConversationUi();
1988				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
1989					if (callback != null) {
1990						callback.onFetchFailed(conversation, packet.getError());
1991					}
1992				}
1993			}
1994		});
1995	}
1996
1997	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1998		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1999		request.setTo(conversation.getJid().toBareJid());
2000		request.query("http://jabber.org/protocol/muc#owner");
2001		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2002			@Override
2003			public void onIqPacketReceived(Account account, IqPacket packet) {
2004				if (packet.getType() == IqPacket.TYPE.RESULT) {
2005					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2006					for (Field field : data.getFields()) {
2007						if (options.containsKey(field.getFieldName())) {
2008							field.setValue(options.getString(field.getFieldName()));
2009						}
2010					}
2011					data.submit();
2012					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2013					set.setTo(conversation.getJid().toBareJid());
2014					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2015					sendIqPacket(account, set, new OnIqPacketReceived() {
2016						@Override
2017						public void onIqPacketReceived(Account account, IqPacket packet) {
2018							if (callback != null) {
2019								if (packet.getType() == IqPacket.TYPE.RESULT) {
2020									callback.onPushSucceeded();
2021								} else {
2022									callback.onPushFailed();
2023								}
2024							}
2025						}
2026					});
2027				} else {
2028					if (callback != null) {
2029						callback.onPushFailed();
2030					}
2031				}
2032			}
2033		});
2034	}
2035
2036	public void pushSubjectToConference(final Conversation conference, final String subject) {
2037		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2038		this.sendMessagePacket(conference.getAccount(), packet);
2039		final MucOptions mucOptions = conference.getMucOptions();
2040		final MucOptions.User self = mucOptions.getSelf();
2041		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2042			Bundle options = new Bundle();
2043			options.putString("muc#roomconfig_persistentroom", "1");
2044			this.pushConferenceConfiguration(conference, options, null);
2045		}
2046	}
2047
2048	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2049		final Jid jid = user.toBareJid();
2050		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2051		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2052			@Override
2053			public void onIqPacketReceived(Account account, IqPacket packet) {
2054				if (packet.getType() == IqPacket.TYPE.RESULT) {
2055					callback.onAffiliationChangedSuccessful(jid);
2056				} else {
2057					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2058				}
2059			}
2060		});
2061	}
2062
2063	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2064		List<Jid> jids = new ArrayList<>();
2065		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2066			if (user.getAffiliation() == before && user.getJid() != null) {
2067				jids.add(user.getJid());
2068			}
2069		}
2070		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2071		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2072	}
2073
2074	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2075		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2076		Log.d(Config.LOGTAG, request.toString());
2077		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2078			@Override
2079			public void onIqPacketReceived(Account account, IqPacket packet) {
2080				Log.d(Config.LOGTAG, packet.toString());
2081				if (packet.getType() == IqPacket.TYPE.RESULT) {
2082					callback.onRoleChangedSuccessful(nick);
2083				} else {
2084					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2085				}
2086			}
2087		});
2088	}
2089
2090	private void disconnect(Account account, boolean force) {
2091		if ((account.getStatus() == Account.State.ONLINE)
2092				|| (account.getStatus() == Account.State.DISABLED)) {
2093			if (!force) {
2094				List<Conversation> conversations = getConversations();
2095				for (Conversation conversation : conversations) {
2096					if (conversation.getAccount() == account) {
2097						if (conversation.getMode() == Conversation.MODE_MULTI) {
2098							leaveMuc(conversation, true);
2099						} else {
2100							if (conversation.endOtrIfNeeded()) {
2101								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2102										+ ": ended otr session with "
2103										+ conversation.getJid());
2104							}
2105						}
2106					}
2107				}
2108				sendOfflinePresence(account);
2109			}
2110			account.getXmppConnection().disconnect(force);
2111		}
2112	}
2113
2114	@Override
2115	public IBinder onBind(Intent intent) {
2116		return mBinder;
2117	}
2118
2119	public void updateMessage(Message message) {
2120		databaseBackend.updateMessage(message);
2121		updateConversationUi();
2122	}
2123
2124	protected void syncDirtyContacts(Account account) {
2125		for (Contact contact : account.getRoster().getContacts()) {
2126			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2127				pushContactToServer(contact);
2128			}
2129			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2130				deleteContactOnServer(contact);
2131			}
2132		}
2133	}
2134
2135	public void createContact(Contact contact) {
2136		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2137		if (autoGrant) {
2138			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2139			contact.setOption(Contact.Options.ASKING);
2140		}
2141		pushContactToServer(contact);
2142	}
2143
2144	public void onOtrSessionEstablished(Conversation conversation) {
2145		final Account account = conversation.getAccount();
2146		final Session otrSession = conversation.getOtrSession();
2147		Log.d(Config.LOGTAG,
2148				account.getJid().toBareJid() + " otr session established with "
2149						+ conversation.getJid() + "/"
2150						+ otrSession.getSessionID().getUserID());
2151		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2152
2153			@Override
2154			public void onMessageFound(Message message) {
2155				SessionID id = otrSession.getSessionID();
2156				try {
2157					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2158				} catch (InvalidJidException e) {
2159					return;
2160				}
2161				if (message.needsUploading()) {
2162					mJingleConnectionManager.createNewConnection(message);
2163				} else {
2164					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2165					if (outPacket != null) {
2166						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2167						message.setStatus(Message.STATUS_SEND);
2168						databaseBackend.updateMessage(message);
2169						sendMessagePacket(account, outPacket);
2170					}
2171				}
2172				updateConversationUi();
2173			}
2174		});
2175	}
2176
2177	public boolean renewSymmetricKey(Conversation conversation) {
2178		Account account = conversation.getAccount();
2179		byte[] symmetricKey = new byte[32];
2180		this.mRandom.nextBytes(symmetricKey);
2181		Session otrSession = conversation.getOtrSession();
2182		if (otrSession != null) {
2183			MessagePacket packet = new MessagePacket();
2184			packet.setType(MessagePacket.TYPE_CHAT);
2185			packet.setFrom(account.getJid());
2186			MessageGenerator.addMessageHints(packet);
2187			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2188					+ otrSession.getSessionID().getUserID());
2189			try {
2190				packet.setBody(otrSession
2191						.transformSending(CryptoHelper.FILETRANSFER
2192								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2193				sendMessagePacket(account, packet);
2194				conversation.setSymmetricKey(symmetricKey);
2195				return true;
2196			} catch (OtrException e) {
2197				return false;
2198			}
2199		}
2200		return false;
2201	}
2202
2203	public void pushContactToServer(final Contact contact) {
2204		contact.resetOption(Contact.Options.DIRTY_DELETE);
2205		contact.setOption(Contact.Options.DIRTY_PUSH);
2206		final Account account = contact.getAccount();
2207		if (account.getStatus() == Account.State.ONLINE) {
2208			final boolean ask = contact.getOption(Contact.Options.ASKING);
2209			final boolean sendUpdates = contact
2210					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2211					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2212			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2213			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2214			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2215			if (sendUpdates) {
2216				sendPresencePacket(account,
2217						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2218			}
2219			if (ask) {
2220				sendPresencePacket(account,
2221						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2222			}
2223		}
2224	}
2225
2226	public void publishAvatar(final Account account,
2227							  final Uri image,
2228							  final UiCallback<Avatar> callback) {
2229		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2230		final int size = Config.AVATAR_SIZE;
2231		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2232		if (avatar != null) {
2233			avatar.height = size;
2234			avatar.width = size;
2235			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2236				avatar.type = "image/webp";
2237			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2238				avatar.type = "image/jpeg";
2239			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2240				avatar.type = "image/png";
2241			}
2242			if (!getFileBackend().save(avatar)) {
2243				callback.error(R.string.error_saving_avatar, avatar);
2244				return;
2245			}
2246			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2247			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2248
2249				@Override
2250				public void onIqPacketReceived(Account account, IqPacket result) {
2251					if (result.getType() == IqPacket.TYPE.RESULT) {
2252						final IqPacket packet = XmppConnectionService.this.mIqGenerator
2253								.publishAvatarMetadata(avatar);
2254						sendIqPacket(account, packet, new OnIqPacketReceived() {
2255							@Override
2256							public void onIqPacketReceived(Account account, IqPacket result) {
2257								if (result.getType() == IqPacket.TYPE.RESULT) {
2258									if (account.setAvatar(avatar.getFilename())) {
2259										getAvatarService().clear(account);
2260										databaseBackend.updateAccount(account);
2261									}
2262									callback.success(avatar);
2263								} else {
2264									callback.error(
2265											R.string.error_publish_avatar_server_reject,
2266											avatar);
2267								}
2268							}
2269						});
2270					} else {
2271						callback.error(
2272								R.string.error_publish_avatar_server_reject,
2273								avatar);
2274					}
2275				}
2276			});
2277		} else {
2278			callback.error(R.string.error_publish_avatar_converting, null);
2279		}
2280	}
2281
2282	public void fetchAvatar(Account account, Avatar avatar) {
2283		fetchAvatar(account, avatar, null);
2284	}
2285
2286	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2287		final String KEY = generateFetchKey(account, avatar);
2288		synchronized (this.mInProgressAvatarFetches) {
2289			if (this.mInProgressAvatarFetches.contains(KEY)) {
2290				return;
2291			} else {
2292				switch (avatar.origin) {
2293					case PEP:
2294						this.mInProgressAvatarFetches.add(KEY);
2295						fetchAvatarPep(account, avatar, callback);
2296						break;
2297					case VCARD:
2298						this.mInProgressAvatarFetches.add(KEY);
2299						fetchAvatarVcard(account, avatar, callback);
2300						break;
2301				}
2302			}
2303		}
2304	}
2305
2306	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2307		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2308		sendIqPacket(account, packet, new OnIqPacketReceived() {
2309
2310			@Override
2311			public void onIqPacketReceived(Account account, IqPacket result) {
2312				synchronized (mInProgressAvatarFetches) {
2313					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2314				}
2315				final String ERROR = account.getJid().toBareJid()
2316						+ ": fetching avatar for " + avatar.owner + " failed ";
2317				if (result.getType() == IqPacket.TYPE.RESULT) {
2318					avatar.image = mIqParser.avatarData(result);
2319					if (avatar.image != null) {
2320						if (getFileBackend().save(avatar)) {
2321							if (account.getJid().toBareJid().equals(avatar.owner)) {
2322								if (account.setAvatar(avatar.getFilename())) {
2323									databaseBackend.updateAccount(account);
2324								}
2325								getAvatarService().clear(account);
2326								updateConversationUi();
2327								updateAccountUi();
2328							} else {
2329								Contact contact = account.getRoster()
2330										.getContact(avatar.owner);
2331								contact.setAvatar(avatar);
2332								getAvatarService().clear(contact);
2333								updateConversationUi();
2334								updateRosterUi();
2335							}
2336							if (callback != null) {
2337								callback.success(avatar);
2338							}
2339							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2340									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2341							return;
2342						}
2343					} else {
2344
2345						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2346					}
2347				} else {
2348					Element error = result.findChild("error");
2349					if (error == null) {
2350						Log.d(Config.LOGTAG, ERROR + "(server error)");
2351					} else {
2352						Log.d(Config.LOGTAG, ERROR + error.toString());
2353					}
2354				}
2355				if (callback != null) {
2356					callback.error(0, null);
2357				}
2358
2359			}
2360		});
2361	}
2362
2363	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2364		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2365		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2366			@Override
2367			public void onIqPacketReceived(Account account, IqPacket packet) {
2368				synchronized (mInProgressAvatarFetches) {
2369					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2370				}
2371				if (packet.getType() == IqPacket.TYPE.RESULT) {
2372					Element vCard = packet.findChild("vCard", "vcard-temp");
2373					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2374					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2375					if (image != null) {
2376						avatar.image = image;
2377						if (getFileBackend().save(avatar)) {
2378							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2379									+ ": successfully fetched vCard avatar for " + avatar.owner);
2380							if (avatar.owner.isBareJid()) {
2381								Contact contact = account.getRoster()
2382										.getContact(avatar.owner);
2383								contact.setAvatar(avatar);
2384								getAvatarService().clear(contact);
2385								updateConversationUi();
2386								updateRosterUi();
2387							} else {
2388								Conversation conversation = find(account, avatar.owner.toBareJid());
2389								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2390									MucOptions.User user = conversation.getMucOptions().findUser(avatar.owner.getResourcepart());
2391									if (user != null) {
2392										if (user.setAvatar(avatar)) {
2393											getAvatarService().clear(user);
2394											updateConversationUi();
2395											updateMucRosterUi();
2396										}
2397									}
2398								}
2399							}
2400						}
2401					}
2402				}
2403			}
2404		});
2405	}
2406
2407	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2408		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2409		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2410
2411			@Override
2412			public void onIqPacketReceived(Account account, IqPacket packet) {
2413				if (packet.getType() == IqPacket.TYPE.RESULT) {
2414					Element pubsub = packet.findChild("pubsub",
2415							"http://jabber.org/protocol/pubsub");
2416					if (pubsub != null) {
2417						Element items = pubsub.findChild("items");
2418						if (items != null) {
2419							Avatar avatar = Avatar.parseMetadata(items);
2420							if (avatar != null) {
2421								avatar.owner = account.getJid().toBareJid();
2422								if (fileBackend.isAvatarCached(avatar)) {
2423									if (account.setAvatar(avatar.getFilename())) {
2424										databaseBackend.updateAccount(account);
2425									}
2426									getAvatarService().clear(account);
2427									callback.success(avatar);
2428								} else {
2429									fetchAvatarPep(account, avatar, callback);
2430								}
2431								return;
2432							}
2433						}
2434					}
2435				}
2436				callback.error(0, null);
2437			}
2438		});
2439	}
2440
2441	public void deleteContactOnServer(Contact contact) {
2442		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2443		contact.resetOption(Contact.Options.DIRTY_PUSH);
2444		contact.setOption(Contact.Options.DIRTY_DELETE);
2445		Account account = contact.getAccount();
2446		if (account.getStatus() == Account.State.ONLINE) {
2447			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2448			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2449			item.setAttribute("jid", contact.getJid().toString());
2450			item.setAttribute("subscription", "remove");
2451			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2452		}
2453	}
2454
2455	public void updateConversation(Conversation conversation) {
2456		this.databaseBackend.updateConversation(conversation);
2457	}
2458
2459	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2460		synchronized (account) {
2461			XmppConnection connection = account.getXmppConnection();
2462			if (connection != null) {
2463				disconnect(account, force);
2464			} else {
2465				connection = createConnection(account);
2466				account.setXmppConnection(connection);
2467			}
2468			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2469				synchronized (this.mInProgressAvatarFetches) {
2470					for (Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
2471						final String KEY = iterator.next();
2472						if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
2473							iterator.remove();
2474						}
2475					}
2476				}
2477				if (!force) {
2478					try {
2479						Log.d(Config.LOGTAG, "wait for disconnect");
2480						Thread.sleep(500); //sleep  wait for disconnect
2481					} catch (InterruptedException e) {
2482						//ignored
2483					}
2484				}
2485				Thread thread = new Thread(connection);
2486				connection.setInteractive(interactive);
2487				thread.start();
2488				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2489			} else {
2490				account.getRoster().clearPresences();
2491				connection.resetEverything();
2492			}
2493		}
2494	}
2495
2496	public void reconnectAccountInBackground(final Account account) {
2497		new Thread(new Runnable() {
2498			@Override
2499			public void run() {
2500				reconnectAccount(account, false, true);
2501			}
2502		}).start();
2503	}
2504
2505	public void invite(Conversation conversation, Jid contact) {
2506		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2507		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2508		sendMessagePacket(conversation.getAccount(), packet);
2509	}
2510
2511	public void directInvite(Conversation conversation, Jid jid) {
2512		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2513		sendMessagePacket(conversation.getAccount(), packet);
2514	}
2515
2516	public void resetSendingToWaiting(Account account) {
2517		for (Conversation conversation : getConversations()) {
2518			if (conversation.getAccount() == account) {
2519				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2520
2521					@Override
2522					public void onMessageFound(Message message) {
2523						markMessage(message, Message.STATUS_WAITING);
2524					}
2525				});
2526			}
2527		}
2528	}
2529
2530	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2531		if (uuid == null) {
2532			return null;
2533		}
2534		for (Conversation conversation : getConversations()) {
2535			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2536				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2537				if (message != null) {
2538					markMessage(message, status);
2539				}
2540				return message;
2541			}
2542		}
2543		return null;
2544	}
2545
2546	public boolean markMessage(Conversation conversation, String uuid, int status) {
2547		if (uuid == null) {
2548			return false;
2549		} else {
2550			Message message = conversation.findSentMessageWithUuid(uuid);
2551			if (message != null) {
2552				markMessage(message, status);
2553				return true;
2554			} else {
2555				return false;
2556			}
2557		}
2558	}
2559
2560	public void markMessage(Message message, int status) {
2561		if (status == Message.STATUS_SEND_FAILED
2562				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2563				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2564			return;
2565		}
2566		message.setStatus(status);
2567		databaseBackend.updateMessage(message);
2568		updateConversationUi();
2569	}
2570
2571	public SharedPreferences getPreferences() {
2572		return PreferenceManager
2573				.getDefaultSharedPreferences(getApplicationContext());
2574	}
2575
2576	public boolean confirmMessages() {
2577		return getPreferences().getBoolean("confirm_messages", true);
2578	}
2579
2580	public boolean sendChatStates() {
2581		return getPreferences().getBoolean("chat_states", false);
2582	}
2583
2584	public boolean saveEncryptedMessages() {
2585		return !getPreferences().getBoolean("dont_save_encrypted", false);
2586	}
2587
2588	private boolean respectAutojoin() {
2589		return getPreferences().getBoolean("autojoin", true);
2590	}
2591
2592	public boolean indicateReceived() {
2593		return getPreferences().getBoolean("indicate_received", false);
2594	}
2595
2596	public boolean useTorToConnect() {
2597		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2598	}
2599
2600	public boolean showExtendedConnectionOptions() {
2601		return getPreferences().getBoolean("show_connection_options", false);
2602	}
2603
2604	public int unreadCount() {
2605		int count = 0;
2606		for (Conversation conversation : getConversations()) {
2607			count += conversation.unreadCount();
2608		}
2609		return count;
2610	}
2611
2612
2613	public void showErrorToastInUi(int resId) {
2614		if (mOnShowErrorToast != null) {
2615			mOnShowErrorToast.onShowErrorToast(resId);
2616		}
2617	}
2618
2619	public void updateConversationUi() {
2620		if (mOnConversationUpdate != null) {
2621			mOnConversationUpdate.onConversationUpdate();
2622		}
2623	}
2624
2625	public void updateAccountUi() {
2626		if (mOnAccountUpdate != null) {
2627			mOnAccountUpdate.onAccountUpdate();
2628		}
2629	}
2630
2631	public void updateRosterUi() {
2632		if (mOnRosterUpdate != null) {
2633			mOnRosterUpdate.onRosterUpdate();
2634		}
2635	}
2636
2637	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2638		boolean rc = false;
2639		if (mOnCaptchaRequested != null) {
2640			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2641			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2642					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2643
2644			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2645			rc = true;
2646		}
2647
2648		return rc;
2649	}
2650
2651	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2652		if (mOnUpdateBlocklist != null) {
2653			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2654		}
2655	}
2656
2657	public void updateMucRosterUi() {
2658		if (mOnMucRosterUpdate != null) {
2659			mOnMucRosterUpdate.onMucRosterUpdate();
2660		}
2661	}
2662
2663	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2664		if (mOnKeyStatusUpdated != null) {
2665			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2666		}
2667	}
2668
2669	public Account findAccountByJid(final Jid accountJid) {
2670		for (Account account : this.accounts) {
2671			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2672				return account;
2673			}
2674		}
2675		return null;
2676	}
2677
2678	public Conversation findConversationByUuid(String uuid) {
2679		for (Conversation conversation : getConversations()) {
2680			if (conversation.getUuid().equals(uuid)) {
2681				return conversation;
2682			}
2683		}
2684		return null;
2685	}
2686
2687	public void markRead(final Conversation conversation) {
2688		mNotificationService.clear(conversation);
2689		final List<Message> readMessages = conversation.markRead();
2690		if (readMessages.size() > 0) {
2691			Runnable runnable = new Runnable() {
2692				@Override
2693				public void run() {
2694					for (Message message : readMessages) {
2695						databaseBackend.updateMessage(message);
2696					}
2697				}
2698			};
2699			mDatabaseExecutor.execute(runnable);
2700		}
2701		updateUnreadCountBadge();
2702	}
2703
2704	public synchronized void updateUnreadCountBadge() {
2705		int count = unreadCount();
2706		if (unreadCount != count) {
2707			Log.d(Config.LOGTAG, "update unread count to " + count);
2708			if (count > 0) {
2709				ShortcutBadger.with(getApplicationContext()).count(count);
2710			} else {
2711				ShortcutBadger.with(getApplicationContext()).remove();
2712			}
2713			unreadCount = count;
2714		}
2715	}
2716
2717	public void sendReadMarker(final Conversation conversation) {
2718		final Message markable = conversation.getLatestMarkableMessage();
2719		this.markRead(conversation);
2720		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2721			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2722			Account account = conversation.getAccount();
2723			final Jid to = markable.getCounterpart();
2724			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2725			this.sendMessagePacket(conversation.getAccount(), packet);
2726		}
2727		updateConversationUi();
2728	}
2729
2730	public SecureRandom getRNG() {
2731		return this.mRandom;
2732	}
2733
2734	public MemorizingTrustManager getMemorizingTrustManager() {
2735		return this.mMemorizingTrustManager;
2736	}
2737
2738	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2739		this.mMemorizingTrustManager = trustManager;
2740	}
2741
2742	public void updateMemorizingTrustmanager() {
2743		final MemorizingTrustManager tm;
2744		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2745		if (dontTrustSystemCAs) {
2746			tm = new MemorizingTrustManager(getApplicationContext(), null);
2747		} else {
2748			tm = new MemorizingTrustManager(getApplicationContext());
2749		}
2750		setMemorizingTrustManager(tm);
2751	}
2752
2753	public PowerManager getPowerManager() {
2754		return this.pm;
2755	}
2756
2757	public LruCache<String, Bitmap> getBitmapCache() {
2758		return this.mBitmapCache;
2759	}
2760
2761	public void syncRosterToDisk(final Account account) {
2762		Runnable runnable = new Runnable() {
2763
2764			@Override
2765			public void run() {
2766				databaseBackend.writeRoster(account.getRoster());
2767			}
2768		};
2769		mDatabaseExecutor.execute(runnable);
2770
2771	}
2772
2773	public List<String> getKnownHosts() {
2774		final List<String> hosts = new ArrayList<>();
2775		for (final Account account : getAccounts()) {
2776			if (!hosts.contains(account.getServer().toString())) {
2777				hosts.add(account.getServer().toString());
2778			}
2779			for (final Contact contact : account.getRoster().getContacts()) {
2780				if (contact.showInRoster()) {
2781					final String server = contact.getServer().toString();
2782					if (server != null && !hosts.contains(server)) {
2783						hosts.add(server);
2784					}
2785				}
2786			}
2787		}
2788		return hosts;
2789	}
2790
2791	public List<String> getKnownConferenceHosts() {
2792		final ArrayList<String> mucServers = new ArrayList<>();
2793		for (final Account account : accounts) {
2794			if (account.getXmppConnection() != null) {
2795				final String server = account.getXmppConnection().getMucServer();
2796				if (server != null && !mucServers.contains(server)) {
2797					mucServers.add(server);
2798				}
2799			}
2800		}
2801		return mucServers;
2802	}
2803
2804	public void sendMessagePacket(Account account, MessagePacket packet) {
2805		XmppConnection connection = account.getXmppConnection();
2806		if (connection != null) {
2807			connection.sendMessagePacket(packet);
2808		}
2809	}
2810
2811	public void sendPresencePacket(Account account, PresencePacket packet) {
2812		XmppConnection connection = account.getXmppConnection();
2813		if (connection != null) {
2814			connection.sendPresencePacket(packet);
2815		}
2816	}
2817
2818	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2819		XmppConnection connection = account.getXmppConnection();
2820		if (connection != null) {
2821			connection.sendCaptchaRegistryRequest(id, data);
2822		}
2823	}
2824
2825	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2826		final XmppConnection connection = account.getXmppConnection();
2827		if (connection != null) {
2828			connection.sendIqPacket(packet, callback);
2829		}
2830	}
2831
2832	public void sendPresence(final Account account) {
2833		sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2834	}
2835
2836	public void refreshAllPresences() {
2837		for (Account account : getAccounts()) {
2838			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2839				sendPresence(account);
2840			}
2841		}
2842	}
2843
2844	public void sendOfflinePresence(final Account account) {
2845		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2846	}
2847
2848	public MessageGenerator getMessageGenerator() {
2849		return this.mMessageGenerator;
2850	}
2851
2852	public PresenceGenerator getPresenceGenerator() {
2853		return this.mPresenceGenerator;
2854	}
2855
2856	public IqGenerator getIqGenerator() {
2857		return this.mIqGenerator;
2858	}
2859
2860	public IqParser getIqParser() {
2861		return this.mIqParser;
2862	}
2863
2864	public JingleConnectionManager getJingleConnectionManager() {
2865		return this.mJingleConnectionManager;
2866	}
2867
2868	public MessageArchiveService getMessageArchiveService() {
2869		return this.mMessageArchiveService;
2870	}
2871
2872	public List<Contact> findContacts(Jid jid) {
2873		ArrayList<Contact> contacts = new ArrayList<>();
2874		for (Account account : getAccounts()) {
2875			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2876				Contact contact = account.getRoster().getContactFromRoster(jid);
2877				if (contact != null) {
2878					contacts.add(contact);
2879				}
2880			}
2881		}
2882		return contacts;
2883	}
2884
2885	public NotificationService getNotificationService() {
2886		return this.mNotificationService;
2887	}
2888
2889	public HttpConnectionManager getHttpConnectionManager() {
2890		return this.mHttpConnectionManager;
2891	}
2892
2893	public void resendFailedMessages(final Message message) {
2894		final Collection<Message> messages = new ArrayList<>();
2895		Message current = message;
2896		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2897			messages.add(current);
2898			if (current.mergeable(current.next())) {
2899				current = current.next();
2900			} else {
2901				break;
2902			}
2903		}
2904		for (final Message msg : messages) {
2905			msg.setTime(System.currentTimeMillis());
2906			markMessage(msg, Message.STATUS_WAITING);
2907			this.resendMessage(msg, false);
2908		}
2909	}
2910
2911	public void clearConversationHistory(final Conversation conversation) {
2912		conversation.clearMessages();
2913		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2914		Runnable runnable = new Runnable() {
2915			@Override
2916			public void run() {
2917				databaseBackend.deleteMessagesInConversation(conversation);
2918			}
2919		};
2920		mDatabaseExecutor.execute(runnable);
2921	}
2922
2923	public void sendBlockRequest(final Blockable blockable) {
2924		if (blockable != null && blockable.getBlockedJid() != null) {
2925			final Jid jid = blockable.getBlockedJid();
2926			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2927
2928				@Override
2929				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2930					if (packet.getType() == IqPacket.TYPE.RESULT) {
2931						account.getBlocklist().add(jid);
2932						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2933					}
2934				}
2935			});
2936		}
2937	}
2938
2939	public void sendUnblockRequest(final Blockable blockable) {
2940		if (blockable != null && blockable.getJid() != null) {
2941			final Jid jid = blockable.getBlockedJid();
2942			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2943				@Override
2944				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2945					if (packet.getType() == IqPacket.TYPE.RESULT) {
2946						account.getBlocklist().remove(jid);
2947						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2948					}
2949				}
2950			});
2951		}
2952	}
2953
2954	public void publishDisplayName(Account account) {
2955		String displayName = account.getDisplayName();
2956		if (displayName != null && !displayName.isEmpty()) {
2957			IqPacket publish = mIqGenerator.publishNick(displayName);
2958			sendIqPacket(account, publish, new OnIqPacketReceived() {
2959				@Override
2960				public void onIqPacketReceived(Account account, IqPacket packet) {
2961					if (packet.getType() == IqPacket.TYPE.ERROR) {
2962						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
2963					}
2964				}
2965			});
2966		}
2967	}
2968
2969	private ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String,String> key) {
2970		ServiceDiscoveryResult result = discoCache.get(key);
2971		if (result != null) {
2972			return result;
2973		} else {
2974			result = databaseBackend.findDiscoveryResult(key.first, key.second);
2975			if (result != null) {
2976				discoCache.put(key, result);
2977			}
2978			return result;
2979		}
2980	}
2981
2982	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
2983		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
2984		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
2985		if (disco != null) {
2986			presence.setServiceDiscoveryResult(disco);
2987		} else {
2988			if (!account.inProgressDiscoFetches.contains(key)) {
2989				account.inProgressDiscoFetches.add(key);
2990				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2991				request.setTo(jid);
2992				request.query("http://jabber.org/protocol/disco#info");
2993				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
2994				sendIqPacket(account, request, new OnIqPacketReceived() {
2995					@Override
2996					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
2997						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
2998							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
2999							if (presence.getVer().equals(disco.getVer())) {
3000								databaseBackend.insertDiscoveryResult(disco);
3001								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3002							} else {
3003								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid+" "+presence.getVer()+" vs "+disco.getVer());
3004							}
3005						}
3006						account.inProgressDiscoFetches.remove(key);
3007					}
3008				});
3009			}
3010		}
3011	}
3012
3013	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3014		for(Contact contact : roster.getContacts()) {
3015			for(Presence presence : contact.getPresences().getPresences().values()) {
3016				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3017					presence.setServiceDiscoveryResult(disco);
3018				}
3019			}
3020		}
3021	}
3022
3023	public interface OnAccountCreated {
3024		void onAccountCreated(Account account);
3025
3026		void informUser(int r);
3027	}
3028
3029	public interface OnMoreMessagesLoaded {
3030		void onMoreMessagesLoaded(int count, Conversation conversation);
3031
3032		void informUser(int r);
3033	}
3034
3035	public interface OnAccountPasswordChanged {
3036		void onPasswordChangeSucceeded();
3037
3038		void onPasswordChangeFailed();
3039	}
3040
3041	public interface OnAffiliationChanged {
3042		void onAffiliationChangedSuccessful(Jid jid);
3043
3044		void onAffiliationChangeFailed(Jid jid, int resId);
3045	}
3046
3047	public interface OnRoleChanged {
3048		void onRoleChangedSuccessful(String nick);
3049
3050		void onRoleChangeFailed(String nick, int resid);
3051	}
3052
3053	public interface OnConversationUpdate {
3054		void onConversationUpdate();
3055	}
3056
3057	public interface OnAccountUpdate {
3058		void onAccountUpdate();
3059	}
3060
3061	public interface OnCaptchaRequested {
3062		void onCaptchaRequested(Account account,
3063								String id,
3064								Data data,
3065								Bitmap captcha);
3066	}
3067
3068	public interface OnRosterUpdate {
3069		void onRosterUpdate();
3070	}
3071
3072	public interface OnMucRosterUpdate {
3073		void onMucRosterUpdate();
3074	}
3075
3076	public interface OnConferenceConfigurationFetched {
3077		void onConferenceConfigurationFetched(Conversation conversation);
3078
3079		void onFetchFailed(Conversation conversation, Element error);
3080	}
3081
3082	public interface OnConferenceJoined {
3083		void onConferenceJoined(Conversation conversation);
3084	}
3085
3086	public interface OnConferenceOptionsPushed {
3087		void onPushSucceeded();
3088
3089		void onPushFailed();
3090	}
3091
3092	public interface OnShowErrorToast {
3093		void onShowErrorToast(int resId);
3094	}
3095
3096	public class XmppConnectionBinder extends Binder {
3097		public XmppConnectionService getService() {
3098			return XmppConnectionService.this;
3099		}
3100	}
3101}