XmppConnectionService.java

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