XmppConnectionService.java

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