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.ERROR) {
 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.ERROR) {
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.ERROR) {
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 (packet.getType() == IqPacket.TYPE.RESULT) {
1720								if (callback != null) {
1721									callback.onPushSucceeded();
1722								}
1723							} else {
1724								if (callback != null) {
1725									callback.onPushFailed();
1726								}
1727							}
1728						}
1729					});
1730				} else {
1731					if (callback != null) {
1732						callback.onPushFailed();
1733					}
1734				}
1735			}
1736		});
1737	}
1738
1739	public void pushSubjectToConference(final Conversation conference, final String subject) {
1740		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1741		this.sendMessagePacket(conference.getAccount(), packet);
1742		final MucOptions mucOptions = conference.getMucOptions();
1743		final MucOptions.User self = mucOptions.getSelf();
1744		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1745			Bundle options = new Bundle();
1746			options.putString("muc#roomconfig_persistentroom", "1");
1747			this.pushConferenceConfiguration(conference, options, null);
1748		}
1749	}
1750
1751	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1752		final Jid jid = user.toBareJid();
1753		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1754		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1755			@Override
1756			public void onIqPacketReceived(Account account, IqPacket packet) {
1757				if (packet.getType() == IqPacket.TYPE.RESULT) {
1758					callback.onAffiliationChangedSuccessful(jid);
1759				} else {
1760					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1761				}
1762			}
1763		});
1764	}
1765
1766	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1767		List<Jid> jids = new ArrayList<>();
1768		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1769			if (user.getAffiliation() == before && user.getJid() != null) {
1770				jids.add(user.getJid());
1771			}
1772		}
1773		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1774		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1775	}
1776
1777	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1778		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1779		Log.d(Config.LOGTAG, request.toString());
1780		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1781			@Override
1782			public void onIqPacketReceived(Account account, IqPacket packet) {
1783				Log.d(Config.LOGTAG, packet.toString());
1784				if (packet.getType() == IqPacket.TYPE.RESULT) {
1785					callback.onRoleChangedSuccessful(nick);
1786				} else {
1787					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1788				}
1789			}
1790		});
1791	}
1792
1793	public void disconnect(Account account, boolean force) {
1794		if ((account.getStatus() == Account.State.ONLINE)
1795				|| (account.getStatus() == Account.State.DISABLED)) {
1796			if (!force) {
1797				List<Conversation> conversations = getConversations();
1798				for (Conversation conversation : conversations) {
1799					if (conversation.getAccount() == account) {
1800						if (conversation.getMode() == Conversation.MODE_MULTI) {
1801							leaveMuc(conversation);
1802						} else {
1803							if (conversation.endOtrIfNeeded()) {
1804								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1805										+ ": ended otr session with "
1806										+ conversation.getJid());
1807							}
1808						}
1809					}
1810				}
1811				sendOfflinePresence(account);
1812			}
1813			account.getXmppConnection().disconnect(force);
1814		}
1815	}
1816
1817	@Override
1818	public IBinder onBind(Intent intent) {
1819		return mBinder;
1820	}
1821
1822	public void updateMessage(Message message) {
1823		databaseBackend.updateMessage(message);
1824		updateConversationUi();
1825	}
1826
1827	protected void syncDirtyContacts(Account account) {
1828		for (Contact contact : account.getRoster().getContacts()) {
1829			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1830				pushContactToServer(contact);
1831			}
1832			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1833				deleteContactOnServer(contact);
1834			}
1835		}
1836	}
1837
1838	public void createContact(Contact contact) {
1839		SharedPreferences sharedPref = getPreferences();
1840		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1841		if (autoGrant) {
1842			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1843			contact.setOption(Contact.Options.ASKING);
1844		}
1845		pushContactToServer(contact);
1846	}
1847
1848	public void onOtrSessionEstablished(Conversation conversation) {
1849		final Account account = conversation.getAccount();
1850		final Session otrSession = conversation.getOtrSession();
1851		Log.d(Config.LOGTAG,
1852				account.getJid().toBareJid() + " otr session established with "
1853						+ conversation.getJid() + "/"
1854						+ otrSession.getSessionID().getUserID());
1855		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
1856
1857			@Override
1858			public void onMessageFound(Message message) {
1859				SessionID id = otrSession.getSessionID();
1860				try {
1861					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1862				} catch (InvalidJidException e) {
1863					return;
1864				}
1865				if (message.needsUploading()) {
1866					mJingleConnectionManager.createNewConnection(message);
1867				} else {
1868					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
1869					if (outPacket != null) {
1870						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
1871						message.setStatus(Message.STATUS_SEND);
1872						databaseBackend.updateMessage(message);
1873						sendMessagePacket(account, outPacket);
1874					}
1875				}
1876				updateConversationUi();
1877			}
1878		});
1879	}
1880
1881	public boolean renewSymmetricKey(Conversation conversation) {
1882		Account account = conversation.getAccount();
1883		byte[] symmetricKey = new byte[32];
1884		this.mRandom.nextBytes(symmetricKey);
1885		Session otrSession = conversation.getOtrSession();
1886		if (otrSession != null) {
1887			MessagePacket packet = new MessagePacket();
1888			packet.setType(MessagePacket.TYPE_CHAT);
1889			packet.setFrom(account.getJid());
1890			packet.addChild("private", "urn:xmpp:carbons:2");
1891			packet.addChild("no-copy", "urn:xmpp:hints");
1892			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1893					+ otrSession.getSessionID().getUserID());
1894			try {
1895				packet.setBody(otrSession
1896						.transformSending(CryptoHelper.FILETRANSFER
1897								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1898				sendMessagePacket(account, packet);
1899				conversation.setSymmetricKey(symmetricKey);
1900				return true;
1901			} catch (OtrException e) {
1902				return false;
1903			}
1904		}
1905		return false;
1906	}
1907
1908	public void pushContactToServer(final Contact contact) {
1909		contact.resetOption(Contact.Options.DIRTY_DELETE);
1910		contact.setOption(Contact.Options.DIRTY_PUSH);
1911		final Account account = contact.getAccount();
1912		if (account.getStatus() == Account.State.ONLINE) {
1913			final boolean ask = contact.getOption(Contact.Options.ASKING);
1914			final boolean sendUpdates = contact
1915					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1916					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1917			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1918			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1919			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1920			if (sendUpdates) {
1921				sendPresencePacket(account,
1922						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1923			}
1924			if (ask) {
1925				sendPresencePacket(account,
1926						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1927			}
1928		}
1929	}
1930
1931	public void publishAvatar(final Account account,
1932							  final Uri image,
1933							  final UiCallback<Avatar> callback) {
1934		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1935		final int size = Config.AVATAR_SIZE;
1936		final Avatar avatar = getFileBackend()
1937				.getPepAvatar(image, size, format);
1938		if (avatar != null) {
1939			avatar.height = size;
1940			avatar.width = size;
1941			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1942				avatar.type = "image/webp";
1943			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1944				avatar.type = "image/jpeg";
1945			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1946				avatar.type = "image/png";
1947			}
1948			if (!getFileBackend().save(avatar)) {
1949				callback.error(R.string.error_saving_avatar, avatar);
1950				return;
1951			}
1952			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1953			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1954
1955				@Override
1956				public void onIqPacketReceived(Account account, IqPacket result) {
1957					if (result.getType() == IqPacket.TYPE.RESULT) {
1958						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1959								.publishAvatarMetadata(avatar);
1960						sendIqPacket(account, packet, new OnIqPacketReceived() {
1961							@Override
1962							public void onIqPacketReceived(Account account, IqPacket result) {
1963								if (result.getType() == IqPacket.TYPE.RESULT) {
1964									if (account.setAvatar(avatar.getFilename())) {
1965										getAvatarService().clear(account);
1966										databaseBackend.updateAccount(account);
1967									}
1968									callback.success(avatar);
1969								} else {
1970									callback.error(
1971											R.string.error_publish_avatar_server_reject,
1972											avatar);
1973								}
1974							}
1975						});
1976					} else {
1977						callback.error(
1978								R.string.error_publish_avatar_server_reject,
1979								avatar);
1980					}
1981				}
1982			});
1983		} else {
1984			callback.error(R.string.error_publish_avatar_converting, null);
1985		}
1986	}
1987
1988	public void fetchAvatar(Account account, Avatar avatar) {
1989		fetchAvatar(account, avatar, null);
1990	}
1991
1992	private static String generateFetchKey(Account account, final Avatar avatar) {
1993		return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1994	}
1995
1996	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1997		final String KEY = generateFetchKey(account, avatar);
1998		synchronized(this.mInProgressAvatarFetches) {
1999			if (this.mInProgressAvatarFetches.contains(KEY)) {
2000				return;
2001			} else {
2002				switch (avatar.origin) {
2003					case PEP:
2004						this.mInProgressAvatarFetches.add(KEY);
2005						fetchAvatarPep(account, avatar, callback);
2006						break;
2007					case VCARD:
2008						this.mInProgressAvatarFetches.add(KEY);
2009						fetchAvatarVcard(account, avatar, callback);
2010						break;
2011				}
2012			}
2013		}
2014	}
2015
2016	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2017		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2018		sendIqPacket(account, packet, new OnIqPacketReceived() {
2019
2020			@Override
2021			public void onIqPacketReceived(Account account, IqPacket result) {
2022				synchronized (mInProgressAvatarFetches) {
2023					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2024				}
2025				final String ERROR = account.getJid().toBareJid()
2026						+ ": fetching avatar for " + avatar.owner + " failed ";
2027				if (result.getType() == IqPacket.TYPE.RESULT) {
2028					avatar.image = mIqParser.avatarData(result);
2029					if (avatar.image != null) {
2030						if (getFileBackend().save(avatar)) {
2031							if (account.getJid().toBareJid().equals(avatar.owner)) {
2032								if (account.setAvatar(avatar.getFilename())) {
2033									databaseBackend.updateAccount(account);
2034								}
2035								getAvatarService().clear(account);
2036								updateConversationUi();
2037								updateAccountUi();
2038							} else {
2039								Contact contact = account.getRoster()
2040										.getContact(avatar.owner);
2041								contact.setAvatar(avatar);
2042								getAvatarService().clear(contact);
2043								updateConversationUi();
2044								updateRosterUi();
2045							}
2046							if (callback != null) {
2047								callback.success(avatar);
2048							}
2049							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2050									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2051							return;
2052						}
2053					} else {
2054
2055						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2056					}
2057				} else {
2058					Element error = result.findChild("error");
2059					if (error == null) {
2060						Log.d(Config.LOGTAG, ERROR + "(server error)");
2061					} else {
2062						Log.d(Config.LOGTAG, ERROR + error.toString());
2063					}
2064				}
2065				if (callback != null) {
2066					callback.error(0, null);
2067				}
2068
2069			}
2070		});
2071	}
2072
2073	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2074		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2075		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2076			@Override
2077			public void onIqPacketReceived(Account account, IqPacket packet) {
2078				synchronized (mInProgressAvatarFetches) {
2079					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2080				}
2081				if (packet.getType() == IqPacket.TYPE.RESULT) {
2082					Element vCard = packet.findChild("vCard", "vcard-temp");
2083					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2084					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2085					if (image != null) {
2086						avatar.image = image;
2087						if (getFileBackend().save(avatar)) {
2088							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2089									+ ": successfully fetched vCard avatar for " + avatar.owner);
2090							Contact contact = account.getRoster()
2091									.getContact(avatar.owner);
2092							contact.setAvatar(avatar);
2093							getAvatarService().clear(contact);
2094							updateConversationUi();
2095							updateRosterUi();
2096						}
2097					}
2098				}
2099			}
2100		});
2101	}
2102
2103	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2104		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2105		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2106
2107			@Override
2108			public void onIqPacketReceived(Account account, IqPacket packet) {
2109				if (packet.getType() == IqPacket.TYPE.RESULT) {
2110					Element pubsub = packet.findChild("pubsub",
2111							"http://jabber.org/protocol/pubsub");
2112					if (pubsub != null) {
2113						Element items = pubsub.findChild("items");
2114						if (items != null) {
2115							Avatar avatar = Avatar.parseMetadata(items);
2116							if (avatar != null) {
2117								avatar.owner = account.getJid().toBareJid();
2118								if (fileBackend.isAvatarCached(avatar)) {
2119									if (account.setAvatar(avatar.getFilename())) {
2120										databaseBackend.updateAccount(account);
2121									}
2122									getAvatarService().clear(account);
2123									callback.success(avatar);
2124								} else {
2125									fetchAvatarPep(account, avatar, callback);
2126								}
2127								return;
2128							}
2129						}
2130					}
2131				}
2132				callback.error(0, null);
2133			}
2134		});
2135	}
2136
2137	public void deleteContactOnServer(Contact contact) {
2138		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2139		contact.resetOption(Contact.Options.DIRTY_PUSH);
2140		contact.setOption(Contact.Options.DIRTY_DELETE);
2141		Account account = contact.getAccount();
2142		if (account.getStatus() == Account.State.ONLINE) {
2143			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2144			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2145			item.setAttribute("jid", contact.getJid().toString());
2146			item.setAttribute("subscription", "remove");
2147			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2148		}
2149	}
2150
2151	public void updateConversation(Conversation conversation) {
2152		this.databaseBackend.updateConversation(conversation);
2153	}
2154
2155	public void reconnectAccount(final Account account, final boolean force) {
2156		synchronized (account) {
2157			if (account.getXmppConnection() != null) {
2158				disconnect(account, force);
2159			}
2160			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2161
2162				synchronized (this.mInProgressAvatarFetches) {
2163					for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2164						final String KEY = iterator.next();
2165						if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2166							iterator.remove();
2167						}
2168					}
2169				}
2170
2171				if (account.getXmppConnection() == null) {
2172					account.setXmppConnection(createConnection(account));
2173				}
2174				Thread thread = new Thread(account.getXmppConnection());
2175				thread.start();
2176				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2177			} else {
2178				account.getRoster().clearPresences();
2179				account.setXmppConnection(null);
2180			}
2181		}
2182	}
2183
2184	public void reconnectAccountInBackground(final Account account) {
2185		new Thread(new Runnable() {
2186			@Override
2187			public void run() {
2188				reconnectAccount(account,false);
2189			}
2190		}).start();
2191	}
2192
2193	public void invite(Conversation conversation, Jid contact) {
2194		Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2195		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2196		sendMessagePacket(conversation.getAccount(), packet);
2197	}
2198
2199	public void directInvite(Conversation conversation, Jid jid) {
2200		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2201		sendMessagePacket(conversation.getAccount(),packet);
2202	}
2203
2204	public void resetSendingToWaiting(Account account) {
2205		for (Conversation conversation : getConversations()) {
2206			if (conversation.getAccount() == account) {
2207				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2208
2209					@Override
2210					public void onMessageFound(Message message) {
2211						markMessage(message, Message.STATUS_WAITING);
2212					}
2213				});
2214			}
2215		}
2216	}
2217
2218	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2219		if (uuid == null) {
2220			return null;
2221		}
2222		for (Conversation conversation : getConversations()) {
2223			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2224				final Message message = conversation.findSentMessageWithUuid(uuid);
2225				if (message != null) {
2226					markMessage(message, status);
2227				}
2228				return message;
2229			}
2230		}
2231		return null;
2232	}
2233
2234	public boolean markMessage(Conversation conversation, String uuid,
2235							   int status) {
2236		if (uuid == null) {
2237			return false;
2238		} else {
2239			Message message = conversation.findSentMessageWithUuid(uuid);
2240			if (message != null) {
2241				markMessage(message, status);
2242				return true;
2243			} else {
2244				return false;
2245			}
2246		}
2247	}
2248
2249	public void markMessage(Message message, int status) {
2250		if (status == Message.STATUS_SEND_FAILED
2251				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2252				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2253			return;
2254		}
2255		message.setStatus(status);
2256		databaseBackend.updateMessage(message);
2257		updateConversationUi();
2258	}
2259
2260	public SharedPreferences getPreferences() {
2261		return PreferenceManager
2262				.getDefaultSharedPreferences(getApplicationContext());
2263	}
2264
2265	public boolean forceEncryption() {
2266		return getPreferences().getBoolean("force_encryption", false);
2267	}
2268
2269	public boolean confirmMessages() {
2270		return getPreferences().getBoolean("confirm_messages", true);
2271	}
2272
2273	public boolean sendChatStates() {
2274		return getPreferences().getBoolean("chat_states", false);
2275	}
2276
2277	public boolean saveEncryptedMessages() {
2278		return !getPreferences().getBoolean("dont_save_encrypted", false);
2279	}
2280
2281	public boolean indicateReceived() {
2282		return getPreferences().getBoolean("indicate_received", false);
2283	}
2284
2285	public int unreadCount() {
2286		int count = 0;
2287		for(Conversation conversation : getConversations()) {
2288			count += conversation.unreadCount();
2289		}
2290		return count;
2291	}
2292
2293
2294	public void showErrorToastInUi(int resId) {
2295		if (mOnShowErrorToast != null) {
2296			mOnShowErrorToast.onShowErrorToast(resId);
2297		}
2298	}
2299
2300	public void updateConversationUi() {
2301		if (mOnConversationUpdate != null) {
2302			mOnConversationUpdate.onConversationUpdate();
2303		}
2304	}
2305
2306	public void updateAccountUi() {
2307		if (mOnAccountUpdate != null) {
2308			mOnAccountUpdate.onAccountUpdate();
2309		}
2310	}
2311
2312	public void updateRosterUi() {
2313		if (mOnRosterUpdate != null) {
2314			mOnRosterUpdate.onRosterUpdate();
2315		}
2316	}
2317
2318	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2319		if (mOnUpdateBlocklist != null) {
2320			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2321		}
2322	}
2323
2324	public void updateMucRosterUi() {
2325		if (mOnMucRosterUpdate != null) {
2326			mOnMucRosterUpdate.onMucRosterUpdate();
2327		}
2328	}
2329
2330	public void keyStatusUpdated() {
2331		if(mOnKeyStatusUpdated != null) {
2332			mOnKeyStatusUpdated.onKeyStatusUpdated();
2333		}
2334	}
2335
2336	public Account findAccountByJid(final Jid accountJid) {
2337		for (Account account : this.accounts) {
2338			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2339				return account;
2340			}
2341		}
2342		return null;
2343	}
2344
2345	public Conversation findConversationByUuid(String uuid) {
2346		for (Conversation conversation : getConversations()) {
2347			if (conversation.getUuid().equals(uuid)) {
2348				return conversation;
2349			}
2350		}
2351		return null;
2352	}
2353
2354	public void markRead(final Conversation conversation) {
2355		mNotificationService.clear(conversation);
2356		conversation.markRead();
2357		updateUnreadCountBadge();
2358	}
2359
2360	public synchronized void updateUnreadCountBadge() {
2361		int count = unreadCount();
2362		if (unreadCount != count) {
2363			Log.d(Config.LOGTAG, "update unread count to " + count);
2364			if (count > 0) {
2365				ShortcutBadger.with(getApplicationContext()).count(count);
2366			} else {
2367				ShortcutBadger.with(getApplicationContext()).remove();
2368			}
2369			unreadCount = count;
2370		}
2371	}
2372
2373	public void sendReadMarker(final Conversation conversation) {
2374		final Message markable = conversation.getLatestMarkableMessage();
2375		this.markRead(conversation);
2376		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2377			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2378			Account account = conversation.getAccount();
2379			final Jid to = markable.getCounterpart();
2380			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2381			this.sendMessagePacket(conversation.getAccount(), packet);
2382		}
2383		updateConversationUi();
2384	}
2385
2386	public SecureRandom getRNG() {
2387		return this.mRandom;
2388	}
2389
2390	public MemorizingTrustManager getMemorizingTrustManager() {
2391		return this.mMemorizingTrustManager;
2392	}
2393
2394	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2395		this.mMemorizingTrustManager = trustManager;
2396	}
2397
2398	public void updateMemorizingTrustmanager() {
2399		final MemorizingTrustManager tm;
2400		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2401		if (dontTrustSystemCAs) {
2402			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2403		} else {
2404			tm = new MemorizingTrustManager(getApplicationContext());
2405		}
2406		setMemorizingTrustManager(tm);
2407	}
2408
2409	public PowerManager getPowerManager() {
2410		return this.pm;
2411	}
2412
2413	public LruCache<String, Bitmap> getBitmapCache() {
2414		return this.mBitmapCache;
2415	}
2416
2417	public void syncRosterToDisk(final Account account) {
2418		Runnable runnable = new Runnable() {
2419
2420			@Override
2421			public void run() {
2422				databaseBackend.writeRoster(account.getRoster());
2423			}
2424		};
2425		mDatabaseExecutor.execute(runnable);
2426
2427	}
2428
2429	public List<String> getKnownHosts() {
2430		final List<String> hosts = new ArrayList<>();
2431		for (final Account account : getAccounts()) {
2432			if (!hosts.contains(account.getServer().toString())) {
2433				hosts.add(account.getServer().toString());
2434			}
2435			for (final Contact contact : account.getRoster().getContacts()) {
2436				if (contact.showInRoster()) {
2437					final String server = contact.getServer().toString();
2438					if (server != null && !hosts.contains(server)) {
2439						hosts.add(server);
2440					}
2441				}
2442			}
2443		}
2444		return hosts;
2445	}
2446
2447	public List<String> getKnownConferenceHosts() {
2448		final ArrayList<String> mucServers = new ArrayList<>();
2449		for (final Account account : accounts) {
2450			if (account.getXmppConnection() != null) {
2451				final String server = account.getXmppConnection().getMucServer();
2452				if (server != null && !mucServers.contains(server)) {
2453					mucServers.add(server);
2454				}
2455			}
2456		}
2457		return mucServers;
2458	}
2459
2460	public void sendMessagePacket(Account account, MessagePacket packet) {
2461		XmppConnection connection = account.getXmppConnection();
2462		if (connection != null) {
2463			connection.sendMessagePacket(packet);
2464		}
2465	}
2466
2467	public void sendPresencePacket(Account account, PresencePacket packet) {
2468		XmppConnection connection = account.getXmppConnection();
2469		if (connection != null) {
2470			connection.sendPresencePacket(packet);
2471		}
2472	}
2473
2474	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2475		final XmppConnection connection = account.getXmppConnection();
2476		if (connection != null) {
2477			connection.sendIqPacket(packet, callback);
2478		}
2479	}
2480
2481	public void sendPresence(final Account account) {
2482		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2483	}
2484
2485	public void sendOfflinePresence(final Account account) {
2486		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2487	}
2488
2489	public MessageGenerator getMessageGenerator() {
2490		return this.mMessageGenerator;
2491	}
2492
2493	public PresenceGenerator getPresenceGenerator() {
2494		return this.mPresenceGenerator;
2495	}
2496
2497	public IqGenerator getIqGenerator() {
2498		return this.mIqGenerator;
2499	}
2500
2501	public IqParser getIqParser() {
2502		return this.mIqParser;
2503	}
2504
2505	public JingleConnectionManager getJingleConnectionManager() {
2506		return this.mJingleConnectionManager;
2507	}
2508
2509	public MessageArchiveService getMessageArchiveService() {
2510		return this.mMessageArchiveService;
2511	}
2512
2513	public List<Contact> findContacts(Jid jid) {
2514		ArrayList<Contact> contacts = new ArrayList<>();
2515		for (Account account : getAccounts()) {
2516			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2517				Contact contact = account.getRoster().getContactFromRoster(jid);
2518				if (contact != null) {
2519					contacts.add(contact);
2520				}
2521			}
2522		}
2523		return contacts;
2524	}
2525
2526	public NotificationService getNotificationService() {
2527		return this.mNotificationService;
2528	}
2529
2530	public HttpConnectionManager getHttpConnectionManager() {
2531		return this.mHttpConnectionManager;
2532	}
2533
2534	public void resendFailedMessages(final Message message) {
2535		final Collection<Message> messages = new ArrayList<>();
2536		Message current = message;
2537		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2538			messages.add(current);
2539			if (current.mergeable(current.next())) {
2540				current = current.next();
2541			} else {
2542				break;
2543			}
2544		}
2545		for (final Message msg : messages) {
2546			msg.setTime(System.currentTimeMillis());
2547			markMessage(msg, Message.STATUS_WAITING);
2548			this.resendMessage(msg,false);
2549		}
2550	}
2551
2552	public void clearConversationHistory(final Conversation conversation) {
2553		conversation.clearMessages();
2554		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2555		new Thread(new Runnable() {
2556			@Override
2557			public void run() {
2558				databaseBackend.deleteMessagesInConversation(conversation);
2559			}
2560		}).start();
2561	}
2562
2563	public void sendBlockRequest(final Blockable blockable) {
2564		if (blockable != null && blockable.getBlockedJid() != null) {
2565			final Jid jid = blockable.getBlockedJid();
2566			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2567
2568				@Override
2569				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2570					if (packet.getType() == IqPacket.TYPE.RESULT) {
2571						account.getBlocklist().add(jid);
2572						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2573					}
2574				}
2575			});
2576		}
2577	}
2578
2579	public void sendUnblockRequest(final Blockable blockable) {
2580		if (blockable != null && blockable.getJid() != null) {
2581			final Jid jid = blockable.getBlockedJid();
2582			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2583				@Override
2584				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2585					if (packet.getType() == IqPacket.TYPE.RESULT) {
2586						account.getBlocklist().remove(jid);
2587						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2588					}
2589				}
2590			});
2591		}
2592	}
2593
2594	public interface OnMoreMessagesLoaded {
2595		public void onMoreMessagesLoaded(int count, Conversation conversation);
2596
2597		public void informUser(int r);
2598	}
2599
2600	public interface OnAccountPasswordChanged {
2601		public void onPasswordChangeSucceeded();
2602
2603		public void onPasswordChangeFailed();
2604	}
2605
2606	public interface OnAffiliationChanged {
2607		public void onAffiliationChangedSuccessful(Jid jid);
2608
2609		public void onAffiliationChangeFailed(Jid jid, int resId);
2610	}
2611
2612	public interface OnRoleChanged {
2613		public void onRoleChangedSuccessful(String nick);
2614
2615		public void onRoleChangeFailed(String nick, int resid);
2616	}
2617
2618	public interface OnConversationUpdate {
2619		public void onConversationUpdate();
2620	}
2621
2622	public interface OnAccountUpdate {
2623		public void onAccountUpdate();
2624	}
2625
2626	public interface OnRosterUpdate {
2627		public void onRosterUpdate();
2628	}
2629
2630	public interface OnMucRosterUpdate {
2631		public void onMucRosterUpdate();
2632	}
2633
2634	public interface OnConferenceOptionsPushed {
2635		public void onPushSucceeded();
2636
2637		public void onPushFailed();
2638	}
2639
2640	public interface OnShowErrorToast {
2641		void onShowErrorToast(int resId);
2642	}
2643
2644	public class XmppConnectionBinder extends Binder {
2645		public XmppConnectionService getService() {
2646			return XmppConnectionService.this;
2647		}
2648	}
2649}