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