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