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 onTrimMemory(int level) {
 678		super.onTrimMemory(level);
 679		if (level >= TRIM_MEMORY_COMPLETE) {
 680			Log.d(Config.LOGTAG,"clear cache due to low memory");
 681			getBitmapCache().evictAll();
 682		}
 683	}
 684
 685	@Override
 686	public void onDestroy() {
 687		try {
 688			unregisterReceiver(this.mEventReceiver);
 689		} catch (IllegalArgumentException e) {
 690			//ignored
 691		}
 692		super.onDestroy();
 693	}
 694
 695	public void toggleScreenEventReceiver() {
 696		if (awayWhenScreenOff()) {
 697			final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
 698			filter.addAction(Intent.ACTION_SCREEN_OFF);
 699			registerReceiver(this.mEventReceiver, filter);
 700		} else {
 701			try {
 702				unregisterReceiver(this.mEventReceiver);
 703			} catch (IllegalArgumentException e) {
 704				//ignored
 705			}
 706		}
 707	}
 708
 709	public void toggleForegroundService() {
 710		if (getPreferences().getBoolean("keep_foreground_service", false)) {
 711			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 712		} else {
 713			stopForeground(true);
 714		}
 715	}
 716
 717	@Override
 718	public void onTaskRemoved(final Intent rootIntent) {
 719		super.onTaskRemoved(rootIntent);
 720		if (!getPreferences().getBoolean("keep_foreground_service",false)) {
 721			this.logoutAndSave();
 722		}
 723	}
 724
 725	private void logoutAndSave() {
 726		for (final Account account : accounts) {
 727			databaseBackend.writeRoster(account.getRoster());
 728			if (account.getXmppConnection() != null) {
 729				disconnect(account, false);
 730			}
 731		}
 732		Context context = getApplicationContext();
 733		AlarmManager alarmManager = (AlarmManager) context
 734				.getSystemService(Context.ALARM_SERVICE);
 735		Intent intent = new Intent(context, EventReceiver.class);
 736		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 737		Log.d(Config.LOGTAG, "good bye");
 738		stopSelf();
 739	}
 740
 741	protected void scheduleWakeUpCall(int seconds, int requestCode) {
 742		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
 743
 744		Context context = getApplicationContext();
 745		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 746
 747		Intent intent = new Intent(context, EventReceiver.class);
 748		intent.setAction("ping");
 749		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
 750		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 751	}
 752
 753	public XmppConnection createConnection(final Account account) {
 754		final SharedPreferences sharedPref = getPreferences();
 755		account.setResource(sharedPref.getString("resource", "mobile")
 756				.toLowerCase(Locale.getDefault()));
 757		final XmppConnection connection = new XmppConnection(account, this);
 758		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 759		connection.setOnStatusChangedListener(this.statusListener);
 760		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 761		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 762		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 763		connection.setOnBindListener(this.mOnBindListener);
 764		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 765		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 766		return connection;
 767	}
 768
 769	public void sendChatState(Conversation conversation) {
 770		if (sendChatStates()) {
 771			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
 772			sendMessagePacket(conversation.getAccount(), packet);
 773		}
 774	}
 775
 776	private void sendFileMessage(final Message message, final boolean delay) {
 777		Log.d(Config.LOGTAG, "send file message");
 778		final Account account = message.getConversation().getAccount();
 779		final XmppConnection connection = account.getXmppConnection();
 780		if (connection != null && connection.getFeatures().httpUpload()) {
 781			mHttpConnectionManager.createNewUploadConnection(message, delay);
 782		} else {
 783			mJingleConnectionManager.createNewConnection(message);
 784		}
 785	}
 786
 787	public void sendMessage(final Message message) {
 788		sendMessage(message, false, false);
 789	}
 790
 791	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
 792		final Account account = message.getConversation().getAccount();
 793		final Conversation conversation = message.getConversation();
 794		account.deactivateGracePeriod();
 795		MessagePacket packet = null;
 796		boolean saveInDb = true;
 797		message.setStatus(Message.STATUS_WAITING);
 798
 799		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
 800			message.getConversation().endOtrIfNeeded();
 801			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
 802					new Conversation.OnMessageFound() {
 803				@Override
 804				public void onMessageFound(Message message) {
 805					markMessage(message,Message.STATUS_SEND_FAILED);
 806				}
 807			});
 808		}
 809
 810		if (account.isOnlineAndConnected()) {
 811			switch (message.getEncryption()) {
 812				case Message.ENCRYPTION_NONE:
 813					if (message.needsUploading()) {
 814						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 815							this.sendFileMessage(message,delay);
 816						} else {
 817							break;
 818						}
 819					} else {
 820						packet = mMessageGenerator.generateChat(message);
 821					}
 822					break;
 823				case Message.ENCRYPTION_PGP:
 824				case Message.ENCRYPTION_DECRYPTED:
 825					if (message.needsUploading()) {
 826						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 827							this.sendFileMessage(message,delay);
 828						} else {
 829							break;
 830						}
 831					} else {
 832						packet = mMessageGenerator.generatePgpChat(message);
 833					}
 834					break;
 835				case Message.ENCRYPTION_OTR:
 836					SessionImpl otrSession = conversation.getOtrSession();
 837					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
 838						try {
 839							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
 840						} catch (InvalidJidException e) {
 841							break;
 842						}
 843						if (message.needsUploading()) {
 844							mJingleConnectionManager.createNewConnection(message);
 845						} else {
 846							packet = mMessageGenerator.generateOtrChat(message);
 847						}
 848					} else if (otrSession == null) {
 849						if (message.fixCounterpart()) {
 850							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
 851						} else {
 852							break;
 853						}
 854					}
 855					break;
 856				case Message.ENCRYPTION_AXOLOTL:
 857					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 858					if (message.needsUploading()) {
 859						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 860							this.sendFileMessage(message,delay);
 861						} else {
 862							break;
 863						}
 864					} else {
 865						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
 866						if (axolotlMessage == null) {
 867							account.getAxolotlService().preparePayloadMessage(message, delay);
 868						} else {
 869							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
 870						}
 871					}
 872					break;
 873
 874			}
 875			if (packet != null) {
 876				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 877					message.setStatus(Message.STATUS_UNSEND);
 878				} else {
 879					message.setStatus(Message.STATUS_SEND);
 880				}
 881			}
 882		} else {
 883			switch(message.getEncryption()) {
 884				case Message.ENCRYPTION_DECRYPTED:
 885					if (!message.needsUploading()) {
 886						String pgpBody = message.getEncryptedBody();
 887						String decryptedBody = message.getBody();
 888						message.setBody(pgpBody);
 889						message.setEncryption(Message.ENCRYPTION_PGP);
 890						databaseBackend.createMessage(message);
 891						saveInDb = false;
 892						message.setBody(decryptedBody);
 893						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 894					}
 895					break;
 896				case Message.ENCRYPTION_OTR:
 897					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
 898						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
 899					}
 900					break;
 901				case Message.ENCRYPTION_AXOLOTL:
 902					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 903					break;
 904			}
 905		}
 906
 907		if (resend) {
 908			if (packet != null) {
 909				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 910					markMessage(message,Message.STATUS_UNSEND);
 911				} else {
 912					markMessage(message,Message.STATUS_SEND);
 913				}
 914			}
 915		} else {
 916			conversation.add(message);
 917			if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
 918				databaseBackend.createMessage(message);
 919			}
 920			updateConversationUi();
 921		}
 922		if (packet != null) {
 923			if (delay) {
 924				mMessageGenerator.addDelay(packet,message.getTimeSent());
 925			}
 926			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 927				if (this.sendChatStates()) {
 928					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
 929				}
 930			}
 931			sendMessagePacket(account, packet);
 932		}
 933	}
 934
 935	private void sendUnsentMessages(final Conversation conversation) {
 936		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 937
 938			@Override
 939			public void onMessageFound(Message message) {
 940				resendMessage(message, true);
 941			}
 942		});
 943	}
 944
 945	public void resendMessage(final Message message, final boolean delay) {
 946		sendMessage(message, true, delay);
 947	}
 948
 949	public void fetchRosterFromServer(final Account account) {
 950		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 951		if (!"".equals(account.getRosterVersion())) {
 952			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 953					+ ": fetching roster version " + account.getRosterVersion());
 954		} else {
 955			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 956		}
 957		iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
 958		sendIqPacket(account, iqPacket, mIqParser);
 959	}
 960
 961	public void fetchBookmarks(final Account account) {
 962		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 963		final Element query = iqPacket.query("jabber:iq:private");
 964		query.addChild("storage", "storage:bookmarks");
 965		final OnIqPacketReceived callback = new OnIqPacketReceived() {
 966
 967			@Override
 968			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 969				if (packet.getType() == IqPacket.TYPE.RESULT) {
 970					final Element query = packet.query();
 971					final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 972					final Element storage = query.findChild("storage", "storage:bookmarks");
 973					if (storage != null) {
 974						for (final Element item : storage.getChildren()) {
 975							if (item.getName().equals("conference")) {
 976								final Bookmark bookmark = Bookmark.parse(item, account);
 977								bookmarks.add(bookmark);
 978								Conversation conversation = find(bookmark);
 979								if (conversation != null) {
 980									conversation.setBookmark(bookmark);
 981								} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 982									conversation = findOrCreateConversation(
 983											account, bookmark.getJid(), true);
 984									conversation.setBookmark(bookmark);
 985									joinMuc(conversation);
 986								}
 987							}
 988						}
 989					}
 990					account.setBookmarks(bookmarks);
 991				} else {
 992					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fetch bookmarks");
 993				}
 994			}
 995		};
 996		sendIqPacket(account, iqPacket, callback);
 997	}
 998
 999	public void pushBookmarks(Account account) {
1000		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1001		Element query = iqPacket.query("jabber:iq:private");
1002		Element storage = query.addChild("storage", "storage:bookmarks");
1003		for (Bookmark bookmark : account.getBookmarks()) {
1004			storage.addChild(bookmark);
1005		}
1006		sendIqPacket(account, iqPacket, mDefaultIqHandler);
1007	}
1008
1009	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
1010		if (mPhoneContactMergerThread != null) {
1011			mPhoneContactMergerThread.interrupt();
1012		}
1013		mPhoneContactMergerThread = new Thread(new Runnable() {
1014			@Override
1015			public void run() {
1016				Log.d(Config.LOGTAG,"start merging phone contacts with roster");
1017				for (Account account : accounts) {
1018					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1019					for (Bundle phoneContact : phoneContacts) {
1020						if (Thread.interrupted()) {
1021							Log.d(Config.LOGTAG,"interrupted merging phone contacts");
1022							return;
1023						}
1024						Jid jid;
1025						try {
1026							jid = Jid.fromString(phoneContact.getString("jid"));
1027						} catch (final InvalidJidException e) {
1028							continue;
1029						}
1030						final Contact contact = account.getRoster().getContact(jid);
1031						String systemAccount = phoneContact.getInt("phoneid")
1032							+ "#"
1033							+ phoneContact.getString("lookup");
1034						contact.setSystemAccount(systemAccount);
1035						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1036							getAvatarService().clear(contact);
1037						}
1038						contact.setSystemName(phoneContact.getString("displayname"));
1039						withSystemAccounts.remove(contact);
1040					}
1041					for(Contact contact : withSystemAccounts) {
1042						contact.setSystemAccount(null);
1043						contact.setSystemName(null);
1044						if (contact.setPhotoUri(null)) {
1045							getAvatarService().clear(contact);
1046						}
1047					}
1048				}
1049				Log.d(Config.LOGTAG,"finished merging phone contacts");
1050				updateAccountUi();
1051			}
1052		});
1053		mPhoneContactMergerThread.start();
1054	}
1055
1056	private void restoreFromDatabase() {
1057		synchronized (this.conversations) {
1058			final Map<String, Account> accountLookupTable = new Hashtable<>();
1059			for (Account account : this.accounts) {
1060				accountLookupTable.put(account.getUuid(), account);
1061			}
1062			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1063			for (Conversation conversation : this.conversations) {
1064				Account account = accountLookupTable.get(conversation.getAccountUuid());
1065				conversation.setAccount(account);
1066			}
1067			Runnable runnable =new Runnable() {
1068				@Override
1069				public void run() {
1070					Log.d(Config.LOGTAG,"restoring roster");
1071					for(Account account : accounts) {
1072						databaseBackend.readRoster(account.getRoster());
1073						account.initAccountServices(XmppConnectionService.this);
1074					}
1075					getBitmapCache().evictAll();
1076					Looper.prepare();
1077					PhoneHelper.loadPhoneContacts(getApplicationContext(),
1078							new CopyOnWriteArrayList<Bundle>(),
1079							XmppConnectionService.this);
1080					Log.d(Config.LOGTAG,"restoring messages");
1081					for (Conversation conversation : conversations) {
1082						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1083						checkDeletedFiles(conversation);
1084						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1085							@Override
1086							public void onMessageFound(Message message) {
1087								mNotificationService.pushFromBacklog(message);
1088							}
1089						});
1090					}
1091					mNotificationService.finishBacklog();
1092					mRestoredFromDatabase = true;
1093					Log.d(Config.LOGTAG,"restored all messages");
1094					updateConversationUi();
1095				}
1096			};
1097			mDatabaseExecutor.execute(runnable);
1098		}
1099	}
1100
1101	public List<Conversation> getConversations() {
1102		return this.conversations;
1103	}
1104
1105	private void checkDeletedFiles(Conversation conversation) {
1106		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1107
1108			@Override
1109			public void onMessageFound(Message message) {
1110				if (!getFileBackend().isFileAvailable(message)) {
1111					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1112					final int s = message.getStatus();
1113					if(s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1114						markMessage(message,Message.STATUS_SEND_FAILED);
1115					}
1116				}
1117			}
1118		});
1119	}
1120
1121	private void markFileDeleted(String uuid) {
1122		for (Conversation conversation : getConversations()) {
1123			Message message = conversation.findMessageWithFileAndUuid(uuid);
1124			if (message != null) {
1125				if (!getFileBackend().isFileAvailable(message)) {
1126					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1127					final int s = message.getStatus();
1128					if(s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1129						markMessage(message,Message.STATUS_SEND_FAILED);
1130					} else {
1131						updateConversationUi();
1132					}
1133				}
1134				return;
1135			}
1136		}
1137	}
1138
1139	public void populateWithOrderedConversations(final List<Conversation> list) {
1140		populateWithOrderedConversations(list, true);
1141	}
1142
1143	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1144		list.clear();
1145		if (includeNoFileUpload) {
1146			list.addAll(getConversations());
1147		} else {
1148			for (Conversation conversation : getConversations()) {
1149				if (conversation.getMode() == Conversation.MODE_SINGLE
1150						|| conversation.getAccount().httpUploadAvailable()) {
1151					list.add(conversation);
1152				}
1153			}
1154		}
1155		Collections.sort(list, new Comparator<Conversation>() {
1156			@Override
1157			public int compare(Conversation lhs, Conversation rhs) {
1158				Message left = lhs.getLatestMessage();
1159				Message right = rhs.getLatestMessage();
1160				if (left.getTimeSent() > right.getTimeSent()) {
1161					return -1;
1162				} else if (left.getTimeSent() < right.getTimeSent()) {
1163					return 1;
1164				} else {
1165					return 0;
1166				}
1167			}
1168		});
1169	}
1170
1171	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1172		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1173			return;
1174		}
1175		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1176		Runnable runnable = new Runnable() {
1177			@Override
1178			public void run() {
1179				final Account account = conversation.getAccount();
1180				List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1181				if (messages.size() > 0) {
1182					conversation.addAll(0, messages);
1183					checkDeletedFiles(conversation);
1184					callback.onMoreMessagesLoaded(messages.size(), conversation);
1185				} else if (conversation.hasMessagesLeftOnServer()
1186						&& account.isOnlineAndConnected()) {
1187					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1188							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1189						MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1190						if (query != null) {
1191							query.setCallback(callback);
1192						}
1193						callback.informUser(R.string.fetching_history_from_server);
1194					}
1195				}
1196			}
1197		};
1198		mDatabaseExecutor.execute(runnable);
1199	}
1200
1201	public List<Account> getAccounts() {
1202		return this.accounts;
1203	}
1204
1205	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1206		for (final Conversation conversation : haystack) {
1207			if (conversation.getContact() == contact) {
1208				return conversation;
1209			}
1210		}
1211		return null;
1212	}
1213
1214	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1215		if (jid == null) {
1216			return null;
1217		}
1218		for (final Conversation conversation : haystack) {
1219			if ((account == null || conversation.getAccount() == account)
1220					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1221				return conversation;
1222			}
1223		}
1224		return null;
1225	}
1226
1227	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1228		return this.findOrCreateConversation(account, jid, muc, null);
1229	}
1230
1231	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1232		synchronized (this.conversations) {
1233			Conversation conversation = find(account, jid);
1234			if (conversation != null) {
1235				return conversation;
1236			}
1237			conversation = databaseBackend.findConversation(account, jid);
1238			if (conversation != null) {
1239				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1240				conversation.setAccount(account);
1241				if (muc) {
1242					conversation.setMode(Conversation.MODE_MULTI);
1243					conversation.setContactJid(jid);
1244				} else {
1245					conversation.setMode(Conversation.MODE_SINGLE);
1246					conversation.setContactJid(jid.toBareJid());
1247				}
1248				conversation.setNextEncryption(-1);
1249				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1250				this.databaseBackend.updateConversation(conversation);
1251			} else {
1252				String conversationName;
1253				Contact contact = account.getRoster().getContact(jid);
1254				if (contact != null) {
1255					conversationName = contact.getDisplayName();
1256				} else {
1257					conversationName = jid.getLocalpart();
1258				}
1259				if (muc) {
1260					conversation = new Conversation(conversationName, account, jid,
1261							Conversation.MODE_MULTI);
1262				} else {
1263					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1264							Conversation.MODE_SINGLE);
1265				}
1266				this.databaseBackend.createConversation(conversation);
1267			}
1268			if (account.getXmppConnection() != null
1269					&& account.getXmppConnection().getFeatures().mam()
1270					&& !muc) {
1271				if (query == null) {
1272					this.mMessageArchiveService.query(conversation);
1273				} else {
1274					if (query.getConversation() == null) {
1275						this.mMessageArchiveService.query(conversation, query.getStart());
1276					}
1277				}
1278			}
1279			checkDeletedFiles(conversation);
1280			this.conversations.add(conversation);
1281			updateConversationUi();
1282			return conversation;
1283		}
1284	}
1285
1286	public void archiveConversation(Conversation conversation) {
1287		getNotificationService().clear(conversation);
1288		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1289		conversation.setNextEncryption(-1);
1290		synchronized (this.conversations) {
1291			if (conversation.getMode() == Conversation.MODE_MULTI) {
1292				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1293					Bookmark bookmark = conversation.getBookmark();
1294					if (bookmark != null && bookmark.autojoin()) {
1295						bookmark.setAutojoin(false);
1296						pushBookmarks(bookmark.getAccount());
1297					}
1298				}
1299				leaveMuc(conversation);
1300			} else {
1301				conversation.endOtrIfNeeded();
1302			}
1303			this.databaseBackend.updateConversation(conversation);
1304			this.conversations.remove(conversation);
1305			updateConversationUi();
1306		}
1307	}
1308
1309	public void createAccount(final Account account) {
1310		account.initAccountServices(this);
1311		databaseBackend.createAccount(account);
1312		this.accounts.add(account);
1313		this.reconnectAccountInBackground(account);
1314		updateAccountUi();
1315	}
1316
1317	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1318		new Thread(new Runnable() {
1319			@Override
1320			public void run() {
1321				try {
1322					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1323					Pair<Jid,String> info = CryptoHelper.extractJidAndName(chain[0]);
1324					if (findAccountByJid(info.first) == null) {
1325						Account account = new Account(info.first, "");
1326						account.setPrivateKeyAlias(alias);
1327						account.setOption(Account.OPTION_DISABLED, true);
1328						createAccount(account);
1329						callback.onAccountCreated(account);
1330						if (Config.X509_VERIFICATION) {
1331							try {
1332								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1333							} catch (CertificateException e) {
1334								callback.informUser(R.string.certificate_chain_is_not_trusted);
1335							}
1336						}
1337					} else {
1338						callback.informUser(R.string.account_already_exists);
1339					}
1340				} catch (Exception e) {
1341					callback.informUser(R.string.unable_to_parse_certificate);
1342				}
1343			}
1344		}).start();
1345
1346	}
1347
1348	public void updateKeyInAccount(final Account account, final String alias) {
1349		Log.d(Config.LOGTAG, "update key in account " + alias);
1350		try {
1351			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1352			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1353			if (account.getJid().toBareJid().equals(info.first)) {
1354				account.setPrivateKeyAlias(alias);
1355				databaseBackend.updateAccount(account);
1356				if (Config.X509_VERIFICATION) {
1357					try {
1358						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1359					} catch (CertificateException e) {
1360						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1361					}
1362					account.getAxolotlService().regenerateKeys(true);
1363				}
1364			} else {
1365				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1366			}
1367		} catch (InterruptedException e) {
1368			e.printStackTrace();
1369		} catch (KeyChainException e) {
1370			e.printStackTrace();
1371		} catch (InvalidJidException e) {
1372			e.printStackTrace();
1373		} catch (CertificateEncodingException e) {
1374			e.printStackTrace();
1375		}
1376	}
1377
1378	public void updateAccount(final Account account) {
1379		this.statusListener.onStatusChanged(account);
1380		databaseBackend.updateAccount(account);
1381		reconnectAccount(account, false, true);
1382		updateAccountUi();
1383		getNotificationService().updateErrorNotification();
1384	}
1385
1386	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1387		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1388		sendIqPacket(account, iq, new OnIqPacketReceived() {
1389			@Override
1390			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1391				if (packet.getType() == IqPacket.TYPE.RESULT) {
1392					account.setPassword(newPassword);
1393					databaseBackend.updateAccount(account);
1394					callback.onPasswordChangeSucceeded();
1395				} else {
1396					callback.onPasswordChangeFailed();
1397				}
1398			}
1399		});
1400	}
1401
1402	public void deleteAccount(final Account account) {
1403		synchronized (this.conversations) {
1404			for (final Conversation conversation : conversations) {
1405				if (conversation.getAccount() == account) {
1406					if (conversation.getMode() == Conversation.MODE_MULTI) {
1407						leaveMuc(conversation);
1408					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1409						conversation.endOtrIfNeeded();
1410					}
1411					conversations.remove(conversation);
1412				}
1413			}
1414			if (account.getXmppConnection() != null) {
1415				this.disconnect(account, true);
1416			}
1417			databaseBackend.deleteAccount(account);
1418			this.accounts.remove(account);
1419			updateAccountUi();
1420			getNotificationService().updateErrorNotification();
1421		}
1422	}
1423
1424	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1425		synchronized (this) {
1426			if (checkListeners()) {
1427				switchToForeground();
1428			}
1429			this.mOnConversationUpdate = listener;
1430			this.mNotificationService.setIsInForeground(true);
1431			if (this.convChangedListenerCount < 2) {
1432				this.convChangedListenerCount++;
1433			}
1434		}
1435	}
1436
1437	public void removeOnConversationListChangedListener() {
1438		synchronized (this) {
1439			this.convChangedListenerCount--;
1440			if (this.convChangedListenerCount <= 0) {
1441				this.convChangedListenerCount = 0;
1442				this.mOnConversationUpdate = null;
1443				this.mNotificationService.setIsInForeground(false);
1444				if (checkListeners()) {
1445					switchToBackground();
1446				}
1447			}
1448		}
1449	}
1450
1451	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1452		synchronized (this) {
1453			if (checkListeners()) {
1454				switchToForeground();
1455			}
1456			this.mOnShowErrorToast = onShowErrorToast;
1457			if (this.showErrorToastListenerCount < 2) {
1458				this.showErrorToastListenerCount++;
1459			}
1460		}
1461		this.mOnShowErrorToast = onShowErrorToast;
1462	}
1463
1464	public void removeOnShowErrorToastListener() {
1465		synchronized (this) {
1466			this.showErrorToastListenerCount--;
1467			if (this.showErrorToastListenerCount <= 0) {
1468				this.showErrorToastListenerCount = 0;
1469				this.mOnShowErrorToast = null;
1470				if (checkListeners()) {
1471					switchToBackground();
1472				}
1473			}
1474		}
1475	}
1476
1477	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1478		synchronized (this) {
1479			if (checkListeners()) {
1480				switchToForeground();
1481			}
1482			this.mOnAccountUpdate = listener;
1483			if (this.accountChangedListenerCount < 2) {
1484				this.accountChangedListenerCount++;
1485			}
1486		}
1487	}
1488
1489	public void removeOnAccountListChangedListener() {
1490		synchronized (this) {
1491			this.accountChangedListenerCount--;
1492			if (this.accountChangedListenerCount <= 0) {
1493				this.mOnAccountUpdate = null;
1494				this.accountChangedListenerCount = 0;
1495				if (checkListeners()) {
1496					switchToBackground();
1497				}
1498			}
1499		}
1500	}
1501
1502	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1503		synchronized (this) {
1504			if (checkListeners()) {
1505				switchToForeground();
1506			}
1507			this.mOnCaptchaRequested = listener;
1508			if (this.captchaRequestedListenerCount < 2) {
1509				this.captchaRequestedListenerCount++;
1510			}
1511		}
1512	}
1513
1514	public void removeOnCaptchaRequestedListener() {
1515		synchronized (this) {
1516			this.captchaRequestedListenerCount--;
1517			if (this.captchaRequestedListenerCount <= 0) {
1518				this.mOnCaptchaRequested = null;
1519				this.captchaRequestedListenerCount = 0;
1520				if (checkListeners()) {
1521					switchToBackground();
1522				}
1523			}
1524		}
1525	}
1526
1527	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1528		synchronized (this) {
1529			if (checkListeners()) {
1530				switchToForeground();
1531			}
1532			this.mOnRosterUpdate = listener;
1533			if (this.rosterChangedListenerCount < 2) {
1534				this.rosterChangedListenerCount++;
1535			}
1536		}
1537	}
1538
1539	public void removeOnRosterUpdateListener() {
1540		synchronized (this) {
1541			this.rosterChangedListenerCount--;
1542			if (this.rosterChangedListenerCount <= 0) {
1543				this.rosterChangedListenerCount = 0;
1544				this.mOnRosterUpdate = null;
1545				if (checkListeners()) {
1546					switchToBackground();
1547				}
1548			}
1549		}
1550	}
1551
1552	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1553		synchronized (this) {
1554			if (checkListeners()) {
1555				switchToForeground();
1556			}
1557			this.mOnUpdateBlocklist = listener;
1558			if (this.updateBlocklistListenerCount < 2) {
1559				this.updateBlocklistListenerCount++;
1560			}
1561		}
1562	}
1563
1564	public void removeOnUpdateBlocklistListener() {
1565		synchronized (this) {
1566			this.updateBlocklistListenerCount--;
1567			if (this.updateBlocklistListenerCount <= 0) {
1568				this.updateBlocklistListenerCount = 0;
1569				this.mOnUpdateBlocklist = null;
1570				if (checkListeners()) {
1571					switchToBackground();
1572				}
1573			}
1574		}
1575	}
1576
1577	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1578		synchronized (this) {
1579			if (checkListeners()) {
1580				switchToForeground();
1581			}
1582			this.mOnKeyStatusUpdated = listener;
1583			if (this.keyStatusUpdatedListenerCount < 2) {
1584				this.keyStatusUpdatedListenerCount++;
1585			}
1586		}
1587	}
1588
1589	public void removeOnNewKeysAvailableListener() {
1590		synchronized (this) {
1591			this.keyStatusUpdatedListenerCount--;
1592			if (this.keyStatusUpdatedListenerCount <= 0) {
1593				this.keyStatusUpdatedListenerCount = 0;
1594				this.mOnKeyStatusUpdated = null;
1595				if (checkListeners()) {
1596					switchToBackground();
1597				}
1598			}
1599		}
1600	}
1601
1602	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1603		synchronized (this) {
1604			if (checkListeners()) {
1605				switchToForeground();
1606			}
1607			this.mOnMucRosterUpdate = listener;
1608			if (this.mucRosterChangedListenerCount < 2) {
1609				this.mucRosterChangedListenerCount++;
1610			}
1611		}
1612	}
1613
1614	public void removeOnMucRosterUpdateListener() {
1615		synchronized (this) {
1616			this.mucRosterChangedListenerCount--;
1617			if (this.mucRosterChangedListenerCount <= 0) {
1618				this.mucRosterChangedListenerCount = 0;
1619				this.mOnMucRosterUpdate = null;
1620				if (checkListeners()) {
1621					switchToBackground();
1622				}
1623			}
1624		}
1625	}
1626
1627	private boolean checkListeners() {
1628		return (this.mOnAccountUpdate == null
1629				&& this.mOnConversationUpdate == null
1630				&& this.mOnRosterUpdate == null
1631				&& this.mOnCaptchaRequested == null
1632				&& this.mOnUpdateBlocklist == null
1633				&& this.mOnShowErrorToast == null
1634				&& this.mOnKeyStatusUpdated == null);
1635	}
1636
1637	private void switchToForeground() {
1638		for (Account account : getAccounts()) {
1639			if (account.getStatus() == Account.State.ONLINE) {
1640				XmppConnection connection = account.getXmppConnection();
1641				if (connection != null && connection.getFeatures().csi()) {
1642					connection.sendActive();
1643				}
1644			}
1645		}
1646		Log.d(Config.LOGTAG, "app switched into foreground");
1647	}
1648
1649	private void switchToBackground() {
1650		for (Account account : getAccounts()) {
1651			if (account.getStatus() == Account.State.ONLINE) {
1652				XmppConnection connection = account.getXmppConnection();
1653				if (connection != null && connection.getFeatures().csi()) {
1654					connection.sendInactive();
1655				}
1656			}
1657		}
1658		for(Conversation conversation : getConversations()) {
1659			conversation.setIncomingChatState(ChatState.ACTIVE);
1660		}
1661		this.mNotificationService.setIsInForeground(false);
1662		Log.d(Config.LOGTAG, "app switched into background");
1663	}
1664
1665	private void connectMultiModeConversations(Account account) {
1666		List<Conversation> conversations = getConversations();
1667		for (Conversation conversation : conversations) {
1668			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1669				joinMuc(conversation,true);
1670			}
1671		}
1672	}
1673
1674	public void joinMuc(Conversation conversation) {
1675		joinMuc(conversation, false);
1676	}
1677
1678	private void joinMuc(Conversation conversation, boolean now) {
1679		Account account = conversation.getAccount();
1680		account.pendingConferenceJoins.remove(conversation);
1681		account.pendingConferenceLeaves.remove(conversation);
1682		if (account.getStatus() == Account.State.ONLINE || now) {
1683			conversation.resetMucOptions();
1684			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1685				@Override
1686				public void onConferenceConfigurationFetched(Conversation conversation) {
1687					Account account = conversation.getAccount();
1688					final String nick = conversation.getMucOptions().getProposedNick();
1689					final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1690					if (joinJid == null) {
1691						return; //safety net
1692					}
1693					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1694					PresencePacket packet = new PresencePacket();
1695					packet.setFrom(conversation.getAccount().getJid());
1696					packet.setTo(joinJid);
1697					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1698					if (conversation.getMucOptions().getPassword() != null) {
1699						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1700					}
1701
1702					if (conversation.getMucOptions().mamSupport()) {
1703						// Use MAM instead of the limited muc history to get history
1704						x.addChild("history").setAttribute("maxchars", "0");
1705					} else {
1706						// Fallback to muc history
1707						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1708					}
1709					String sig = account.getPgpSignature();
1710					if (sig != null) {
1711						packet.addChild("status").setContent("online");
1712						packet.addChild("x", "jabber:x:signed").setContent(sig);
1713					}
1714					sendPresencePacket(account, packet);
1715					fetchConferenceConfiguration(conversation);
1716					if (!joinJid.equals(conversation.getJid())) {
1717						conversation.setContactJid(joinJid);
1718						databaseBackend.updateConversation(conversation);
1719					}
1720					conversation.setHasMessagesLeftOnServer(false);
1721					if (conversation.getMucOptions().mamSupport()) {
1722						getMessageArchiveService().catchupMUC(conversation);
1723					}
1724				}
1725			});
1726
1727		} else {
1728			account.pendingConferenceJoins.add(conversation);
1729		}
1730	}
1731
1732	public void providePasswordForMuc(Conversation conversation, String password) {
1733		if (conversation.getMode() == Conversation.MODE_MULTI) {
1734			conversation.getMucOptions().setPassword(password);
1735			if (conversation.getBookmark() != null) {
1736				conversation.getBookmark().setAutojoin(true);
1737				pushBookmarks(conversation.getAccount());
1738			}
1739			databaseBackend.updateConversation(conversation);
1740			joinMuc(conversation);
1741		}
1742	}
1743
1744	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1745		final MucOptions options = conversation.getMucOptions();
1746		final Jid joinJid = options.createJoinJid(nick);
1747		if (options.online()) {
1748			Account account = conversation.getAccount();
1749			options.setOnRenameListener(new OnRenameListener() {
1750
1751				@Override
1752				public void onSuccess() {
1753					conversation.setContactJid(joinJid);
1754					databaseBackend.updateConversation(conversation);
1755					Bookmark bookmark = conversation.getBookmark();
1756					if (bookmark != null) {
1757						bookmark.setNick(nick);
1758						pushBookmarks(bookmark.getAccount());
1759					}
1760					callback.success(conversation);
1761				}
1762
1763				@Override
1764				public void onFailure() {
1765					callback.error(R.string.nick_in_use, conversation);
1766				}
1767			});
1768
1769			PresencePacket packet = new PresencePacket();
1770			packet.setTo(joinJid);
1771			packet.setFrom(conversation.getAccount().getJid());
1772
1773			String sig = account.getPgpSignature();
1774			if (sig != null) {
1775				packet.addChild("status").setContent("online");
1776				packet.addChild("x", "jabber:x:signed").setContent(sig);
1777			}
1778			sendPresencePacket(account, packet);
1779		} else {
1780			conversation.setContactJid(joinJid);
1781			databaseBackend.updateConversation(conversation);
1782			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1783				Bookmark bookmark = conversation.getBookmark();
1784				if (bookmark != null) {
1785					bookmark.setNick(nick);
1786					pushBookmarks(bookmark.getAccount());
1787				}
1788				joinMuc(conversation);
1789			}
1790		}
1791	}
1792
1793	public void leaveMuc(Conversation conversation) {
1794		Account account = conversation.getAccount();
1795		account.pendingConferenceJoins.remove(conversation);
1796		account.pendingConferenceLeaves.remove(conversation);
1797		if (account.getStatus() == Account.State.ONLINE) {
1798			PresencePacket packet = new PresencePacket();
1799			packet.setTo(conversation.getJid());
1800			packet.setFrom(conversation.getAccount().getJid());
1801			packet.setAttribute("type", "unavailable");
1802			sendPresencePacket(conversation.getAccount(), packet);
1803			conversation.getMucOptions().setOffline();
1804			conversation.deregisterWithBookmark();
1805			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1806					+ ": leaving muc " + conversation.getJid());
1807		} else {
1808			account.pendingConferenceLeaves.add(conversation);
1809		}
1810	}
1811
1812	private String findConferenceServer(final Account account) {
1813		String server;
1814		if (account.getXmppConnection() != null) {
1815			server = account.getXmppConnection().getMucServer();
1816			if (server != null) {
1817				return server;
1818			}
1819		}
1820		for (Account other : getAccounts()) {
1821			if (other != account && other.getXmppConnection() != null) {
1822				server = other.getXmppConnection().getMucServer();
1823				if (server != null) {
1824					return server;
1825				}
1826			}
1827		}
1828		return null;
1829	}
1830
1831	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1832		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1833		if (account.getStatus() == Account.State.ONLINE) {
1834			try {
1835				String server = findConferenceServer(account);
1836				if (server == null) {
1837					if (callback != null) {
1838						callback.error(R.string.no_conference_server_found, null);
1839					}
1840					return;
1841				}
1842				String name = new BigInteger(75, getRNG()).toString(32);
1843				Jid jid = Jid.fromParts(name, server, null);
1844				final Conversation conversation = findOrCreateConversation(account, jid, true);
1845				joinMuc(conversation);
1846				Bundle options = new Bundle();
1847				options.putString("muc#roomconfig_persistentroom", "1");
1848				options.putString("muc#roomconfig_membersonly", "1");
1849				options.putString("muc#roomconfig_publicroom", "0");
1850				options.putString("muc#roomconfig_whois", "anyone");
1851				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1852					@Override
1853					public void onPushSucceeded() {
1854						for (Jid invite : jids) {
1855							invite(conversation, invite);
1856						}
1857						if (account.countPresences() > 1) {
1858							directInvite(conversation, account.getJid().toBareJid());
1859						}
1860						if (callback != null) {
1861							callback.success(conversation);
1862						}
1863					}
1864
1865					@Override
1866					public void onPushFailed() {
1867						if (callback != null) {
1868							callback.error(R.string.conference_creation_failed, conversation);
1869						}
1870					}
1871				});
1872
1873			} catch (InvalidJidException e) {
1874				if (callback != null) {
1875					callback.error(R.string.conference_creation_failed, null);
1876				}
1877			}
1878		} else {
1879			if (callback != null) {
1880				callback.error(R.string.not_connected_try_again, null);
1881			}
1882		}
1883	}
1884
1885	public void fetchConferenceConfiguration(final Conversation conversation) {
1886		fetchConferenceConfiguration(conversation, null);
1887	}
1888
1889	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1890		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1891		request.setTo(conversation.getJid().toBareJid());
1892		request.query("http://jabber.org/protocol/disco#info");
1893		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1894			@Override
1895			public void onIqPacketReceived(Account account, IqPacket packet) {
1896				if (packet.getType() == IqPacket.TYPE.RESULT) {
1897					ArrayList<String> features = new ArrayList<>();
1898					for (Element child : packet.query().getChildren()) {
1899						if (child != null && child.getName().equals("feature")) {
1900							String var = child.getAttribute("var");
1901							if (var != null) {
1902								features.add(var);
1903							}
1904						}
1905					}
1906					conversation.getMucOptions().updateFeatures(features);
1907					if (callback != null) {
1908						callback.onConferenceConfigurationFetched(conversation);
1909					}
1910					updateConversationUi();
1911				}
1912			}
1913		});
1914	}
1915
1916	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1917		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1918		request.setTo(conversation.getJid().toBareJid());
1919		request.query("http://jabber.org/protocol/muc#owner");
1920		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1921			@Override
1922			public void onIqPacketReceived(Account account, IqPacket packet) {
1923				if (packet.getType() == IqPacket.TYPE.RESULT) {
1924					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1925					for (Field field : data.getFields()) {
1926						if (options.containsKey(field.getFieldName())) {
1927							field.setValue(options.getString(field.getFieldName()));
1928						}
1929					}
1930					data.submit();
1931					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1932					set.setTo(conversation.getJid().toBareJid());
1933					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1934					sendIqPacket(account, set, new OnIqPacketReceived() {
1935						@Override
1936						public void onIqPacketReceived(Account account, IqPacket packet) {
1937							if (callback != null) {
1938								if (packet.getType() == IqPacket.TYPE.RESULT) {
1939									callback.onPushSucceeded();
1940								} else {
1941									callback.onPushFailed();
1942								}
1943							}
1944						}
1945					});
1946				} else {
1947					if (callback != null) {
1948						callback.onPushFailed();
1949					}
1950				}
1951			}
1952		});
1953	}
1954
1955	public void pushSubjectToConference(final Conversation conference, final String subject) {
1956		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1957		this.sendMessagePacket(conference.getAccount(), packet);
1958		final MucOptions mucOptions = conference.getMucOptions();
1959		final MucOptions.User self = mucOptions.getSelf();
1960		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1961			Bundle options = new Bundle();
1962			options.putString("muc#roomconfig_persistentroom", "1");
1963			this.pushConferenceConfiguration(conference, options, null);
1964		}
1965	}
1966
1967	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1968		final Jid jid = user.toBareJid();
1969		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1970		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1971			@Override
1972			public void onIqPacketReceived(Account account, IqPacket packet) {
1973				if (packet.getType() == IqPacket.TYPE.RESULT) {
1974					callback.onAffiliationChangedSuccessful(jid);
1975				} else {
1976					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1977				}
1978			}
1979		});
1980	}
1981
1982	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1983		List<Jid> jids = new ArrayList<>();
1984		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1985			if (user.getAffiliation() == before && user.getJid() != null) {
1986				jids.add(user.getJid());
1987			}
1988		}
1989		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1990		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1991	}
1992
1993	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1994		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1995		Log.d(Config.LOGTAG, request.toString());
1996		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1997			@Override
1998			public void onIqPacketReceived(Account account, IqPacket packet) {
1999				Log.d(Config.LOGTAG, packet.toString());
2000				if (packet.getType() == IqPacket.TYPE.RESULT) {
2001					callback.onRoleChangedSuccessful(nick);
2002				} else {
2003					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2004				}
2005			}
2006		});
2007	}
2008
2009	public void disconnect(Account account, boolean force) {
2010		if ((account.getStatus() == Account.State.ONLINE)
2011				|| (account.getStatus() == Account.State.DISABLED)) {
2012			if (!force) {
2013				List<Conversation> conversations = getConversations();
2014				for (Conversation conversation : conversations) {
2015					if (conversation.getAccount() == account) {
2016						if (conversation.getMode() == Conversation.MODE_MULTI) {
2017							leaveMuc(conversation);
2018						} else {
2019							if (conversation.endOtrIfNeeded()) {
2020								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2021										+ ": ended otr session with "
2022										+ conversation.getJid());
2023							}
2024						}
2025					}
2026				}
2027				sendOfflinePresence(account);
2028			}
2029			account.getXmppConnection().disconnect(force);
2030		}
2031	}
2032
2033	@Override
2034	public IBinder onBind(Intent intent) {
2035		return mBinder;
2036	}
2037
2038	public void updateMessage(Message message) {
2039		databaseBackend.updateMessage(message);
2040		updateConversationUi();
2041	}
2042
2043	protected void syncDirtyContacts(Account account) {
2044		for (Contact contact : account.getRoster().getContacts()) {
2045			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2046				pushContactToServer(contact);
2047			}
2048			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2049				deleteContactOnServer(contact);
2050			}
2051		}
2052	}
2053
2054	public void createContact(Contact contact) {
2055		SharedPreferences sharedPref = getPreferences();
2056		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
2057		if (autoGrant) {
2058			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2059			contact.setOption(Contact.Options.ASKING);
2060		}
2061		pushContactToServer(contact);
2062	}
2063
2064	public void onOtrSessionEstablished(Conversation conversation) {
2065		final Account account = conversation.getAccount();
2066		final Session otrSession = conversation.getOtrSession();
2067		Log.d(Config.LOGTAG,
2068				account.getJid().toBareJid() + " otr session established with "
2069						+ conversation.getJid() + "/"
2070						+ otrSession.getSessionID().getUserID());
2071		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2072
2073			@Override
2074			public void onMessageFound(Message message) {
2075				SessionID id = otrSession.getSessionID();
2076				try {
2077					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2078				} catch (InvalidJidException e) {
2079					return;
2080				}
2081				if (message.needsUploading()) {
2082					mJingleConnectionManager.createNewConnection(message);
2083				} else {
2084					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2085					if (outPacket != null) {
2086						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2087						message.setStatus(Message.STATUS_SEND);
2088						databaseBackend.updateMessage(message);
2089						sendMessagePacket(account, outPacket);
2090					}
2091				}
2092				updateConversationUi();
2093			}
2094		});
2095	}
2096
2097	public boolean renewSymmetricKey(Conversation conversation) {
2098		Account account = conversation.getAccount();
2099		byte[] symmetricKey = new byte[32];
2100		this.mRandom.nextBytes(symmetricKey);
2101		Session otrSession = conversation.getOtrSession();
2102		if (otrSession != null) {
2103			MessagePacket packet = new MessagePacket();
2104			packet.setType(MessagePacket.TYPE_CHAT);
2105			packet.setFrom(account.getJid());
2106			MessageGenerator.addMessageHints(packet);
2107			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2108					+ otrSession.getSessionID().getUserID());
2109			try {
2110				packet.setBody(otrSession
2111						.transformSending(CryptoHelper.FILETRANSFER
2112								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2113				sendMessagePacket(account, packet);
2114				conversation.setSymmetricKey(symmetricKey);
2115				return true;
2116			} catch (OtrException e) {
2117				return false;
2118			}
2119		}
2120		return false;
2121	}
2122
2123	public void pushContactToServer(final Contact contact) {
2124		contact.resetOption(Contact.Options.DIRTY_DELETE);
2125		contact.setOption(Contact.Options.DIRTY_PUSH);
2126		final Account account = contact.getAccount();
2127		if (account.getStatus() == Account.State.ONLINE) {
2128			final boolean ask = contact.getOption(Contact.Options.ASKING);
2129			final boolean sendUpdates = contact
2130					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2131					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2132			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2133			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2134			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2135			if (sendUpdates) {
2136				sendPresencePacket(account,
2137						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2138			}
2139			if (ask) {
2140				sendPresencePacket(account,
2141						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2142			}
2143		}
2144	}
2145
2146	public void publishAvatar(final Account account,
2147							  final Uri image,
2148							  final UiCallback<Avatar> callback) {
2149		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2150		final int size = Config.AVATAR_SIZE;
2151		final Avatar avatar = getFileBackend()
2152				.getPepAvatar(image, size, format);
2153		if (avatar != null) {
2154			avatar.height = size;
2155			avatar.width = size;
2156			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2157				avatar.type = "image/webp";
2158			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2159				avatar.type = "image/jpeg";
2160			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2161				avatar.type = "image/png";
2162			}
2163			if (!getFileBackend().save(avatar)) {
2164				callback.error(R.string.error_saving_avatar, avatar);
2165				return;
2166			}
2167			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2168			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2169
2170				@Override
2171				public void onIqPacketReceived(Account account, IqPacket result) {
2172					if (result.getType() == IqPacket.TYPE.RESULT) {
2173						final IqPacket packet = XmppConnectionService.this.mIqGenerator
2174								.publishAvatarMetadata(avatar);
2175						sendIqPacket(account, packet, new OnIqPacketReceived() {
2176							@Override
2177							public void onIqPacketReceived(Account account, IqPacket result) {
2178								if (result.getType() == IqPacket.TYPE.RESULT) {
2179									if (account.setAvatar(avatar.getFilename())) {
2180										getAvatarService().clear(account);
2181										databaseBackend.updateAccount(account);
2182									}
2183									callback.success(avatar);
2184								} else {
2185									callback.error(
2186											R.string.error_publish_avatar_server_reject,
2187											avatar);
2188								}
2189							}
2190						});
2191					} else {
2192						callback.error(
2193								R.string.error_publish_avatar_server_reject,
2194								avatar);
2195					}
2196				}
2197			});
2198		} else {
2199			callback.error(R.string.error_publish_avatar_converting, null);
2200		}
2201	}
2202
2203	public void fetchAvatar(Account account, Avatar avatar) {
2204		fetchAvatar(account, avatar, null);
2205	}
2206
2207	private static String generateFetchKey(Account account, final Avatar avatar) {
2208		return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
2209	}
2210
2211	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2212		final String KEY = generateFetchKey(account, avatar);
2213		synchronized(this.mInProgressAvatarFetches) {
2214			if (this.mInProgressAvatarFetches.contains(KEY)) {
2215				return;
2216			} else {
2217				switch (avatar.origin) {
2218					case PEP:
2219						this.mInProgressAvatarFetches.add(KEY);
2220						fetchAvatarPep(account, avatar, callback);
2221						break;
2222					case VCARD:
2223						this.mInProgressAvatarFetches.add(KEY);
2224						fetchAvatarVcard(account, avatar, callback);
2225						break;
2226				}
2227			}
2228		}
2229	}
2230
2231	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2232		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2233		sendIqPacket(account, packet, new OnIqPacketReceived() {
2234
2235			@Override
2236			public void onIqPacketReceived(Account account, IqPacket result) {
2237				synchronized (mInProgressAvatarFetches) {
2238					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2239				}
2240				final String ERROR = account.getJid().toBareJid()
2241						+ ": fetching avatar for " + avatar.owner + " failed ";
2242				if (result.getType() == IqPacket.TYPE.RESULT) {
2243					avatar.image = mIqParser.avatarData(result);
2244					if (avatar.image != null) {
2245						if (getFileBackend().save(avatar)) {
2246							if (account.getJid().toBareJid().equals(avatar.owner)) {
2247								if (account.setAvatar(avatar.getFilename())) {
2248									databaseBackend.updateAccount(account);
2249								}
2250								getAvatarService().clear(account);
2251								updateConversationUi();
2252								updateAccountUi();
2253							} else {
2254								Contact contact = account.getRoster()
2255										.getContact(avatar.owner);
2256								contact.setAvatar(avatar);
2257								getAvatarService().clear(contact);
2258								updateConversationUi();
2259								updateRosterUi();
2260							}
2261							if (callback != null) {
2262								callback.success(avatar);
2263							}
2264							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2265									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2266							return;
2267						}
2268					} else {
2269
2270						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2271					}
2272				} else {
2273					Element error = result.findChild("error");
2274					if (error == null) {
2275						Log.d(Config.LOGTAG, ERROR + "(server error)");
2276					} else {
2277						Log.d(Config.LOGTAG, ERROR + error.toString());
2278					}
2279				}
2280				if (callback != null) {
2281					callback.error(0, null);
2282				}
2283
2284			}
2285		});
2286	}
2287
2288	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2289		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2290		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2291			@Override
2292			public void onIqPacketReceived(Account account, IqPacket packet) {
2293				synchronized (mInProgressAvatarFetches) {
2294					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2295				}
2296				if (packet.getType() == IqPacket.TYPE.RESULT) {
2297					Element vCard = packet.findChild("vCard", "vcard-temp");
2298					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2299					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2300					if (image != null) {
2301						avatar.image = image;
2302						if (getFileBackend().save(avatar)) {
2303							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2304									+ ": successfully fetched vCard avatar for " + avatar.owner);
2305							Contact contact = account.getRoster()
2306									.getContact(avatar.owner);
2307							contact.setAvatar(avatar);
2308							getAvatarService().clear(contact);
2309							updateConversationUi();
2310							updateRosterUi();
2311						}
2312					}
2313				}
2314			}
2315		});
2316	}
2317
2318	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2319		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2320		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2321
2322			@Override
2323			public void onIqPacketReceived(Account account, IqPacket packet) {
2324				if (packet.getType() == IqPacket.TYPE.RESULT) {
2325					Element pubsub = packet.findChild("pubsub",
2326							"http://jabber.org/protocol/pubsub");
2327					if (pubsub != null) {
2328						Element items = pubsub.findChild("items");
2329						if (items != null) {
2330							Avatar avatar = Avatar.parseMetadata(items);
2331							if (avatar != null) {
2332								avatar.owner = account.getJid().toBareJid();
2333								if (fileBackend.isAvatarCached(avatar)) {
2334									if (account.setAvatar(avatar.getFilename())) {
2335										databaseBackend.updateAccount(account);
2336									}
2337									getAvatarService().clear(account);
2338									callback.success(avatar);
2339								} else {
2340									fetchAvatarPep(account, avatar, callback);
2341								}
2342								return;
2343							}
2344						}
2345					}
2346				}
2347				callback.error(0, null);
2348			}
2349		});
2350	}
2351
2352	public void deleteContactOnServer(Contact contact) {
2353		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2354		contact.resetOption(Contact.Options.DIRTY_PUSH);
2355		contact.setOption(Contact.Options.DIRTY_DELETE);
2356		Account account = contact.getAccount();
2357		if (account.getStatus() == Account.State.ONLINE) {
2358			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2359			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2360			item.setAttribute("jid", contact.getJid().toString());
2361			item.setAttribute("subscription", "remove");
2362			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2363		}
2364	}
2365
2366	public void updateConversation(Conversation conversation) {
2367		this.databaseBackend.updateConversation(conversation);
2368	}
2369
2370	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2371		synchronized (account) {
2372			if (account.getXmppConnection() != null) {
2373				disconnect(account, force);
2374			}
2375			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2376
2377				synchronized (this.mInProgressAvatarFetches) {
2378					for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2379						final String KEY = iterator.next();
2380						if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2381							iterator.remove();
2382						}
2383					}
2384				}
2385
2386				if (account.getXmppConnection() == null) {
2387					account.setXmppConnection(createConnection(account));
2388				}
2389				Thread thread = new Thread(account.getXmppConnection());
2390				account.getXmppConnection().setInteractive(interactive);
2391				thread.start();
2392				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2393			} else {
2394				account.getRoster().clearPresences();
2395				account.setXmppConnection(null);
2396			}
2397		}
2398	}
2399
2400	public void reconnectAccountInBackground(final Account account) {
2401		new Thread(new Runnable() {
2402			@Override
2403			public void run() {
2404				reconnectAccount(account,false,true);
2405			}
2406		}).start();
2407	}
2408
2409	public void invite(Conversation conversation, Jid contact) {
2410		Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2411		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2412		sendMessagePacket(conversation.getAccount(), packet);
2413	}
2414
2415	public void directInvite(Conversation conversation, Jid jid) {
2416		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2417		sendMessagePacket(conversation.getAccount(),packet);
2418	}
2419
2420	public void resetSendingToWaiting(Account account) {
2421		for (Conversation conversation : getConversations()) {
2422			if (conversation.getAccount() == account) {
2423				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2424
2425					@Override
2426					public void onMessageFound(Message message) {
2427						markMessage(message, Message.STATUS_WAITING);
2428					}
2429				});
2430			}
2431		}
2432	}
2433
2434	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2435		if (uuid == null) {
2436			return null;
2437		}
2438		for (Conversation conversation : getConversations()) {
2439			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2440				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2441				if (message != null) {
2442					markMessage(message, status);
2443				}
2444				return message;
2445			}
2446		}
2447		return null;
2448	}
2449
2450	public boolean markMessage(Conversation conversation, String uuid, int status) {
2451		if (uuid == null) {
2452			return false;
2453		} else {
2454			Message message = conversation.findSentMessageWithUuid(uuid);
2455			if (message != null) {
2456				markMessage(message, status);
2457				return true;
2458			} else {
2459				return false;
2460			}
2461		}
2462	}
2463
2464	public void markMessage(Message message, int status) {
2465		if (status == Message.STATUS_SEND_FAILED
2466				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2467				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2468			return;
2469		}
2470		message.setStatus(status);
2471		databaseBackend.updateMessage(message);
2472		updateConversationUi();
2473	}
2474
2475	public SharedPreferences getPreferences() {
2476		return PreferenceManager
2477				.getDefaultSharedPreferences(getApplicationContext());
2478	}
2479
2480	public boolean forceEncryption() {
2481		return getPreferences().getBoolean("force_encryption", false);
2482	}
2483
2484	public boolean confirmMessages() {
2485		return getPreferences().getBoolean("confirm_messages", true);
2486	}
2487
2488	public boolean sendChatStates() {
2489		return getPreferences().getBoolean("chat_states", false);
2490	}
2491
2492	public boolean saveEncryptedMessages() {
2493		return !getPreferences().getBoolean("dont_save_encrypted", false);
2494	}
2495
2496	public boolean indicateReceived() {
2497		return getPreferences().getBoolean("indicate_received", false);
2498	}
2499
2500	public int unreadCount() {
2501		int count = 0;
2502		for(Conversation conversation : getConversations()) {
2503			count += conversation.unreadCount();
2504		}
2505		return count;
2506	}
2507
2508
2509	public void showErrorToastInUi(int resId) {
2510		if (mOnShowErrorToast != null) {
2511			mOnShowErrorToast.onShowErrorToast(resId);
2512		}
2513	}
2514
2515	public void updateConversationUi() {
2516		if (mOnConversationUpdate != null) {
2517			mOnConversationUpdate.onConversationUpdate();
2518		}
2519	}
2520
2521	public void updateAccountUi() {
2522		if (mOnAccountUpdate != null) {
2523			mOnAccountUpdate.onAccountUpdate();
2524		}
2525	}
2526
2527	public void updateRosterUi() {
2528		if (mOnRosterUpdate != null) {
2529			mOnRosterUpdate.onRosterUpdate();
2530		}
2531	}
2532
2533	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2534		boolean rc = false;
2535		if (mOnCaptchaRequested != null) {
2536			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2537			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int)(captcha.getWidth() * metrics.scaledDensity),
2538						(int)(captcha.getHeight() * metrics.scaledDensity), false);
2539
2540			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2541			rc = true;
2542		}
2543
2544		return rc;
2545	}
2546
2547	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2548		if (mOnUpdateBlocklist != null) {
2549			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2550		}
2551	}
2552
2553	public void updateMucRosterUi() {
2554		if (mOnMucRosterUpdate != null) {
2555			mOnMucRosterUpdate.onMucRosterUpdate();
2556		}
2557	}
2558
2559	public void keyStatusUpdated() {
2560		if(mOnKeyStatusUpdated != null) {
2561			mOnKeyStatusUpdated.onKeyStatusUpdated();
2562		}
2563	}
2564
2565	public Account findAccountByJid(final Jid accountJid) {
2566		for (Account account : this.accounts) {
2567			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2568				return account;
2569			}
2570		}
2571		return null;
2572	}
2573
2574	public Conversation findConversationByUuid(String uuid) {
2575		for (Conversation conversation : getConversations()) {
2576			if (conversation.getUuid().equals(uuid)) {
2577				return conversation;
2578			}
2579		}
2580		return null;
2581	}
2582
2583	public void markRead(final Conversation conversation) {
2584		mNotificationService.clear(conversation);
2585		for(Message message : conversation.markRead()) {
2586			databaseBackend.updateMessage(message);
2587		}
2588		updateUnreadCountBadge();
2589	}
2590
2591	public synchronized void updateUnreadCountBadge() {
2592		int count = unreadCount();
2593		if (unreadCount != count) {
2594			Log.d(Config.LOGTAG, "update unread count to " + count);
2595			if (count > 0) {
2596				ShortcutBadger.with(getApplicationContext()).count(count);
2597			} else {
2598				ShortcutBadger.with(getApplicationContext()).remove();
2599			}
2600			unreadCount = count;
2601		}
2602	}
2603
2604	public void sendReadMarker(final Conversation conversation) {
2605		final Message markable = conversation.getLatestMarkableMessage();
2606		this.markRead(conversation);
2607		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2608			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2609			Account account = conversation.getAccount();
2610			final Jid to = markable.getCounterpart();
2611			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2612			this.sendMessagePacket(conversation.getAccount(), packet);
2613		}
2614		updateConversationUi();
2615	}
2616
2617	public SecureRandom getRNG() {
2618		return this.mRandom;
2619	}
2620
2621	public MemorizingTrustManager getMemorizingTrustManager() {
2622		return this.mMemorizingTrustManager;
2623	}
2624
2625	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2626		this.mMemorizingTrustManager = trustManager;
2627	}
2628
2629	public void updateMemorizingTrustmanager() {
2630		final MemorizingTrustManager tm;
2631		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2632		if (dontTrustSystemCAs) {
2633			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2634		} else {
2635			tm = new MemorizingTrustManager(getApplicationContext());
2636		}
2637		setMemorizingTrustManager(tm);
2638	}
2639
2640	public PowerManager getPowerManager() {
2641		return this.pm;
2642	}
2643
2644	public LruCache<String, Bitmap> getBitmapCache() {
2645		return this.mBitmapCache;
2646	}
2647
2648	public void syncRosterToDisk(final Account account) {
2649		Runnable runnable = new Runnable() {
2650
2651			@Override
2652			public void run() {
2653				databaseBackend.writeRoster(account.getRoster());
2654			}
2655		};
2656		mDatabaseExecutor.execute(runnable);
2657
2658	}
2659
2660	public List<String> getKnownHosts() {
2661		final List<String> hosts = new ArrayList<>();
2662		for (final Account account : getAccounts()) {
2663			if (!hosts.contains(account.getServer().toString())) {
2664				hosts.add(account.getServer().toString());
2665			}
2666			for (final Contact contact : account.getRoster().getContacts()) {
2667				if (contact.showInRoster()) {
2668					final String server = contact.getServer().toString();
2669					if (server != null && !hosts.contains(server)) {
2670						hosts.add(server);
2671					}
2672				}
2673			}
2674		}
2675		return hosts;
2676	}
2677
2678	public List<String> getKnownConferenceHosts() {
2679		final ArrayList<String> mucServers = new ArrayList<>();
2680		for (final Account account : accounts) {
2681			if (account.getXmppConnection() != null) {
2682				final String server = account.getXmppConnection().getMucServer();
2683				if (server != null && !mucServers.contains(server)) {
2684					mucServers.add(server);
2685				}
2686			}
2687		}
2688		return mucServers;
2689	}
2690
2691	public void sendMessagePacket(Account account, MessagePacket packet) {
2692		XmppConnection connection = account.getXmppConnection();
2693		if (connection != null) {
2694			connection.sendMessagePacket(packet);
2695		}
2696	}
2697
2698	public void sendPresencePacket(Account account, PresencePacket packet) {
2699		XmppConnection connection = account.getXmppConnection();
2700		if (connection != null) {
2701			connection.sendPresencePacket(packet);
2702		}
2703	}
2704
2705	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2706		XmppConnection connection = account.getXmppConnection();
2707		if (connection != null) {
2708			connection.sendCaptchaRegistryRequest(id, data);
2709		}
2710	}
2711
2712	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2713		final XmppConnection connection = account.getXmppConnection();
2714		if (connection != null) {
2715			connection.sendIqPacket(packet, callback);
2716		}
2717	}
2718
2719	public void sendPresence(final Account account) {
2720		sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2721	}
2722
2723	public void refreshAllPresences() {
2724		for (Account account : getAccounts()) {
2725			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2726				sendPresence(account);
2727			}
2728		}
2729	}
2730
2731	public void sendOfflinePresence(final Account account) {
2732		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2733	}
2734
2735	public MessageGenerator getMessageGenerator() {
2736		return this.mMessageGenerator;
2737	}
2738
2739	public PresenceGenerator getPresenceGenerator() {
2740		return this.mPresenceGenerator;
2741	}
2742
2743	public IqGenerator getIqGenerator() {
2744		return this.mIqGenerator;
2745	}
2746
2747	public IqParser getIqParser() {
2748		return this.mIqParser;
2749	}
2750
2751	public JingleConnectionManager getJingleConnectionManager() {
2752		return this.mJingleConnectionManager;
2753	}
2754
2755	public MessageArchiveService getMessageArchiveService() {
2756		return this.mMessageArchiveService;
2757	}
2758
2759	public List<Contact> findContacts(Jid jid) {
2760		ArrayList<Contact> contacts = new ArrayList<>();
2761		for (Account account : getAccounts()) {
2762			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2763				Contact contact = account.getRoster().getContactFromRoster(jid);
2764				if (contact != null) {
2765					contacts.add(contact);
2766				}
2767			}
2768		}
2769		return contacts;
2770	}
2771
2772	public NotificationService getNotificationService() {
2773		return this.mNotificationService;
2774	}
2775
2776	public HttpConnectionManager getHttpConnectionManager() {
2777		return this.mHttpConnectionManager;
2778	}
2779
2780	public void resendFailedMessages(final Message message) {
2781		final Collection<Message> messages = new ArrayList<>();
2782		Message current = message;
2783		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2784			messages.add(current);
2785			if (current.mergeable(current.next())) {
2786				current = current.next();
2787			} else {
2788				break;
2789			}
2790		}
2791		for (final Message msg : messages) {
2792			msg.setTime(System.currentTimeMillis());
2793			markMessage(msg, Message.STATUS_WAITING);
2794			this.resendMessage(msg,false);
2795		}
2796	}
2797
2798	public void clearConversationHistory(final Conversation conversation) {
2799		conversation.clearMessages();
2800		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2801		conversation.resetLastMessageTransmitted();
2802		new Thread(new Runnable() {
2803			@Override
2804			public void run() {
2805				databaseBackend.deleteMessagesInConversation(conversation);
2806			}
2807		}).start();
2808	}
2809
2810	public void sendBlockRequest(final Blockable blockable) {
2811		if (blockable != null && blockable.getBlockedJid() != null) {
2812			final Jid jid = blockable.getBlockedJid();
2813			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2814
2815				@Override
2816				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2817					if (packet.getType() == IqPacket.TYPE.RESULT) {
2818						account.getBlocklist().add(jid);
2819						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2820					}
2821				}
2822			});
2823		}
2824	}
2825
2826	public void sendUnblockRequest(final Blockable blockable) {
2827		if (blockable != null && blockable.getJid() != null) {
2828			final Jid jid = blockable.getBlockedJid();
2829			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2830				@Override
2831				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2832					if (packet.getType() == IqPacket.TYPE.RESULT) {
2833						account.getBlocklist().remove(jid);
2834						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2835					}
2836				}
2837			});
2838		}
2839	}
2840
2841	public interface OnAccountCreated {
2842		void onAccountCreated(Account account);
2843		void informUser(int r);
2844	}
2845
2846	public interface OnMoreMessagesLoaded {
2847		void onMoreMessagesLoaded(int count, Conversation conversation);
2848
2849		void informUser(int r);
2850	}
2851
2852	public interface OnAccountPasswordChanged {
2853		void onPasswordChangeSucceeded();
2854
2855		void onPasswordChangeFailed();
2856	}
2857
2858	public interface OnAffiliationChanged {
2859		void onAffiliationChangedSuccessful(Jid jid);
2860
2861		void onAffiliationChangeFailed(Jid jid, int resId);
2862	}
2863
2864	public interface OnRoleChanged {
2865		void onRoleChangedSuccessful(String nick);
2866
2867		void onRoleChangeFailed(String nick, int resid);
2868	}
2869
2870	public interface OnConversationUpdate {
2871		void onConversationUpdate();
2872	}
2873
2874	public interface OnAccountUpdate {
2875		void onAccountUpdate();
2876	}
2877
2878	public interface OnCaptchaRequested {
2879		void onCaptchaRequested(Account account,
2880					String id,
2881					Data data,
2882					Bitmap captcha);
2883	}
2884
2885	public interface OnRosterUpdate {
2886		void onRosterUpdate();
2887	}
2888
2889	public interface OnMucRosterUpdate {
2890		void onMucRosterUpdate();
2891	}
2892
2893	public interface OnConferenceConfigurationFetched {
2894		void onConferenceConfigurationFetched(Conversation conversation);
2895	}
2896
2897	public interface OnConferenceOptionsPushed {
2898		void onPushSucceeded();
2899
2900		void onPushFailed();
2901	}
2902
2903	public interface OnShowErrorToast {
2904		void onShowErrorToast(int resId);
2905	}
2906
2907	public class XmppConnectionBinder extends Binder {
2908		public XmppConnectionService getService() {
2909			return XmppConnectionService.this;
2910		}
2911	}
2912}