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