XmppConnectionService.java

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