XmppConnectionService.java

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