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