XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.annotation.SuppressLint;
   4import android.annotation.TargetApi;
   5import android.app.AlarmManager;
   6import android.app.PendingIntent;
   7import android.app.Service;
   8import android.content.Context;
   9import android.content.Intent;
  10import android.content.IntentFilter;
  11import android.content.SharedPreferences;
  12import android.database.ContentObserver;
  13import android.graphics.Bitmap;
  14import android.media.AudioManager;
  15import android.net.ConnectivityManager;
  16import android.net.NetworkInfo;
  17import android.net.Uri;
  18import android.os.Binder;
  19import android.os.Build;
  20import android.os.Bundle;
  21import android.os.Environment;
  22import android.os.IBinder;
  23import android.os.PowerManager;
  24import android.os.PowerManager.WakeLock;
  25import android.os.SystemClock;
  26import android.preference.PreferenceManager;
  27import android.provider.ContactsContract;
  28import android.security.KeyChain;
  29import android.support.v4.app.RemoteInput;
  30import android.util.DisplayMetrics;
  31import android.util.Log;
  32import android.util.LruCache;
  33import android.util.Pair;
  34
  35import net.java.otr4j.OtrException;
  36import net.java.otr4j.session.Session;
  37import net.java.otr4j.session.SessionID;
  38import net.java.otr4j.session.SessionImpl;
  39import net.java.otr4j.session.SessionStatus;
  40
  41import org.openintents.openpgp.IOpenPgpService2;
  42import org.openintents.openpgp.util.OpenPgpApi;
  43import org.openintents.openpgp.util.OpenPgpServiceConnection;
  44
  45import java.math.BigInteger;
  46import java.security.SecureRandom;
  47import java.security.cert.CertificateException;
  48import java.security.cert.X509Certificate;
  49import java.util.ArrayList;
  50import java.util.Arrays;
  51import java.util.Collection;
  52import java.util.Collections;
  53import java.util.HashMap;
  54import java.util.HashSet;
  55import java.util.Hashtable;
  56import java.util.Iterator;
  57import java.util.List;
  58import java.util.Locale;
  59import java.util.Map;
  60import java.util.concurrent.CopyOnWriteArrayList;
  61
  62import de.duenndns.ssl.MemorizingTrustManager;
  63import eu.siacs.conversations.Config;
  64import eu.siacs.conversations.R;
  65import eu.siacs.conversations.crypto.PgpDecryptionService;
  66import eu.siacs.conversations.crypto.PgpEngine;
  67import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  68import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  69import eu.siacs.conversations.entities.Account;
  70import eu.siacs.conversations.entities.Blockable;
  71import eu.siacs.conversations.entities.Bookmark;
  72import eu.siacs.conversations.entities.Contact;
  73import eu.siacs.conversations.entities.Conversation;
  74import eu.siacs.conversations.entities.DownloadableFile;
  75import eu.siacs.conversations.entities.Message;
  76import eu.siacs.conversations.entities.MucOptions;
  77import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  78import eu.siacs.conversations.entities.Presence;
  79import eu.siacs.conversations.entities.PresenceTemplate;
  80import eu.siacs.conversations.entities.Roster;
  81import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  82import eu.siacs.conversations.entities.Transferable;
  83import eu.siacs.conversations.entities.TransferablePlaceholder;
  84import eu.siacs.conversations.generator.AbstractGenerator;
  85import eu.siacs.conversations.generator.IqGenerator;
  86import eu.siacs.conversations.generator.MessageGenerator;
  87import eu.siacs.conversations.generator.PresenceGenerator;
  88import eu.siacs.conversations.http.HttpConnectionManager;
  89import eu.siacs.conversations.parser.AbstractParser;
  90import eu.siacs.conversations.parser.IqParser;
  91import eu.siacs.conversations.parser.MessageParser;
  92import eu.siacs.conversations.parser.PresenceParser;
  93import eu.siacs.conversations.persistance.DatabaseBackend;
  94import eu.siacs.conversations.persistance.FileBackend;
  95import eu.siacs.conversations.ui.UiCallback;
  96import eu.siacs.conversations.utils.ConversationsFileObserver;
  97import eu.siacs.conversations.utils.CryptoHelper;
  98import eu.siacs.conversations.utils.ExceptionHelper;
  99import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
 100import eu.siacs.conversations.utils.PRNGFixes;
 101import eu.siacs.conversations.utils.PhoneHelper;
 102import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
 103import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 104import eu.siacs.conversations.utils.Xmlns;
 105import eu.siacs.conversations.xml.Element;
 106import eu.siacs.conversations.xmpp.OnBindListener;
 107import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 108import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 109import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 110import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
 111import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 112import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 113import eu.siacs.conversations.xmpp.OnStatusChanged;
 114import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 115import eu.siacs.conversations.xmpp.XmppConnection;
 116import eu.siacs.conversations.xmpp.chatstate.ChatState;
 117import eu.siacs.conversations.xmpp.forms.Data;
 118import eu.siacs.conversations.xmpp.forms.Field;
 119import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 120import eu.siacs.conversations.xmpp.jid.Jid;
 121import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 122import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 123import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 124import eu.siacs.conversations.xmpp.pep.Avatar;
 125import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 126import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 127import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 128import me.leolin.shortcutbadger.ShortcutBadger;
 129
 130public class XmppConnectionService extends Service {
 131
 132	public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
 133	public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 134	public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
 135	public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
 136	public static final String ACTION_TRY_AGAIN = "try_again";
 137	public static final String ACTION_IDLE_PING = "idle_ping";
 138	private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
 139	public static final String ACTION_GCM_TOKEN_REFRESH = "gcm_token_refresh";
 140	public static final String ACTION_GCM_MESSAGE_RECEIVED = "gcm_message_received";
 141	private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
 142	private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
 143	private ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor(true);
 144	private final IBinder mBinder = new XmppConnectionBinder();
 145	private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 146	private final IqGenerator mIqGenerator = new IqGenerator(this);
 147	private final List<String> mInProgressAvatarFetches = new ArrayList<>();
 148	private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
 149
 150	private long mLastActivity = 0;
 151
 152	public DatabaseBackend databaseBackend;
 153	private ContentObserver contactObserver = new ContentObserver(null) {
 154		@Override
 155		public void onChange(boolean selfChange) {
 156			super.onChange(selfChange);
 157			Intent intent = new Intent(getApplicationContext(),
 158					XmppConnectionService.class);
 159			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 160			startService(intent);
 161		}
 162	};
 163	private FileBackend fileBackend = new FileBackend(this);
 164	private MemorizingTrustManager mMemorizingTrustManager;
 165	private NotificationService mNotificationService = new NotificationService(
 166			this);
 167	private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 168	private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 169	private IqParser mIqParser = new IqParser(this);
 170	private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
 171		@Override
 172		public void onIqPacketReceived(Account account, IqPacket packet) {
 173			if (packet.getType() != IqPacket.TYPE.RESULT) {
 174				Element error = packet.findChild("error");
 175				String text = error != null ? error.findChildContent("text") : null;
 176				if (text != null) {
 177					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
 178				}
 179			}
 180		}
 181	};
 182	private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 183	private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 184	private List<Account> accounts;
 185	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 186			this);
 187	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
 188
 189		@Override
 190		public void onContactStatusChanged(Contact contact, boolean online) {
 191			Conversation conversation = find(getConversations(), contact);
 192			if (conversation != null) {
 193				if (online) {
 194					conversation.endOtrIfNeeded();
 195					if (contact.getPresences().size() == 1) {
 196						sendUnsentMessages(conversation);
 197					}
 198				} else {
 199					//check if the resource we are haveing a conversation with is still online
 200					if (conversation.hasValidOtrSession()) {
 201						String otrResource = conversation.getOtrSession().getSessionID().getUserID();
 202						if (!(Arrays.asList(contact.getPresences().toResourceArray()).contains(otrResource))) {
 203							conversation.endOtrIfNeeded();
 204						}
 205					}
 206				}
 207			}
 208		}
 209	};
 210	private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 211			this);
 212	private AvatarService mAvatarService = new AvatarService(this);
 213	private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 214	private PushManagementService mPushManagementService = new PushManagementService(this);
 215	private OnConversationUpdate mOnConversationUpdate = null;
 216
 217
 218	private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
 219			Environment.getExternalStorageDirectory().getAbsolutePath()
 220	) {
 221		@Override
 222		public void onEvent(int event, String path) {
 223			markFileDeleted(path);
 224		}
 225	};
 226	private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 227
 228		@Override
 229		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 230			mJingleConnectionManager.deliverPacket(account, packet);
 231		}
 232	};
 233	private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 234
 235		@Override
 236		public void onMessageAcknowledged(Account account, String uuid) {
 237			for (final Conversation conversation : getConversations()) {
 238				if (conversation.getAccount() == account) {
 239					Message message = conversation.findUnsentMessageWithUuid(uuid);
 240					if (message != null) {
 241						markMessage(message, Message.STATUS_SEND);
 242					}
 243				}
 244			}
 245		}
 246	};
 247	private int convChangedListenerCount = 0;
 248	private OnShowErrorToast mOnShowErrorToast = null;
 249	private int showErrorToastListenerCount = 0;
 250	private int unreadCount = -1;
 251	private OnAccountUpdate mOnAccountUpdate = null;
 252	private OnCaptchaRequested mOnCaptchaRequested = null;
 253	private int accountChangedListenerCount = 0;
 254	private int captchaRequestedListenerCount = 0;
 255	private OnRosterUpdate mOnRosterUpdate = null;
 256	private OnUpdateBlocklist mOnUpdateBlocklist = null;
 257	private int updateBlocklistListenerCount = 0;
 258	private int rosterChangedListenerCount = 0;
 259	private OnMucRosterUpdate mOnMucRosterUpdate = null;
 260	private int mucRosterChangedListenerCount = 0;
 261	private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
 262	private int keyStatusUpdatedListenerCount = 0;
 263	private SecureRandom mRandom;
 264	private LruCache<Pair<String,String>,ServiceDiscoveryResult> discoCache = new LruCache<>(20);
 265	private final OnBindListener mOnBindListener = new OnBindListener() {
 266
 267		@Override
 268		public void onBind(final Account account) {
 269			synchronized (mInProgressAvatarFetches) {
 270				for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
 271					final String KEY = iterator.next();
 272					if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
 273						iterator.remove();
 274					}
 275				}
 276			}
 277			account.getRoster().clearPresences();
 278			mJingleConnectionManager.cancelInTransmission();
 279			fetchRosterFromServer(account);
 280			fetchBookmarks(account);
 281			sendPresence(account);
 282			if (mPushManagementService.available(account)) {
 283				mPushManagementService.registerPushTokenOnServer(account);
 284			}
 285			connectMultiModeConversations(account);
 286			syncDirtyContacts(account);
 287		}
 288	};
 289	private OnStatusChanged statusListener = new OnStatusChanged() {
 290
 291		@Override
 292		public void onStatusChanged(final Account account) {
 293			XmppConnection connection = account.getXmppConnection();
 294			if (mOnAccountUpdate != null) {
 295				mOnAccountUpdate.onAccountUpdate();
 296			}
 297			if (account.getStatus() == Account.State.ONLINE) {
 298				synchronized (mLowPingTimeoutMode) {
 299					if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) {
 300						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode");
 301					}
 302				}
 303				if (account.setShowErrorNotification(true)) {
 304					databaseBackend.updateAccount(account);
 305				}
 306				mMessageArchiveService.executePendingQueries(account);
 307				if (connection != null && connection.getFeatures().csi()) {
 308					if (checkListeners()) {
 309						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
 310						connection.sendInactive();
 311					} else {
 312						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
 313						connection.sendActive();
 314					}
 315				}
 316				List<Conversation> conversations = getConversations();
 317				for (Conversation conversation : conversations) {
 318					if (conversation.getAccount() == account
 319							&& !account.pendingConferenceJoins.contains(conversation)) {
 320						if (!conversation.startOtrIfNeeded()) {
 321							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": couldn't start OTR with "+conversation.getContact().getJid()+" when needed");
 322						}
 323						sendUnsentMessages(conversation);
 324					}
 325				}
 326				for (Conversation conversation : account.pendingConferenceLeaves) {
 327					leaveMuc(conversation);
 328				}
 329				account.pendingConferenceLeaves.clear();
 330				for (Conversation conversation : account.pendingConferenceJoins) {
 331					joinMuc(conversation);
 332				}
 333				account.pendingConferenceJoins.clear();
 334				scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 335			} else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
 336				resetSendingToWaiting(account);
 337				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 338					synchronized (mLowPingTimeoutMode) {
 339						if (mLowPingTimeoutMode.contains(account.getJid().toBareJid())) {
 340							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": went into offline state during low ping mode. reconnecting now");
 341							reconnectAccount(account, true, false);
 342						} else {
 343							int timeToReconnect = mRandom.nextInt(20) + 10;
 344							scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 345						}
 346					}
 347				}
 348			} else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 349				databaseBackend.updateAccount(account);
 350				reconnectAccount(account, true, false);
 351			} else if ((account.getStatus() != Account.State.CONNECTING)
 352					&& (account.getStatus() != Account.State.NO_INTERNET)) {
 353				resetSendingToWaiting(account);
 354				if (connection != null) {
 355					int next = connection.getTimeToNextAttempt();
 356					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 357							+ ": error connecting account. try again in "
 358							+ next + "s for the "
 359							+ (connection.getAttempt() + 1) + " time");
 360					scheduleWakeUpCall(next, account.getUuid().hashCode());
 361				}
 362			}
 363			getNotificationService().updateErrorNotification();
 364		}
 365	};
 366	private OpenPgpServiceConnection pgpServiceConnection;
 367	private PgpEngine mPgpEngine = null;
 368	private WakeLock wakeLock;
 369	private PowerManager pm;
 370	private LruCache<String, Bitmap> mBitmapCache;
 371	private EventReceiver mEventReceiver = new EventReceiver();
 372
 373	private boolean mRestoredFromDatabase = false;
 374
 375	private static String generateFetchKey(Account account, final Avatar avatar) {
 376		return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 377	}
 378
 379	public boolean areMessagesInitialized() {
 380		return this.mRestoredFromDatabase;
 381	}
 382
 383	public PgpEngine getPgpEngine() {
 384		if (!Config.supportOpenPgp()) {
 385			return null;
 386		} else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 387			if (this.mPgpEngine == null) {
 388				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 389						getApplicationContext(),
 390						pgpServiceConnection.getService()), this);
 391			}
 392			return mPgpEngine;
 393		} else {
 394			return null;
 395		}
 396
 397	}
 398
 399	public OpenPgpApi getOpenPgpApi() {
 400		if (!Config.supportOpenPgp()) {
 401			return null;
 402		} else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 403			return new OpenPgpApi(this, pgpServiceConnection.getService());
 404		} else {
 405			return null;
 406		}
 407	}
 408
 409	public FileBackend getFileBackend() {
 410		return this.fileBackend;
 411	}
 412
 413	public AvatarService getAvatarService() {
 414		return this.mAvatarService;
 415	}
 416
 417	public void attachLocationToConversation(final Conversation conversation,
 418											 final Uri uri,
 419											 final UiCallback<Message> callback) {
 420		int encryption = conversation.getNextEncryption();
 421		if (encryption == Message.ENCRYPTION_PGP) {
 422			encryption = Message.ENCRYPTION_DECRYPTED;
 423		}
 424		Message message = new Message(conversation, uri.toString(), encryption);
 425		if (conversation.getNextCounterpart() != null) {
 426			message.setCounterpart(conversation.getNextCounterpart());
 427		}
 428		if (encryption == Message.ENCRYPTION_DECRYPTED) {
 429			getPgpEngine().encrypt(message, callback);
 430		} else {
 431			callback.success(message);
 432		}
 433	}
 434
 435	public void attachFileToConversation(final Conversation conversation,
 436										 final Uri uri,
 437										 final UiCallback<Message> callback) {
 438		if (FileBackend.weOwnFile(this, uri)) {
 439			Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
 440			callback.error(R.string.security_error_invalid_file_access, null);
 441			return;
 442		}
 443		final Message message;
 444		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 445			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 446		} else {
 447			message = new Message(conversation, "", conversation.getNextEncryption());
 448		}
 449		message.setCounterpart(conversation.getNextCounterpart());
 450		message.setType(Message.TYPE_FILE);
 451		final String path = getFileBackend().getOriginalPath(uri);
 452		mFileAddingExecutor.execute(new Runnable() {
 453			@Override
 454			public void run() {
 455				if (path != null) {
 456					message.setRelativeFilePath(path);
 457					getFileBackend().updateFileParams(message);
 458					if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 459						getPgpEngine().encrypt(message, callback);
 460					} else {
 461						callback.success(message);
 462					}
 463				} else {
 464					try {
 465						getFileBackend().copyFileToPrivateStorage(message, uri);
 466						getFileBackend().updateFileParams(message);
 467						if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 468							final PgpEngine pgpEngine = getPgpEngine();
 469							if (pgpEngine != null) {
 470								pgpEngine.encrypt(message, callback);
 471							} else if (callback != null) {
 472								callback.error(R.string.unable_to_connect_to_keychain, null);
 473							}
 474						} else {
 475							callback.success(message);
 476						}
 477					} catch (FileBackend.FileCopyException e) {
 478						callback.error(e.getResId(), message);
 479					}
 480				}
 481			}
 482		});
 483	}
 484
 485	public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 486		if (FileBackend.weOwnFile(this, uri)) {
 487			Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
 488			callback.error(R.string.security_error_invalid_file_access, null);
 489			return;
 490		}
 491		final String compressPictures = getCompressPicturesPreference();
 492		if ("never".equals(compressPictures)
 493				|| ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))) {
 494			Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+ ": not compressing picture. sending as file");
 495			attachFileToConversation(conversation, uri, callback);
 496			return;
 497		}
 498		final Message message;
 499		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 500			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 501		} else {
 502			message = new Message(conversation, "", conversation.getNextEncryption());
 503		}
 504		message.setCounterpart(conversation.getNextCounterpart());
 505		message.setType(Message.TYPE_IMAGE);
 506		mFileAddingExecutor.execute(new Runnable() {
 507
 508			@Override
 509			public void run() {
 510				try {
 511					getFileBackend().copyImageToPrivateStorage(message, uri);
 512					if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 513						final PgpEngine pgpEngine = getPgpEngine();
 514						if (pgpEngine != null) {
 515							pgpEngine.encrypt(message, callback);
 516						} else if (callback != null){
 517							callback.error(R.string.unable_to_connect_to_keychain, null);
 518						}
 519					} else {
 520						callback.success(message);
 521					}
 522				} catch (final FileBackend.FileCopyException e) {
 523					callback.error(e.getResId(), message);
 524				}
 525			}
 526		});
 527	}
 528
 529	public Conversation find(Bookmark bookmark) {
 530		return find(bookmark.getAccount(), bookmark.getJid());
 531	}
 532
 533	public Conversation find(final Account account, final Jid jid) {
 534		return find(getConversations(), account, jid);
 535	}
 536
 537	@Override
 538	public int onStartCommand(Intent intent, int flags, int startId) {
 539		final String action = intent == null ? null : intent.getAction();
 540		String pushedAccountHash = null;
 541		boolean interactive = false;
 542		if (action != null) {
 543			final Conversation c = findConversationByUuid(intent.getStringExtra("uuid"));
 544			switch (action) {
 545				case ConnectivityManager.CONNECTIVITY_ACTION:
 546					if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 547						resetAllAttemptCounts(true);
 548					}
 549					break;
 550				case ACTION_MERGE_PHONE_CONTACTS:
 551					if (mRestoredFromDatabase) {
 552						loadPhoneContacts();
 553					}
 554					return START_STICKY;
 555				case Intent.ACTION_SHUTDOWN:
 556					logoutAndSave(true);
 557					return START_NOT_STICKY;
 558				case ACTION_CLEAR_NOTIFICATION:
 559					if (c != null) {
 560						mNotificationService.clear(c);
 561					} else {
 562						mNotificationService.clear();
 563					}
 564					break;
 565				case ACTION_DISABLE_FOREGROUND:
 566					getPreferences().edit().putBoolean("keep_foreground_service", false).commit();
 567					toggleForegroundService();
 568					break;
 569				case ACTION_DISMISS_ERROR_NOTIFICATIONS:
 570					dismissErrorNotifications();
 571					break;
 572				case ACTION_TRY_AGAIN:
 573					resetAllAttemptCounts(false);
 574					interactive = true;
 575					break;
 576				case ACTION_REPLY_TO_CONVERSATION:
 577					Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
 578					if (remoteInput != null && c != null) {
 579						final CharSequence body = remoteInput.getCharSequence("text_reply");
 580						if (body != null && body.length() > 0) {
 581							directReply(c, body.toString(),intent.getBooleanExtra("dismiss_notification",false));
 582						}
 583					}
 584					break;
 585				case AudioManager.RINGER_MODE_CHANGED_ACTION:
 586					if (xaOnSilentMode()) {
 587						refreshAllPresences();
 588					}
 589					break;
 590				case Intent.ACTION_SCREEN_ON:
 591					deactivateGracePeriod();
 592				case Intent.ACTION_SCREEN_OFF:
 593					if (awayWhenScreenOff()) {
 594						refreshAllPresences();
 595					}
 596					break;
 597				case ACTION_GCM_TOKEN_REFRESH:
 598					refreshAllGcmTokens();
 599					break;
 600				case ACTION_IDLE_PING:
 601					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 602						scheduleNextIdlePing();
 603					}
 604					break;
 605				case ACTION_GCM_MESSAGE_RECEIVED:
 606					Log.d(Config.LOGTAG,"gcm push message arrived in service. extras="+intent.getExtras());
 607					pushedAccountHash = intent.getStringExtra("account");
 608					break;
 609			}
 610		}
 611		this.wakeLock.acquire();
 612
 613		boolean pingNow = false;
 614		HashSet<Account> pingCandidates = new HashSet<>();
 615
 616		for (Account account : accounts) {
 617			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 618				if (!hasInternetConnection()) {
 619					account.setStatus(Account.State.NO_INTERNET);
 620					if (statusListener != null) {
 621						statusListener.onStatusChanged(account);
 622					}
 623				} else {
 624					if (account.getStatus() == Account.State.NO_INTERNET) {
 625						account.setStatus(Account.State.OFFLINE);
 626						if (statusListener != null) {
 627							statusListener.onStatusChanged(account);
 628						}
 629					}
 630					if (account.getStatus() == Account.State.ONLINE) {
 631						synchronized (mLowPingTimeoutMode) {
 632							long lastReceived = account.getXmppConnection().getLastPacketReceived();
 633							long lastSent = account.getXmppConnection().getLastPingSent();
 634							long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 635							long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 636							int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().toBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
 637							long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
 638							if (lastSent > lastReceived) {
 639								if (pingTimeoutIn < 0) {
 640									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
 641									this.reconnectAccount(account, true, interactive);
 642								} else {
 643									int secs = (int) (pingTimeoutIn / 1000);
 644									this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
 645								}
 646							} else {
 647								pingCandidates.add(account);
 648								if (CryptoHelper.getAccountFingerprint(account).equals(pushedAccountHash)) {
 649									pingNow = true;
 650									if (mLowPingTimeoutMode.add(account.getJid().toBareJid())) {
 651										Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": entering low ping timeout mode");
 652									}
 653								} else if (msToNextPing <= 0) {
 654									pingNow = true;
 655								} else {
 656									this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 657									if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) {
 658										Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode");
 659									}
 660								}
 661							}
 662						}
 663					} else if (account.getStatus() == Account.State.OFFLINE) {
 664						reconnectAccount(account, true, interactive);
 665					} else if (account.getStatus() == Account.State.CONNECTING) {
 666						long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
 667						long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
 668						long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
 669						long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
 670						if (timeout < 0) {
 671							Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
 672							account.getXmppConnection().resetAttemptCount();
 673							reconnectAccount(account, true, interactive);
 674						} else if (discoTimeout < 0) {
 675							account.getXmppConnection().sendDiscoTimeout();
 676							scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
 677						} else {
 678							scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
 679						}
 680					} else {
 681						if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 682							reconnectAccount(account, true, interactive);
 683						}
 684					}
 685				}
 686				if (mOnAccountUpdate != null) {
 687					mOnAccountUpdate.onAccountUpdate();
 688				}
 689			}
 690		}
 691		if (pingNow) {
 692			for (Account account : pingCandidates) {
 693				synchronized (mLowPingTimeoutMode) {
 694					final boolean lowTimeout = mLowPingTimeoutMode.contains(account.getJid().toBareJid());
 695					account.getXmppConnection().sendPing();
 696					Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")");
 697					scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
 698				}
 699			}
 700		}
 701		if (wakeLock.isHeld()) {
 702			try {
 703				wakeLock.release();
 704			} catch (final RuntimeException ignored) {
 705			}
 706		}
 707		return START_STICKY;
 708	}
 709
 710	public boolean isDataSaverDisabled() {
 711		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 712			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
 713			return !connectivityManager.isActiveNetworkMetered()
 714					|| connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
 715		} else {
 716			return true;
 717		}
 718	}
 719
 720	private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) {
 721		Message message = new Message(conversation,body,conversation.getNextEncryption());
 722		message.markUnread();
 723		if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 724			getPgpEngine().encrypt(message, new UiCallback<Message>() {
 725				@Override
 726				public void success(Message message) {
 727					message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 728					sendMessage(message);
 729					if (dismissAfterReply) {
 730						markRead(message.getConversation(),true);
 731					} else {
 732						mNotificationService.pushFromDirectReply(message);
 733					}
 734				}
 735
 736				@Override
 737				public void error(int errorCode, Message object) {
 738
 739				}
 740
 741				@Override
 742				public void userInputRequried(PendingIntent pi, Message object) {
 743
 744				}
 745			});
 746		} else {
 747			sendMessage(message);
 748			if (dismissAfterReply) {
 749				markRead(conversation,true);
 750			} else {
 751				mNotificationService.pushFromDirectReply(message);
 752			}
 753		}
 754	}
 755
 756	private boolean xaOnSilentMode() {
 757		return getPreferences().getBoolean("xa_on_silent_mode", false);
 758	}
 759
 760	private boolean manuallyChangePresence() {
 761		return getPreferences().getBoolean("manually_change_presence", false);
 762	}
 763
 764	private boolean treatVibrateAsSilent() {
 765		return getPreferences().getBoolean("treat_vibrate_as_silent", false);
 766	}
 767
 768	private boolean awayWhenScreenOff() {
 769		return getPreferences().getBoolean("away_when_screen_off", false);
 770	}
 771
 772	private String getCompressPicturesPreference() {
 773		return getPreferences().getString("picture_compression", "auto");
 774	}
 775
 776	private Presence.Status getTargetPresence() {
 777		if (xaOnSilentMode() && isPhoneSilenced()) {
 778			return Presence.Status.XA;
 779		} else if (awayWhenScreenOff() && !isInteractive()) {
 780			return Presence.Status.AWAY;
 781		} else {
 782			return Presence.Status.ONLINE;
 783		}
 784	}
 785
 786	@SuppressLint("NewApi")
 787	@SuppressWarnings("deprecation")
 788	public boolean isInteractive() {
 789		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 790
 791		final boolean isScreenOn;
 792		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 793			isScreenOn = pm.isScreenOn();
 794		} else {
 795			isScreenOn = pm.isInteractive();
 796		}
 797		return isScreenOn;
 798	}
 799
 800	private boolean isPhoneSilenced() {
 801		AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
 802		try {
 803			if (treatVibrateAsSilent()) {
 804				return audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
 805			} else {
 806				return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
 807			}
 808		} catch (Throwable throwable) {
 809			Log.d(Config.LOGTAG,"platform bug in isPhoneSilenced ("+ throwable.getMessage()+")");
 810			return false;
 811		}
 812	}
 813
 814	private void resetAllAttemptCounts(boolean reallyAll) {
 815		Log.d(Config.LOGTAG, "resetting all attempt counts");
 816		for (Account account : accounts) {
 817			if (account.hasErrorStatus() || reallyAll) {
 818				final XmppConnection connection = account.getXmppConnection();
 819				if (connection != null) {
 820					connection.resetAttemptCount();
 821				}
 822			}
 823			if (account.setShowErrorNotification(true)) {
 824				databaseBackend.updateAccount(account);
 825			}
 826		}
 827		mNotificationService.updateErrorNotification();
 828	}
 829
 830	private void dismissErrorNotifications() {
 831		for (final Account account : this.accounts) {
 832			if (account.hasErrorStatus()) {
 833				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": dismissing error notification");
 834				if (account.setShowErrorNotification(false)) {
 835					databaseBackend.updateAccount(account);
 836				}
 837			}
 838		}
 839	}
 840
 841	public boolean hasInternetConnection() {
 842		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 843				.getSystemService(Context.CONNECTIVITY_SERVICE);
 844		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 845		return activeNetwork != null && activeNetwork.isConnected();
 846	}
 847
 848	@SuppressLint("TrulyRandom")
 849	@Override
 850	public void onCreate() {
 851		ExceptionHelper.init(getApplicationContext());
 852		PRNGFixes.apply();
 853		this.mRandom = new SecureRandom();
 854		updateMemorizingTrustmanager();
 855		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 856		final int cacheSize = maxMemory / 8;
 857		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 858			@Override
 859			protected int sizeOf(final String key, final Bitmap bitmap) {
 860				return bitmap.getByteCount() / 1024;
 861			}
 862		};
 863
 864		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 865		this.accounts = databaseBackend.getAccounts();
 866
 867		restoreFromDatabase();
 868
 869		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 870		new Thread(new Runnable() {
 871			@Override
 872			public void run() {
 873				fileObserver.startWatching();
 874			}
 875		}).start();
 876		if (Config.supportOpenPgp()) {
 877			this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
 878				@Override
 879				public void onBound(IOpenPgpService2 service) {
 880					for (Account account : accounts) {
 881						final PgpDecryptionService pgp = account.getPgpDecryptionService();
 882						if(pgp != null) {
 883							pgp.continueDecryption(true);
 884						}
 885					}
 886				}
 887
 888				@Override
 889				public void onError(Exception e) {
 890				}
 891			});
 892			this.pgpServiceConnection.bindToService();
 893		}
 894
 895		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 896		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
 897		toggleForegroundService();
 898		updateUnreadCountBadge();
 899		toggleScreenEventReceiver();
 900		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 901			scheduleNextIdlePing();
 902		}
 903		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 904			registerReceiver(this.mEventReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
 905		}
 906	}
 907
 908	@Override
 909	public void onTrimMemory(int level) {
 910		super.onTrimMemory(level);
 911		if (level >= TRIM_MEMORY_COMPLETE) {
 912			Log.d(Config.LOGTAG, "clear cache due to low memory");
 913			getBitmapCache().evictAll();
 914		}
 915	}
 916
 917	@Override
 918	public void onDestroy() {
 919		try {
 920			unregisterReceiver(this.mEventReceiver);
 921		} catch (IllegalArgumentException e) {
 922			//ignored
 923		}
 924		fileObserver.stopWatching();
 925		super.onDestroy();
 926	}
 927
 928	public void toggleScreenEventReceiver() {
 929		if (awayWhenScreenOff() && !manuallyChangePresence()) {
 930			final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
 931			filter.addAction(Intent.ACTION_SCREEN_OFF);
 932			registerReceiver(this.mEventReceiver, filter);
 933		} else {
 934			try {
 935				unregisterReceiver(this.mEventReceiver);
 936			} catch (IllegalArgumentException e) {
 937				//ignored
 938			}
 939		}
 940	}
 941
 942	public void toggleForegroundService() {
 943		if (getPreferences().getBoolean("keep_foreground_service", false)) {
 944			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 945		} else {
 946			stopForeground(true);
 947		}
 948	}
 949
 950	@Override
 951	public void onTaskRemoved(final Intent rootIntent) {
 952		super.onTaskRemoved(rootIntent);
 953		if (!getPreferences().getBoolean("keep_foreground_service", false)) {
 954			this.logoutAndSave(false);
 955		} else {
 956			Log.d(Config.LOGTAG,"ignoring onTaskRemoved because foreground service is activated");
 957		}
 958	}
 959
 960	private void logoutAndSave(boolean stop) {
 961		int activeAccounts = 0;
 962		for (final Account account : accounts) {
 963			if (account.getStatus() != Account.State.DISABLED) {
 964				activeAccounts++;
 965			}
 966			databaseBackend.writeRoster(account.getRoster());
 967			if (account.getXmppConnection() != null) {
 968				new Thread(new Runnable() {
 969					@Override
 970					public void run() {
 971						disconnect(account, false);
 972					}
 973				}).start();
 974			}
 975		}
 976		if (stop || activeAccounts == 0) {
 977			Log.d(Config.LOGTAG, "good bye");
 978			stopSelf();
 979		}
 980	}
 981
 982	private void cancelWakeUpCall(int requestCode) {
 983		final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
 984		final Intent intent = new Intent(this, EventReceiver.class);
 985		intent.setAction("ping");
 986		alarmManager.cancel(PendingIntent.getBroadcast(this, requestCode, intent, 0));
 987	}
 988
 989	public void scheduleWakeUpCall(int seconds, int requestCode) {
 990		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
 991		AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
 992		Intent intent = new Intent(this, EventReceiver.class);
 993		intent.setAction("ping");
 994		PendingIntent alarmIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
 995		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 996	}
 997
 998	@TargetApi(Build.VERSION_CODES.M)
 999	private void scheduleNextIdlePing() {
1000		Log.d(Config.LOGTAG,"schedule next idle ping");
1001		AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1002		Intent intent = new Intent(this, EventReceiver.class);
1003		intent.setAction(ACTION_IDLE_PING);
1004		alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1005				SystemClock.elapsedRealtime()+(Config.IDLE_PING_INTERVAL * 1000),
1006				PendingIntent.getBroadcast(this,0,intent,0)
1007				);
1008	}
1009
1010	public XmppConnection createConnection(final Account account) {
1011		final SharedPreferences sharedPref = getPreferences();
1012		String resource;
1013		try {
1014			resource = sharedPref.getString("resource", getString(R.string.default_resource)).toLowerCase(Locale.ENGLISH);
1015			if (resource.trim().isEmpty()) {
1016				throw new Exception();
1017			}
1018		} catch (Exception e) {
1019			resource = "conversations";
1020		}
1021		account.setResource(resource);
1022		final XmppConnection connection = new XmppConnection(account, this);
1023		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1024		connection.setOnStatusChangedListener(this.statusListener);
1025		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1026		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1027		connection.setOnJinglePacketReceivedListener(this.jingleListener);
1028		connection.setOnBindListener(this.mOnBindListener);
1029		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1030		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1031		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1032		AxolotlService axolotlService = account.getAxolotlService();
1033		if (axolotlService != null) {
1034			connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1035		}
1036		return connection;
1037	}
1038
1039	public void sendChatState(Conversation conversation) {
1040		if (sendChatStates()) {
1041			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1042			sendMessagePacket(conversation.getAccount(), packet);
1043		}
1044	}
1045
1046	private void sendFileMessage(final Message message, final boolean delay) {
1047		Log.d(Config.LOGTAG, "send file message");
1048		final Account account = message.getConversation().getAccount();
1049		if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())) {
1050			mHttpConnectionManager.createNewUploadConnection(message, delay);
1051		} else {
1052			mJingleConnectionManager.createNewConnection(message);
1053		}
1054	}
1055
1056	public void sendMessage(final Message message) {
1057		sendMessage(message, false, false);
1058	}
1059
1060	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1061		final Account account = message.getConversation().getAccount();
1062		if (account.setShowErrorNotification(true)) {
1063			databaseBackend.updateAccount(account);
1064			mNotificationService.updateErrorNotification();
1065		}
1066		final Conversation conversation = message.getConversation();
1067		account.deactivateGracePeriod();
1068		MessagePacket packet = null;
1069		final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1070				|| account.getServerIdentity() != XmppConnection.Identity.SLACK)
1071				&& !message.edited();
1072		boolean saveInDb = addToConversation;
1073		message.setStatus(Message.STATUS_WAITING);
1074
1075		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
1076			message.getConversation().endOtrIfNeeded();
1077			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
1078					new Conversation.OnMessageFound() {
1079						@Override
1080						public void onMessageFound(Message message) {
1081							markMessage(message, Message.STATUS_SEND_FAILED);
1082						}
1083					});
1084		}
1085
1086		if (account.isOnlineAndConnected()) {
1087			switch (message.getEncryption()) {
1088				case Message.ENCRYPTION_NONE:
1089					if (message.needsUploading()) {
1090						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1091								|| message.fixCounterpart()) {
1092							this.sendFileMessage(message, delay);
1093						} else {
1094							break;
1095						}
1096					} else {
1097						packet = mMessageGenerator.generateChat(message);
1098					}
1099					break;
1100				case Message.ENCRYPTION_PGP:
1101				case Message.ENCRYPTION_DECRYPTED:
1102					if (message.needsUploading()) {
1103						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1104								|| message.fixCounterpart()) {
1105							this.sendFileMessage(message, delay);
1106						} else {
1107							break;
1108						}
1109					} else {
1110						packet = mMessageGenerator.generatePgpChat(message);
1111					}
1112					break;
1113				case Message.ENCRYPTION_OTR:
1114					SessionImpl otrSession = conversation.getOtrSession();
1115					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
1116						try {
1117							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
1118						} catch (InvalidJidException e) {
1119							break;
1120						}
1121						if (message.needsUploading()) {
1122							mJingleConnectionManager.createNewConnection(message);
1123						} else {
1124							packet = mMessageGenerator.generateOtrChat(message);
1125						}
1126					} else if (otrSession == null) {
1127						if (message.fixCounterpart()) {
1128							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
1129						} else {
1130							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fix counterpart for OTR message to contact "+message.getContact().getJid());
1131							break;
1132						}
1133					} else {
1134						Log.d(Config.LOGTAG,account.getJid().toBareJid()+" OTR session with "+message.getContact()+" is in wrong state: "+otrSession.getSessionStatus().toString());
1135					}
1136					break;
1137				case Message.ENCRYPTION_AXOLOTL:
1138					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1139					if (message.needsUploading()) {
1140						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1141								|| message.fixCounterpart()) {
1142							this.sendFileMessage(message, delay);
1143						} else {
1144							break;
1145						}
1146					} else {
1147						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1148						if (axolotlMessage == null) {
1149							account.getAxolotlService().preparePayloadMessage(message, delay);
1150						} else {
1151							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1152						}
1153					}
1154					break;
1155
1156			}
1157			if (packet != null) {
1158				if (account.getXmppConnection().getFeatures().sm()
1159						|| (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1160					message.setStatus(Message.STATUS_UNSEND);
1161				} else {
1162					message.setStatus(Message.STATUS_SEND);
1163				}
1164			}
1165		} else {
1166			switch (message.getEncryption()) {
1167				case Message.ENCRYPTION_DECRYPTED:
1168					if (!message.needsUploading()) {
1169						String pgpBody = message.getEncryptedBody();
1170						String decryptedBody = message.getBody();
1171						message.setBody(pgpBody);
1172						message.setEncryption(Message.ENCRYPTION_PGP);
1173						if (message.edited()) {
1174							message.setBody(decryptedBody);
1175							message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1176							databaseBackend.updateMessage(message, message.getEditedId());
1177							updateConversationUi();
1178							return;
1179						} else {
1180							databaseBackend.createMessage(message);
1181							saveInDb = false;
1182							message.setBody(decryptedBody);
1183							message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1184						}
1185					}
1186					break;
1187				case Message.ENCRYPTION_OTR:
1188					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
1189						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": create otr session without starting for "+message.getContact().getJid());
1190						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
1191					}
1192					break;
1193				case Message.ENCRYPTION_AXOLOTL:
1194					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1195					break;
1196			}
1197		}
1198
1199		if (resend) {
1200			if (packet != null && addToConversation) {
1201				if (account.getXmppConnection().getFeatures().sm()
1202						|| (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1203					markMessage(message, Message.STATUS_UNSEND);
1204				} else {
1205					markMessage(message, Message.STATUS_SEND);
1206				}
1207			}
1208		} else {
1209			if (addToConversation) {
1210				conversation.add(message);
1211			}
1212			if (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages()) {
1213				if (saveInDb) {
1214					databaseBackend.createMessage(message);
1215				} else if (message.edited()) {
1216					databaseBackend.updateMessage(message, message.getEditedId());
1217				}
1218			}
1219			updateConversationUi();
1220		}
1221		if (packet != null) {
1222			if (delay) {
1223				mMessageGenerator.addDelay(packet, message.getTimeSent());
1224			}
1225			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1226				if (this.sendChatStates()) {
1227					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1228				}
1229			}
1230			sendMessagePacket(account, packet);
1231		}
1232	}
1233
1234	private void sendUnsentMessages(final Conversation conversation) {
1235		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
1236
1237			@Override
1238			public void onMessageFound(Message message) {
1239				resendMessage(message, true);
1240			}
1241		});
1242	}
1243
1244	public void resendMessage(final Message message, final boolean delay) {
1245		sendMessage(message, true, delay);
1246	}
1247
1248	public void fetchRosterFromServer(final Account account) {
1249		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1250		if (!"".equals(account.getRosterVersion())) {
1251			Log.d(Config.LOGTAG, account.getJid().toBareJid()
1252					+ ": fetching roster version " + account.getRosterVersion());
1253		} else {
1254			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1255		}
1256		iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
1257		sendIqPacket(account, iqPacket, mIqParser);
1258	}
1259
1260	public void fetchBookmarks(final Account account) {
1261		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1262		final Element query = iqPacket.query("jabber:iq:private");
1263		query.addChild("storage", "storage:bookmarks");
1264		final OnIqPacketReceived callback = new OnIqPacketReceived() {
1265
1266			@Override
1267			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1268				if (packet.getType() == IqPacket.TYPE.RESULT) {
1269					final Element query = packet.query();
1270					final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1271					final Element storage = query.findChild("storage", "storage:bookmarks");
1272					final boolean autojoin = respectAutojoin();
1273					if (storage != null) {
1274						for (final Element item : storage.getChildren()) {
1275							if (item.getName().equals("conference")) {
1276								final Bookmark bookmark = Bookmark.parse(item, account);
1277								Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1278								if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1279									bookmark.setBookmarkName(old.getBookmarkName());
1280								}
1281								Conversation conversation = find(bookmark);
1282								if (conversation != null) {
1283									conversation.setBookmark(bookmark);
1284								} else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1285									conversation = findOrCreateConversation(
1286											account, bookmark.getJid(), true);
1287									conversation.setBookmark(bookmark);
1288									joinMuc(conversation);
1289								}
1290							}
1291						}
1292					}
1293					account.setBookmarks(new ArrayList<>(bookmarks.values()));
1294				} else {
1295					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1296				}
1297			}
1298		};
1299		sendIqPacket(account, iqPacket, callback);
1300	}
1301
1302	public void pushBookmarks(Account account) {
1303		Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1304		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1305		Element query = iqPacket.query("jabber:iq:private");
1306		Element storage = query.addChild("storage", "storage:bookmarks");
1307		for (Bookmark bookmark : account.getBookmarks()) {
1308			storage.addChild(bookmark);
1309		}
1310		sendIqPacket(account, iqPacket, mDefaultIqHandler);
1311	}
1312
1313	private void restoreFromDatabase() {
1314		synchronized (this.conversations) {
1315			final Map<String, Account> accountLookupTable = new Hashtable<>();
1316			for (Account account : this.accounts) {
1317				accountLookupTable.put(account.getUuid(), account);
1318			}
1319			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1320			for (Conversation conversation : this.conversations) {
1321				Account account = accountLookupTable.get(conversation.getAccountUuid());
1322				conversation.setAccount(account);
1323			}
1324			Runnable runnable = new Runnable() {
1325				@Override
1326				public void run() {
1327					Log.d(Config.LOGTAG, "restoring roster");
1328					for (Account account : accounts) {
1329						databaseBackend.readRoster(account.getRoster());
1330						account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1331					}
1332					getBitmapCache().evictAll();
1333					loadPhoneContacts();
1334					Log.d(Config.LOGTAG, "restoring messages");
1335					for (Conversation conversation : conversations) {
1336						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1337						checkDeletedFiles(conversation);
1338						conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
1339
1340							@Override
1341							public void onMessageFound(Message message) {
1342								markMessage(message, Message.STATUS_WAITING);
1343							}
1344						});
1345						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1346							@Override
1347							public void onMessageFound(Message message) {
1348								mNotificationService.pushFromBacklog(message);
1349							}
1350						});
1351					}
1352					mNotificationService.finishBacklog(false);
1353					mRestoredFromDatabase = true;
1354					Log.d(Config.LOGTAG, "restored all messages");
1355					updateConversationUi();
1356				}
1357			};
1358			mDatabaseExecutor.execute(runnable);
1359		}
1360	}
1361
1362	public void loadPhoneContacts() {
1363		mContactMergerExecutor.execute(new Runnable() {
1364			@Override
1365			public void run() {
1366				PhoneHelper.loadPhoneContacts(XmppConnectionService.this, new OnPhoneContactsLoadedListener() {
1367					@Override
1368					public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
1369						Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1370						for (Account account : accounts) {
1371							List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1372							for (Bundle phoneContact : phoneContacts) {
1373								Jid jid;
1374								try {
1375									jid = Jid.fromString(phoneContact.getString("jid"));
1376								} catch (final InvalidJidException e) {
1377									continue;
1378								}
1379								final Contact contact = account.getRoster().getContact(jid);
1380								String systemAccount = phoneContact.getInt("phoneid")
1381										+ "#"
1382										+ phoneContact.getString("lookup");
1383								contact.setSystemAccount(systemAccount);
1384								if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1385									getAvatarService().clear(contact);
1386								}
1387								contact.setSystemName(phoneContact.getString("displayname"));
1388								withSystemAccounts.remove(contact);
1389							}
1390							for (Contact contact : withSystemAccounts) {
1391								contact.setSystemAccount(null);
1392								contact.setSystemName(null);
1393								if (contact.setPhotoUri(null)) {
1394									getAvatarService().clear(contact);
1395								}
1396							}
1397						}
1398						Log.d(Config.LOGTAG, "finished merging phone contacts");
1399						updateAccountUi();
1400					}
1401				});
1402			}
1403		});
1404	}
1405
1406	public List<Conversation> getConversations() {
1407		return this.conversations;
1408	}
1409
1410	private void checkDeletedFiles(Conversation conversation) {
1411		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1412
1413			@Override
1414			public void onMessageFound(Message message) {
1415				if (!getFileBackend().isFileAvailable(message)) {
1416					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1417					final int s = message.getStatus();
1418					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1419						markMessage(message, Message.STATUS_SEND_FAILED);
1420					}
1421				}
1422			}
1423		});
1424	}
1425
1426	private void markFileDeleted(final String path) {
1427		Log.d(Config.LOGTAG,"deleted file "+path);
1428		for (Conversation conversation : getConversations()) {
1429			conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1430				@Override
1431				public void onMessageFound(Message message) {
1432					DownloadableFile file = fileBackend.getFile(message);
1433					if (file.getAbsolutePath().equals(path)) {
1434						if (!file.exists()) {
1435							message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1436							final int s = message.getStatus();
1437							if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1438								markMessage(message, Message.STATUS_SEND_FAILED);
1439							} else {
1440								updateConversationUi();
1441							}
1442						} else {
1443							Log.d(Config.LOGTAG,"found matching message for file "+path+" but file still exists");
1444						}
1445					}
1446				}
1447			});
1448		}
1449	}
1450
1451	public void populateWithOrderedConversations(final List<Conversation> list) {
1452		populateWithOrderedConversations(list, true);
1453	}
1454
1455	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1456		list.clear();
1457		if (includeNoFileUpload) {
1458			list.addAll(getConversations());
1459		} else {
1460			for (Conversation conversation : getConversations()) {
1461				if (conversation.getMode() == Conversation.MODE_SINGLE
1462						|| conversation.getAccount().httpUploadAvailable()) {
1463					list.add(conversation);
1464				}
1465			}
1466		}
1467		try {
1468			Collections.sort(list);
1469		} catch (IllegalArgumentException e) {
1470			//ignore
1471		}
1472	}
1473
1474	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1475		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1476			return;
1477		} else if (timestamp == 0) {
1478			return;
1479		}
1480		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1481		Runnable runnable = new Runnable() {
1482			@Override
1483			public void run() {
1484				final Account account = conversation.getAccount();
1485				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1486				if (messages.size() > 0) {
1487					conversation.addAll(0, messages);
1488					checkDeletedFiles(conversation);
1489					callback.onMoreMessagesLoaded(messages.size(), conversation);
1490				} else if (conversation.hasMessagesLeftOnServer()
1491						&& account.isOnlineAndConnected()
1492						&& conversation.getLastClearHistory() == 0) {
1493					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1494							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1495						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1496						if (query != null) {
1497							query.setCallback(callback);
1498						}
1499						callback.informUser(R.string.fetching_history_from_server);
1500					}
1501				}
1502			}
1503		};
1504		mDatabaseExecutor.execute(runnable);
1505	}
1506
1507	public List<Account> getAccounts() {
1508		return this.accounts;
1509	}
1510
1511	public List<Conversation> findAllConferencesWith(Contact contact) {
1512		ArrayList<Conversation> results = new ArrayList<>();
1513		for(Conversation conversation : conversations) {
1514			if (conversation.getMode() == Conversation.MODE_MULTI
1515					&& conversation.getMucOptions().isContactInRoom(contact)) {
1516				results.add(conversation);
1517			}
1518		}
1519		return results;
1520	}
1521
1522	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1523		for (final Conversation conversation : haystack) {
1524			if (conversation.getContact() == contact) {
1525				return conversation;
1526			}
1527		}
1528		return null;
1529	}
1530
1531	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1532		if (jid == null) {
1533			return null;
1534		}
1535		for (final Conversation conversation : haystack) {
1536			if ((account == null || conversation.getAccount() == account)
1537					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1538				return conversation;
1539			}
1540		}
1541		return null;
1542	}
1543
1544	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1545		return this.findOrCreateConversation(account, jid, muc, null);
1546	}
1547
1548	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1549		synchronized (this.conversations) {
1550			Conversation conversation = find(account, jid);
1551			if (conversation != null) {
1552				return conversation;
1553			}
1554			conversation = databaseBackend.findConversation(account, jid);
1555			if (conversation != null) {
1556				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1557				conversation.setAccount(account);
1558				if (muc) {
1559					conversation.setMode(Conversation.MODE_MULTI);
1560					conversation.setContactJid(jid);
1561				} else {
1562					conversation.setMode(Conversation.MODE_SINGLE);
1563					conversation.setContactJid(jid.toBareJid());
1564				}
1565				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1566				this.databaseBackend.updateConversation(conversation);
1567			} else {
1568				String conversationName;
1569				Contact contact = account.getRoster().getContact(jid);
1570				if (contact != null) {
1571					conversationName = contact.getDisplayName();
1572				} else {
1573					conversationName = jid.getLocalpart();
1574				}
1575				if (muc) {
1576					conversation = new Conversation(conversationName, account, jid,
1577							Conversation.MODE_MULTI);
1578				} else {
1579					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1580							Conversation.MODE_SINGLE);
1581				}
1582				this.databaseBackend.createConversation(conversation);
1583			}
1584			if (account.getXmppConnection() != null
1585					&& account.getXmppConnection().getFeatures().mam()
1586					&& !muc) {
1587				if (query == null) {
1588					this.mMessageArchiveService.query(conversation);
1589				} else {
1590					if (query.getConversation() == null) {
1591						this.mMessageArchiveService.query(conversation, query.getStart());
1592					}
1593				}
1594			}
1595			checkDeletedFiles(conversation);
1596			this.conversations.add(conversation);
1597			updateConversationUi();
1598			return conversation;
1599		}
1600	}
1601
1602	public void archiveConversation(Conversation conversation) {
1603		getNotificationService().clear(conversation);
1604		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1605		synchronized (this.conversations) {
1606			if (conversation.getMode() == Conversation.MODE_MULTI) {
1607				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1608					Bookmark bookmark = conversation.getBookmark();
1609					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1610						bookmark.setAutojoin(false);
1611						pushBookmarks(bookmark.getAccount());
1612					}
1613				}
1614				leaveMuc(conversation);
1615			} else {
1616				conversation.endOtrIfNeeded();
1617				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1618					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1619					sendPresencePacket(
1620							conversation.getAccount(),
1621							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1622					);
1623				}
1624			}
1625			updateConversation(conversation);
1626			this.conversations.remove(conversation);
1627			updateConversationUi();
1628		}
1629	}
1630
1631	public void createAccount(final Account account) {
1632		account.initAccountServices(this);
1633		databaseBackend.createAccount(account);
1634		this.accounts.add(account);
1635		this.reconnectAccountInBackground(account);
1636		updateAccountUi();
1637	}
1638
1639	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1640		new Thread(new Runnable() {
1641			@Override
1642			public void run() {
1643				try {
1644					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1645					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1646					if (findAccountByJid(info.first) == null) {
1647						Account account = new Account(info.first, "");
1648						account.setPrivateKeyAlias(alias);
1649						account.setOption(Account.OPTION_DISABLED, true);
1650						account.setDisplayName(info.second);
1651						createAccount(account);
1652						callback.onAccountCreated(account);
1653						if (Config.X509_VERIFICATION) {
1654							try {
1655								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1656							} catch (CertificateException e) {
1657								callback.informUser(R.string.certificate_chain_is_not_trusted);
1658							}
1659						}
1660					} else {
1661						callback.informUser(R.string.account_already_exists);
1662					}
1663				} catch (Exception e) {
1664					e.printStackTrace();
1665					callback.informUser(R.string.unable_to_parse_certificate);
1666				}
1667			}
1668		}).start();
1669
1670	}
1671
1672	public void updateKeyInAccount(final Account account, final String alias) {
1673		Log.d(Config.LOGTAG, "update key in account " + alias);
1674		try {
1675			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1676			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1677			if (account.getJid().toBareJid().equals(info.first)) {
1678				account.setPrivateKeyAlias(alias);
1679				account.setDisplayName(info.second);
1680				databaseBackend.updateAccount(account);
1681				if (Config.X509_VERIFICATION) {
1682					try {
1683						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1684					} catch (CertificateException e) {
1685						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1686					}
1687					account.getAxolotlService().regenerateKeys(true);
1688				}
1689			} else {
1690				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1691			}
1692		} catch (Exception e) {
1693			e.printStackTrace();
1694		}
1695	}
1696
1697	public boolean updateAccount(final Account account) {
1698		if (databaseBackend.updateAccount(account)) {
1699			account.setShowErrorNotification(true);
1700			this.statusListener.onStatusChanged(account);
1701			databaseBackend.updateAccount(account);
1702			reconnectAccountInBackground(account);
1703			updateAccountUi();
1704			getNotificationService().updateErrorNotification();
1705			return true;
1706		} else {
1707			return false;
1708		}
1709	}
1710
1711	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1712		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1713		sendIqPacket(account, iq, new OnIqPacketReceived() {
1714			@Override
1715			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1716				if (packet.getType() == IqPacket.TYPE.RESULT) {
1717					account.setPassword(newPassword);
1718					account.setOption(Account.OPTION_MAGIC_CREATE, false);
1719					databaseBackend.updateAccount(account);
1720					callback.onPasswordChangeSucceeded();
1721				} else {
1722					callback.onPasswordChangeFailed();
1723				}
1724			}
1725		});
1726	}
1727
1728	public void deleteAccount(final Account account) {
1729		synchronized (this.conversations) {
1730			for (final Conversation conversation : conversations) {
1731				if (conversation.getAccount() == account) {
1732					if (conversation.getMode() == Conversation.MODE_MULTI) {
1733						leaveMuc(conversation);
1734					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1735						conversation.endOtrIfNeeded();
1736					}
1737					conversations.remove(conversation);
1738				}
1739			}
1740			if (account.getXmppConnection() != null) {
1741				new Thread(new Runnable() {
1742					@Override
1743					public void run() {
1744						disconnect(account, true);
1745					}
1746				}).start();
1747			}
1748			Runnable runnable = new Runnable() {
1749				@Override
1750				public void run() {
1751					if (!databaseBackend.deleteAccount(account)) {
1752						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": unable to delete account");
1753					}
1754				}
1755			};
1756			mDatabaseExecutor.execute(runnable);
1757			this.accounts.remove(account);
1758			updateAccountUi();
1759			getNotificationService().updateErrorNotification();
1760		}
1761	}
1762
1763	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1764		synchronized (this) {
1765			this.mLastActivity = System.currentTimeMillis();
1766			if (checkListeners()) {
1767				switchToForeground();
1768			}
1769			this.mOnConversationUpdate = listener;
1770			this.mNotificationService.setIsInForeground(true);
1771			if (this.convChangedListenerCount < 2) {
1772				this.convChangedListenerCount++;
1773			}
1774		}
1775	}
1776
1777	public void removeOnConversationListChangedListener() {
1778		synchronized (this) {
1779			this.convChangedListenerCount--;
1780			if (this.convChangedListenerCount <= 0) {
1781				this.convChangedListenerCount = 0;
1782				this.mOnConversationUpdate = null;
1783				this.mNotificationService.setIsInForeground(false);
1784				if (checkListeners()) {
1785					switchToBackground();
1786				}
1787			}
1788		}
1789	}
1790
1791	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1792		synchronized (this) {
1793			if (checkListeners()) {
1794				switchToForeground();
1795			}
1796			this.mOnShowErrorToast = onShowErrorToast;
1797			if (this.showErrorToastListenerCount < 2) {
1798				this.showErrorToastListenerCount++;
1799			}
1800		}
1801		this.mOnShowErrorToast = onShowErrorToast;
1802	}
1803
1804	public void removeOnShowErrorToastListener() {
1805		synchronized (this) {
1806			this.showErrorToastListenerCount--;
1807			if (this.showErrorToastListenerCount <= 0) {
1808				this.showErrorToastListenerCount = 0;
1809				this.mOnShowErrorToast = null;
1810				if (checkListeners()) {
1811					switchToBackground();
1812				}
1813			}
1814		}
1815	}
1816
1817	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1818		synchronized (this) {
1819			if (checkListeners()) {
1820				switchToForeground();
1821			}
1822			this.mOnAccountUpdate = listener;
1823			if (this.accountChangedListenerCount < 2) {
1824				this.accountChangedListenerCount++;
1825			}
1826		}
1827	}
1828
1829	public void removeOnAccountListChangedListener() {
1830		synchronized (this) {
1831			this.accountChangedListenerCount--;
1832			if (this.accountChangedListenerCount <= 0) {
1833				this.mOnAccountUpdate = null;
1834				this.accountChangedListenerCount = 0;
1835				if (checkListeners()) {
1836					switchToBackground();
1837				}
1838			}
1839		}
1840	}
1841
1842	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1843		synchronized (this) {
1844			if (checkListeners()) {
1845				switchToForeground();
1846			}
1847			this.mOnCaptchaRequested = listener;
1848			if (this.captchaRequestedListenerCount < 2) {
1849				this.captchaRequestedListenerCount++;
1850			}
1851		}
1852	}
1853
1854	public void removeOnCaptchaRequestedListener() {
1855		synchronized (this) {
1856			this.captchaRequestedListenerCount--;
1857			if (this.captchaRequestedListenerCount <= 0) {
1858				this.mOnCaptchaRequested = null;
1859				this.captchaRequestedListenerCount = 0;
1860				if (checkListeners()) {
1861					switchToBackground();
1862				}
1863			}
1864		}
1865	}
1866
1867	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1868		synchronized (this) {
1869			if (checkListeners()) {
1870				switchToForeground();
1871			}
1872			this.mOnRosterUpdate = listener;
1873			if (this.rosterChangedListenerCount < 2) {
1874				this.rosterChangedListenerCount++;
1875			}
1876		}
1877	}
1878
1879	public void removeOnRosterUpdateListener() {
1880		synchronized (this) {
1881			this.rosterChangedListenerCount--;
1882			if (this.rosterChangedListenerCount <= 0) {
1883				this.rosterChangedListenerCount = 0;
1884				this.mOnRosterUpdate = null;
1885				if (checkListeners()) {
1886					switchToBackground();
1887				}
1888			}
1889		}
1890	}
1891
1892	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1893		synchronized (this) {
1894			if (checkListeners()) {
1895				switchToForeground();
1896			}
1897			this.mOnUpdateBlocklist = listener;
1898			if (this.updateBlocklistListenerCount < 2) {
1899				this.updateBlocklistListenerCount++;
1900			}
1901		}
1902	}
1903
1904	public void removeOnUpdateBlocklistListener() {
1905		synchronized (this) {
1906			this.updateBlocklistListenerCount--;
1907			if (this.updateBlocklistListenerCount <= 0) {
1908				this.updateBlocklistListenerCount = 0;
1909				this.mOnUpdateBlocklist = null;
1910				if (checkListeners()) {
1911					switchToBackground();
1912				}
1913			}
1914		}
1915	}
1916
1917	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1918		synchronized (this) {
1919			if (checkListeners()) {
1920				switchToForeground();
1921			}
1922			this.mOnKeyStatusUpdated = listener;
1923			if (this.keyStatusUpdatedListenerCount < 2) {
1924				this.keyStatusUpdatedListenerCount++;
1925			}
1926		}
1927	}
1928
1929	public void removeOnNewKeysAvailableListener() {
1930		synchronized (this) {
1931			this.keyStatusUpdatedListenerCount--;
1932			if (this.keyStatusUpdatedListenerCount <= 0) {
1933				this.keyStatusUpdatedListenerCount = 0;
1934				this.mOnKeyStatusUpdated = null;
1935				if (checkListeners()) {
1936					switchToBackground();
1937				}
1938			}
1939		}
1940	}
1941
1942	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1943		synchronized (this) {
1944			if (checkListeners()) {
1945				switchToForeground();
1946			}
1947			this.mOnMucRosterUpdate = listener;
1948			if (this.mucRosterChangedListenerCount < 2) {
1949				this.mucRosterChangedListenerCount++;
1950			}
1951		}
1952	}
1953
1954	public void removeOnMucRosterUpdateListener() {
1955		synchronized (this) {
1956			this.mucRosterChangedListenerCount--;
1957			if (this.mucRosterChangedListenerCount <= 0) {
1958				this.mucRosterChangedListenerCount = 0;
1959				this.mOnMucRosterUpdate = null;
1960				if (checkListeners()) {
1961					switchToBackground();
1962				}
1963			}
1964		}
1965	}
1966
1967	public boolean checkListeners() {
1968		return (this.mOnAccountUpdate == null
1969				&& this.mOnConversationUpdate == null
1970				&& this.mOnRosterUpdate == null
1971				&& this.mOnCaptchaRequested == null
1972				&& this.mOnUpdateBlocklist == null
1973				&& this.mOnShowErrorToast == null
1974				&& this.mOnKeyStatusUpdated == null);
1975	}
1976
1977	private void switchToForeground() {
1978		final boolean broadcastLastActivity = broadcastLastActivity();
1979		for (Conversation conversation : getConversations()) {
1980			conversation.setIncomingChatState(ChatState.ACTIVE);
1981		}
1982		for (Account account : getAccounts()) {
1983			if (account.getStatus() == Account.State.ONLINE) {
1984				account.deactivateGracePeriod();
1985				final XmppConnection connection = account.getXmppConnection();
1986				if (connection != null ) {
1987					if (connection.getFeatures().csi()) {
1988						connection.sendActive();
1989					}
1990					if (broadcastLastActivity) {
1991						sendPresence(account, false); //send new presence but don't include idle because we are not
1992					}
1993				}
1994			}
1995		}
1996		Log.d(Config.LOGTAG, "app switched into foreground");
1997	}
1998
1999	private void switchToBackground() {
2000		final boolean broadcastLastActivity = broadcastLastActivity();
2001		for (Account account : getAccounts()) {
2002			if (account.getStatus() == Account.State.ONLINE) {
2003				XmppConnection connection = account.getXmppConnection();
2004				if (connection != null) {
2005					if (broadcastLastActivity) {
2006						sendPresence(account, broadcastLastActivity);
2007					}
2008					if (connection.getFeatures().csi()) {
2009						connection.sendInactive();
2010					}
2011				}
2012			}
2013		}
2014		this.mNotificationService.setIsInForeground(false);
2015		Log.d(Config.LOGTAG, "app switched into background");
2016	}
2017
2018	private void connectMultiModeConversations(Account account) {
2019		List<Conversation> conversations = getConversations();
2020		for (Conversation conversation : conversations) {
2021			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2022				joinMuc(conversation);
2023			}
2024		}
2025	}
2026
2027	public void joinMuc(Conversation conversation) {
2028		joinMuc(conversation, null);
2029	}
2030
2031	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2032		Account account = conversation.getAccount();
2033		account.pendingConferenceJoins.remove(conversation);
2034		account.pendingConferenceLeaves.remove(conversation);
2035		if (account.getStatus() == Account.State.ONLINE) {
2036			conversation.resetMucOptions();
2037			if (onConferenceJoined != null) {
2038				conversation.getMucOptions().flagNoAutoPushConfiguration();
2039			}
2040			conversation.setHasMessagesLeftOnServer(false);
2041			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2042
2043				private void join(Conversation conversation) {
2044					Account account = conversation.getAccount();
2045					final MucOptions mucOptions = conversation.getMucOptions();
2046					final Jid joinJid = mucOptions.getSelf().getFullJid();
2047					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
2048					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
2049					packet.setTo(joinJid);
2050					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2051					if (conversation.getMucOptions().getPassword() != null) {
2052						x.addChild("password").setContent(mucOptions.getPassword());
2053					}
2054
2055					if (mucOptions.mamSupport()) {
2056						// Use MAM instead of the limited muc history to get history
2057						x.addChild("history").setAttribute("maxchars", "0");
2058					} else {
2059						// Fallback to muc history
2060						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
2061					}
2062					sendPresencePacket(account, packet);
2063					if (onConferenceJoined != null) {
2064						onConferenceJoined.onConferenceJoined(conversation);
2065					}
2066					if (!joinJid.equals(conversation.getJid())) {
2067						conversation.setContactJid(joinJid);
2068						databaseBackend.updateConversation(conversation);
2069					}
2070
2071					if (mucOptions.mamSupport()) {
2072						getMessageArchiveService().catchupMUC(conversation);
2073					}
2074					if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
2075						fetchConferenceMembers(conversation);
2076					}
2077					sendUnsentMessages(conversation);
2078				}
2079
2080				@Override
2081				public void onConferenceConfigurationFetched(Conversation conversation) {
2082					join(conversation);
2083				}
2084
2085				@Override
2086				public void onFetchFailed(final Conversation conversation, Element error) {
2087					if (error != null && "remote-server-not-found".equals(error.getName())) {
2088						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2089					} else {
2090						join(conversation);
2091						fetchConferenceConfiguration(conversation);
2092					}
2093				}
2094			});
2095			updateConversationUi();
2096		} else {
2097			account.pendingConferenceJoins.add(conversation);
2098			conversation.resetMucOptions();
2099			conversation.setHasMessagesLeftOnServer(false);
2100			updateConversationUi();
2101		}
2102	}
2103
2104	private void fetchConferenceMembers(final Conversation conversation) {
2105		final Account account = conversation.getAccount();
2106		final String[] affiliations = {"member","admin","owner"};
2107		OnIqPacketReceived callback = new OnIqPacketReceived() {
2108
2109			private int i = 0;
2110
2111			@Override
2112			public void onIqPacketReceived(Account account, IqPacket packet) {
2113
2114				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2115				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2116					for(Element child : query.getChildren()) {
2117						if ("item".equals(child.getName())) {
2118							MucOptions.User user = AbstractParser.parseItem(conversation,child);
2119							if (!user.realJidMatchesAccount()) {
2120								conversation.getMucOptions().addUser(user);
2121								getAvatarService().clear(conversation);
2122								updateMucRosterUi();
2123								updateConversationUi();
2124							}
2125						}
2126					}
2127				} else {
2128					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
2129				}
2130				++i;
2131				if (i >= affiliations.length) {
2132					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
2133				}
2134			}
2135		};
2136		for(String affiliation : affiliations) {
2137			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2138		}
2139		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
2140	}
2141
2142	public void providePasswordForMuc(Conversation conversation, String password) {
2143		if (conversation.getMode() == Conversation.MODE_MULTI) {
2144			conversation.getMucOptions().setPassword(password);
2145			if (conversation.getBookmark() != null) {
2146				if (respectAutojoin()) {
2147					conversation.getBookmark().setAutojoin(true);
2148				}
2149				pushBookmarks(conversation.getAccount());
2150			}
2151			updateConversation(conversation);
2152			joinMuc(conversation);
2153		}
2154	}
2155
2156	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2157		final MucOptions options = conversation.getMucOptions();
2158		final Jid joinJid = options.createJoinJid(nick);
2159		if (options.online()) {
2160			Account account = conversation.getAccount();
2161			options.setOnRenameListener(new OnRenameListener() {
2162
2163				@Override
2164				public void onSuccess() {
2165					conversation.setContactJid(joinJid);
2166					databaseBackend.updateConversation(conversation);
2167					Bookmark bookmark = conversation.getBookmark();
2168					if (bookmark != null) {
2169						bookmark.setNick(nick);
2170						pushBookmarks(bookmark.getAccount());
2171					}
2172					callback.success(conversation);
2173				}
2174
2175				@Override
2176				public void onFailure() {
2177					callback.error(R.string.nick_in_use, conversation);
2178				}
2179			});
2180
2181			PresencePacket packet = new PresencePacket();
2182			packet.setTo(joinJid);
2183			packet.setFrom(conversation.getAccount().getJid());
2184
2185			String sig = account.getPgpSignature();
2186			if (sig != null) {
2187				packet.addChild("status").setContent("online");
2188				packet.addChild("x", "jabber:x:signed").setContent(sig);
2189			}
2190			sendPresencePacket(account, packet);
2191		} else {
2192			conversation.setContactJid(joinJid);
2193			databaseBackend.updateConversation(conversation);
2194			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2195				Bookmark bookmark = conversation.getBookmark();
2196				if (bookmark != null) {
2197					bookmark.setNick(nick);
2198					pushBookmarks(bookmark.getAccount());
2199				}
2200				joinMuc(conversation);
2201			}
2202		}
2203	}
2204
2205	public void leaveMuc(Conversation conversation) {
2206		leaveMuc(conversation, false);
2207	}
2208
2209	private void leaveMuc(Conversation conversation, boolean now) {
2210		Account account = conversation.getAccount();
2211		account.pendingConferenceJoins.remove(conversation);
2212		account.pendingConferenceLeaves.remove(conversation);
2213		if (account.getStatus() == Account.State.ONLINE || now) {
2214			PresencePacket packet = new PresencePacket();
2215			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2216			packet.setFrom(conversation.getAccount().getJid());
2217			packet.setAttribute("type", "unavailable");
2218			sendPresencePacket(conversation.getAccount(), packet);
2219			conversation.getMucOptions().setOffline();
2220			conversation.deregisterWithBookmark();
2221			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2222					+ ": leaving muc " + conversation.getJid());
2223		} else {
2224			account.pendingConferenceLeaves.add(conversation);
2225		}
2226	}
2227
2228	private String findConferenceServer(final Account account) {
2229		String server;
2230		if (account.getXmppConnection() != null) {
2231			server = account.getXmppConnection().getMucServer();
2232			if (server != null) {
2233				return server;
2234			}
2235		}
2236		for (Account other : getAccounts()) {
2237			if (other != account && other.getXmppConnection() != null) {
2238				server = other.getXmppConnection().getMucServer();
2239				if (server != null) {
2240					return server;
2241				}
2242			}
2243		}
2244		return null;
2245	}
2246
2247	public void createAdhocConference(final Account account,
2248									  final String subject,
2249									  final Iterable<Jid> jids,
2250									  final UiCallback<Conversation> callback) {
2251		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2252		if (account.getStatus() == Account.State.ONLINE) {
2253			try {
2254				String server = findConferenceServer(account);
2255				if (server == null) {
2256					if (callback != null) {
2257						callback.error(R.string.no_conference_server_found, null);
2258					}
2259					return;
2260				}
2261				final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2262				final Conversation conversation = findOrCreateConversation(account, jid, true);
2263				joinMuc(conversation, new OnConferenceJoined() {
2264					@Override
2265					public void onConferenceJoined(final Conversation conversation) {
2266						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConferenceOptionsPushed() {
2267							@Override
2268							public void onPushSucceeded() {
2269								if (subject != null && !subject.trim().isEmpty()) {
2270									pushSubjectToConference(conversation, subject.trim());
2271								}
2272								for (Jid invite : jids) {
2273									invite(conversation, invite);
2274								}
2275								if (account.countPresences() > 1) {
2276									directInvite(conversation, account.getJid().toBareJid());
2277								}
2278								saveConversationAsBookmark(conversation, subject);
2279								if (callback != null) {
2280									callback.success(conversation);
2281								}
2282							}
2283
2284							@Override
2285							public void onPushFailed() {
2286								archiveConversation(conversation);
2287								if (callback != null) {
2288									callback.error(R.string.conference_creation_failed, conversation);
2289								}
2290							}
2291						});
2292					}
2293				});
2294			} catch (InvalidJidException e) {
2295				if (callback != null) {
2296					callback.error(R.string.conference_creation_failed, null);
2297				}
2298			}
2299		} else {
2300			if (callback != null) {
2301				callback.error(R.string.not_connected_try_again, null);
2302			}
2303		}
2304	}
2305
2306	public void fetchConferenceConfiguration(final Conversation conversation) {
2307		fetchConferenceConfiguration(conversation, null);
2308	}
2309
2310	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2311		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2312		request.setTo(conversation.getJid().toBareJid());
2313		request.query("http://jabber.org/protocol/disco#info");
2314		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2315			@Override
2316			public void onIqPacketReceived(Account account, IqPacket packet) {
2317				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2318				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2319					ArrayList<String> features = new ArrayList<>();
2320					for (Element child : query.getChildren()) {
2321						if (child != null && child.getName().equals("feature")) {
2322							String var = child.getAttribute("var");
2323							if (var != null) {
2324								features.add(var);
2325							}
2326						}
2327					}
2328					Element form = query.findChild("x", "jabber:x:data");
2329					if (form != null) {
2330						conversation.getMucOptions().updateFormData(Data.parse(form));
2331					}
2332					conversation.getMucOptions().updateFeatures(features);
2333					if (callback != null) {
2334						callback.onConferenceConfigurationFetched(conversation);
2335					}
2336					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2337					updateConversationUi();
2338				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2339					if (callback != null) {
2340						callback.onFetchFailed(conversation, packet.getError());
2341					}
2342				}
2343			}
2344		});
2345	}
2346
2347	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2348		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2349		request.setTo(conversation.getJid().toBareJid());
2350		request.query("http://jabber.org/protocol/muc#owner");
2351		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2352			@Override
2353			public void onIqPacketReceived(Account account, IqPacket packet) {
2354				if (packet.getType() == IqPacket.TYPE.RESULT) {
2355					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2356					for (Field field : data.getFields()) {
2357						if (options.containsKey(field.getFieldName())) {
2358							field.setValue(options.getString(field.getFieldName()));
2359						}
2360					}
2361					data.submit();
2362					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2363					set.setTo(conversation.getJid().toBareJid());
2364					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2365					sendIqPacket(account, set, new OnIqPacketReceived() {
2366						@Override
2367						public void onIqPacketReceived(Account account, IqPacket packet) {
2368							if (callback != null) {
2369								if (packet.getType() == IqPacket.TYPE.RESULT) {
2370									callback.onPushSucceeded();
2371								} else {
2372									callback.onPushFailed();
2373								}
2374							}
2375						}
2376					});
2377				} else {
2378					if (callback != null) {
2379						callback.onPushFailed();
2380					}
2381				}
2382			}
2383		});
2384	}
2385
2386	public void pushSubjectToConference(final Conversation conference, final String subject) {
2387		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2388		this.sendMessagePacket(conference.getAccount(), packet);
2389		final MucOptions mucOptions = conference.getMucOptions();
2390		final MucOptions.User self = mucOptions.getSelf();
2391		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2392			Bundle options = new Bundle();
2393			options.putString("muc#roomconfig_persistentroom", "1");
2394			this.pushConferenceConfiguration(conference, options, null);
2395		}
2396	}
2397
2398	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2399		final Jid jid = user.toBareJid();
2400		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2401		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2402			@Override
2403			public void onIqPacketReceived(Account account, IqPacket packet) {
2404				if (packet.getType() == IqPacket.TYPE.RESULT) {
2405					conference.getMucOptions().changeAffiliation(jid, affiliation);
2406					getAvatarService().clear(conference);
2407					callback.onAffiliationChangedSuccessful(jid);
2408				} else {
2409					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2410				}
2411			}
2412		});
2413	}
2414
2415	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2416		List<Jid> jids = new ArrayList<>();
2417		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2418			if (user.getAffiliation() == before && user.getRealJid() != null) {
2419				jids.add(user.getRealJid());
2420			}
2421		}
2422		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2423		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2424	}
2425
2426	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2427		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2428		Log.d(Config.LOGTAG, request.toString());
2429		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2430			@Override
2431			public void onIqPacketReceived(Account account, IqPacket packet) {
2432				Log.d(Config.LOGTAG, packet.toString());
2433				if (packet.getType() == IqPacket.TYPE.RESULT) {
2434					callback.onRoleChangedSuccessful(nick);
2435				} else {
2436					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2437				}
2438			}
2439		});
2440	}
2441
2442	private void disconnect(Account account, boolean force) {
2443		if ((account.getStatus() == Account.State.ONLINE)
2444				|| (account.getStatus() == Account.State.DISABLED)) {
2445			final XmppConnection connection = account.getXmppConnection();
2446			if (!force) {
2447				List<Conversation> conversations = getConversations();
2448				for (Conversation conversation : conversations) {
2449					if (conversation.getAccount() == account) {
2450						if (conversation.getMode() == Conversation.MODE_MULTI) {
2451							leaveMuc(conversation, true);
2452						} else {
2453							if (conversation.endOtrIfNeeded()) {
2454								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2455										+ ": ended otr session with "
2456										+ conversation.getJid());
2457							}
2458						}
2459					}
2460				}
2461				sendOfflinePresence(account);
2462			}
2463			connection.disconnect(force);
2464		}
2465	}
2466
2467	@Override
2468	public IBinder onBind(Intent intent) {
2469		return mBinder;
2470	}
2471
2472	public void updateMessage(Message message) {
2473		databaseBackend.updateMessage(message);
2474		updateConversationUi();
2475	}
2476
2477	public void updateMessage(Message message, String uuid) {
2478		databaseBackend.updateMessage(message, uuid);
2479		updateConversationUi();
2480	}
2481
2482	protected void syncDirtyContacts(Account account) {
2483		for (Contact contact : account.getRoster().getContacts()) {
2484			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2485				pushContactToServer(contact);
2486			}
2487			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2488				deleteContactOnServer(contact);
2489			}
2490		}
2491	}
2492
2493	public void createContact(Contact contact) {
2494		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2495		if (autoGrant) {
2496			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2497			contact.setOption(Contact.Options.ASKING);
2498		}
2499		pushContactToServer(contact);
2500	}
2501
2502	public void onOtrSessionEstablished(Conversation conversation) {
2503		final Account account = conversation.getAccount();
2504		final Session otrSession = conversation.getOtrSession();
2505		Log.d(Config.LOGTAG,
2506				account.getJid().toBareJid() + " otr session established with "
2507						+ conversation.getJid() + "/"
2508						+ otrSession.getSessionID().getUserID());
2509		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2510
2511			@Override
2512			public void onMessageFound(Message message) {
2513				SessionID id = otrSession.getSessionID();
2514				try {
2515					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2516				} catch (InvalidJidException e) {
2517					return;
2518				}
2519				if (message.needsUploading()) {
2520					mJingleConnectionManager.createNewConnection(message);
2521				} else {
2522					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2523					if (outPacket != null) {
2524						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2525						message.setStatus(Message.STATUS_SEND);
2526						databaseBackend.updateMessage(message);
2527						sendMessagePacket(account, outPacket);
2528					}
2529				}
2530				updateConversationUi();
2531			}
2532		});
2533	}
2534
2535	public boolean renewSymmetricKey(Conversation conversation) {
2536		Account account = conversation.getAccount();
2537		byte[] symmetricKey = new byte[32];
2538		this.mRandom.nextBytes(symmetricKey);
2539		Session otrSession = conversation.getOtrSession();
2540		if (otrSession != null) {
2541			MessagePacket packet = new MessagePacket();
2542			packet.setType(MessagePacket.TYPE_CHAT);
2543			packet.setFrom(account.getJid());
2544			MessageGenerator.addMessageHints(packet);
2545			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2546					+ otrSession.getSessionID().getUserID());
2547			try {
2548				packet.setBody(otrSession
2549						.transformSending(CryptoHelper.FILETRANSFER
2550								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2551				sendMessagePacket(account, packet);
2552				conversation.setSymmetricKey(symmetricKey);
2553				return true;
2554			} catch (OtrException e) {
2555				return false;
2556			}
2557		}
2558		return false;
2559	}
2560
2561	public void pushContactToServer(final Contact contact) {
2562		contact.resetOption(Contact.Options.DIRTY_DELETE);
2563		contact.setOption(Contact.Options.DIRTY_PUSH);
2564		final Account account = contact.getAccount();
2565		if (account.getStatus() == Account.State.ONLINE) {
2566			final boolean ask = contact.getOption(Contact.Options.ASKING);
2567			final boolean sendUpdates = contact
2568					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2569					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2570			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2571			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2572			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2573			if (sendUpdates) {
2574				sendPresencePacket(account,
2575						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2576			}
2577			if (ask) {
2578				sendPresencePacket(account,
2579						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2580			}
2581		}
2582	}
2583
2584	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2585		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2586		final int size = Config.AVATAR_SIZE;
2587		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2588		if (avatar != null) {
2589			avatar.height = size;
2590			avatar.width = size;
2591			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2592				avatar.type = "image/webp";
2593			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2594				avatar.type = "image/jpeg";
2595			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2596				avatar.type = "image/png";
2597			}
2598			if (!getFileBackend().save(avatar)) {
2599				callback.error(R.string.error_saving_avatar, avatar);
2600				return;
2601			}
2602			publishAvatar(account, avatar, callback);
2603		} else {
2604			callback.error(R.string.error_publish_avatar_converting, null);
2605		}
2606	}
2607
2608	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2609		final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2610		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2611
2612			@Override
2613			public void onIqPacketReceived(Account account, IqPacket result) {
2614				if (result.getType() == IqPacket.TYPE.RESULT) {
2615					final IqPacket packet = XmppConnectionService.this.mIqGenerator
2616							.publishAvatarMetadata(avatar);
2617					sendIqPacket(account, packet, new OnIqPacketReceived() {
2618						@Override
2619						public void onIqPacketReceived(Account account, IqPacket result) {
2620							if (result.getType() == IqPacket.TYPE.RESULT) {
2621								if (account.setAvatar(avatar.getFilename())) {
2622									getAvatarService().clear(account);
2623									databaseBackend.updateAccount(account);
2624								}
2625								if (callback != null) {
2626									callback.success(avatar);
2627								} else {
2628									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
2629								}
2630							} else {
2631								if (callback != null) {
2632									callback.error(
2633											R.string.error_publish_avatar_server_reject,
2634											avatar);
2635								}
2636							}
2637						}
2638					});
2639				} else {
2640					if (callback != null) {
2641						callback.error(
2642								R.string.error_publish_avatar_server_reject,
2643								avatar);
2644					}
2645				}
2646			}
2647		});
2648	}
2649
2650	public void republishAvatarIfNeeded(Account account) {
2651		if (account.getAxolotlService().isPepBroken()) {
2652			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2653			return;
2654		}
2655		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2656		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2657
2658			private Avatar parseAvatar(IqPacket packet) {
2659				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2660				if (pubsub != null) {
2661					Element items = pubsub.findChild("items");
2662					if (items != null) {
2663						return Avatar.parseMetadata(items);
2664					}
2665				}
2666				return null;
2667			}
2668
2669			private boolean errorIsItemNotFound(IqPacket packet) {
2670				Element error = packet.findChild("error");
2671				return packet.getType() == IqPacket.TYPE.ERROR
2672						&& error != null
2673						&& error.hasChild("item-not-found");
2674			}
2675
2676			@Override
2677			public void onIqPacketReceived(Account account, IqPacket packet) {
2678				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2679					Avatar serverAvatar = parseAvatar(packet);
2680					if (serverAvatar == null && account.getAvatar() != null) {
2681						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2682						if (avatar != null) {
2683							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2684							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2685						} else {
2686							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2687						}
2688					}
2689				}
2690			}
2691		});
2692	}
2693
2694	public void fetchAvatar(Account account, Avatar avatar) {
2695		fetchAvatar(account, avatar, null);
2696	}
2697
2698	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2699		final String KEY = generateFetchKey(account, avatar);
2700		synchronized (this.mInProgressAvatarFetches) {
2701			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2702				switch (avatar.origin) {
2703					case PEP:
2704						this.mInProgressAvatarFetches.add(KEY);
2705						fetchAvatarPep(account, avatar, callback);
2706						break;
2707					case VCARD:
2708						this.mInProgressAvatarFetches.add(KEY);
2709						fetchAvatarVcard(account, avatar, callback);
2710						break;
2711				}
2712			}
2713		}
2714	}
2715
2716	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2717		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2718		sendIqPacket(account, packet, new OnIqPacketReceived() {
2719
2720			@Override
2721			public void onIqPacketReceived(Account account, IqPacket result) {
2722				synchronized (mInProgressAvatarFetches) {
2723					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2724				}
2725				final String ERROR = account.getJid().toBareJid()
2726						+ ": fetching avatar for " + avatar.owner + " failed ";
2727				if (result.getType() == IqPacket.TYPE.RESULT) {
2728					avatar.image = mIqParser.avatarData(result);
2729					if (avatar.image != null) {
2730						if (getFileBackend().save(avatar)) {
2731							if (account.getJid().toBareJid().equals(avatar.owner)) {
2732								if (account.setAvatar(avatar.getFilename())) {
2733									databaseBackend.updateAccount(account);
2734								}
2735								getAvatarService().clear(account);
2736								updateConversationUi();
2737								updateAccountUi();
2738							} else {
2739								Contact contact = account.getRoster()
2740										.getContact(avatar.owner);
2741								contact.setAvatar(avatar);
2742								getAvatarService().clear(contact);
2743								updateConversationUi();
2744								updateRosterUi();
2745							}
2746							if (callback != null) {
2747								callback.success(avatar);
2748							}
2749							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2750									+ ": successfully fetched pep avatar for " + avatar.owner);
2751							return;
2752						}
2753					} else {
2754
2755						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2756					}
2757				} else {
2758					Element error = result.findChild("error");
2759					if (error == null) {
2760						Log.d(Config.LOGTAG, ERROR + "(server error)");
2761					} else {
2762						Log.d(Config.LOGTAG, ERROR + error.toString());
2763					}
2764				}
2765				if (callback != null) {
2766					callback.error(0, null);
2767				}
2768
2769			}
2770		});
2771	}
2772
2773	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2774		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2775		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2776			@Override
2777			public void onIqPacketReceived(Account account, IqPacket packet) {
2778				synchronized (mInProgressAvatarFetches) {
2779					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2780				}
2781				if (packet.getType() == IqPacket.TYPE.RESULT) {
2782					Element vCard = packet.findChild("vCard", "vcard-temp");
2783					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2784					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2785					if (image != null) {
2786						avatar.image = image;
2787						if (getFileBackend().save(avatar)) {
2788							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2789									+ ": successfully fetched vCard avatar for " + avatar.owner);
2790							if (avatar.owner.isBareJid()) {
2791								if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2792									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": had no avatar. replacing with vcard");
2793									account.setAvatar(avatar.getFilename());
2794									databaseBackend.updateAccount(account);
2795									getAvatarService().clear(account);
2796									updateAccountUi();
2797								} else {
2798									Contact contact = account.getRoster().getContact(avatar.owner);
2799									contact.setAvatar(avatar);
2800									getAvatarService().clear(contact);
2801									updateRosterUi();
2802								}
2803								updateConversationUi();
2804							} else {
2805								Conversation conversation = find(account, avatar.owner.toBareJid());
2806								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2807									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2808									if (user != null) {
2809										if (user.setAvatar(avatar)) {
2810											getAvatarService().clear(user);
2811											updateConversationUi();
2812											updateMucRosterUi();
2813										}
2814									}
2815								}
2816							}
2817						}
2818					}
2819				}
2820			}
2821		});
2822	}
2823
2824	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2825		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2826		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2827
2828			@Override
2829			public void onIqPacketReceived(Account account, IqPacket packet) {
2830				if (packet.getType() == IqPacket.TYPE.RESULT) {
2831					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2832					if (pubsub != null) {
2833						Element items = pubsub.findChild("items");
2834						if (items != null) {
2835							Avatar avatar = Avatar.parseMetadata(items);
2836							if (avatar != null) {
2837								avatar.owner = account.getJid().toBareJid();
2838								if (fileBackend.isAvatarCached(avatar)) {
2839									if (account.setAvatar(avatar.getFilename())) {
2840										databaseBackend.updateAccount(account);
2841									}
2842									getAvatarService().clear(account);
2843									callback.success(avatar);
2844								} else {
2845									fetchAvatarPep(account, avatar, callback);
2846								}
2847								return;
2848							}
2849						}
2850					}
2851				}
2852				callback.error(0, null);
2853			}
2854		});
2855	}
2856
2857	public void deleteContactOnServer(Contact contact) {
2858		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2859		contact.resetOption(Contact.Options.DIRTY_PUSH);
2860		contact.setOption(Contact.Options.DIRTY_DELETE);
2861		Account account = contact.getAccount();
2862		if (account.getStatus() == Account.State.ONLINE) {
2863			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2864			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2865			item.setAttribute("jid", contact.getJid().toString());
2866			item.setAttribute("subscription", "remove");
2867			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2868		}
2869	}
2870
2871	public void updateConversation(final Conversation conversation) {
2872		mDatabaseExecutor.execute(new Runnable() {
2873			@Override
2874			public void run() {
2875				databaseBackend.updateConversation(conversation);
2876			}
2877		});
2878	}
2879
2880	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2881		synchronized (account) {
2882			XmppConnection connection = account.getXmppConnection();
2883			if (connection == null) {
2884				connection = createConnection(account);
2885				account.setXmppConnection(connection);
2886			} else {
2887				connection.interrupt();
2888			}
2889			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2890				if (!force) {
2891					disconnect(account, false);
2892				}
2893				Thread thread = new Thread(connection);
2894				connection.setInteractive(interactive);
2895				connection.prepareNewConnection();
2896				thread.start();
2897				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2898			} else {
2899				disconnect(account, force);
2900				account.getRoster().clearPresences();
2901				connection.resetEverything();
2902				account.getAxolotlService().resetBrokenness();
2903			}
2904		}
2905	}
2906
2907	public void reconnectAccountInBackground(final Account account) {
2908		new Thread(new Runnable() {
2909			@Override
2910			public void run() {
2911				reconnectAccount(account, false, true);
2912			}
2913		}).start();
2914	}
2915
2916	public void invite(Conversation conversation, Jid contact) {
2917		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2918		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2919		sendMessagePacket(conversation.getAccount(), packet);
2920	}
2921
2922	public void directInvite(Conversation conversation, Jid jid) {
2923		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2924		sendMessagePacket(conversation.getAccount(), packet);
2925	}
2926
2927	public void resetSendingToWaiting(Account account) {
2928		for (Conversation conversation : getConversations()) {
2929			if (conversation.getAccount() == account) {
2930				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2931
2932					@Override
2933					public void onMessageFound(Message message) {
2934						markMessage(message, Message.STATUS_WAITING);
2935					}
2936				});
2937			}
2938		}
2939	}
2940
2941	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2942		return markMessage(account, recipient, uuid, status, null);
2943	}
2944
2945	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
2946		if (uuid == null) {
2947			return null;
2948		}
2949		for (Conversation conversation : getConversations()) {
2950			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2951				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2952				if (message != null) {
2953					markMessage(message, status, errorMessage);
2954				}
2955				return message;
2956			}
2957		}
2958		return null;
2959	}
2960
2961	public boolean markMessage(Conversation conversation, String uuid, int status) {
2962		if (uuid == null) {
2963			return false;
2964		} else {
2965			Message message = conversation.findSentMessageWithUuid(uuid);
2966			if (message != null) {
2967				markMessage(message, status);
2968				return true;
2969			} else {
2970				return false;
2971			}
2972		}
2973	}
2974
2975	public void markMessage(Message message, int status) {
2976		markMessage(message, status, null);
2977	}
2978
2979
2980	public void markMessage(Message message, int status, String errorMessage) {
2981		if (status == Message.STATUS_SEND_FAILED
2982				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2983				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2984			return;
2985		}
2986		message.setErrorMessage(errorMessage);
2987		message.setStatus(status);
2988		databaseBackend.updateMessage(message);
2989		updateConversationUi();
2990	}
2991
2992	public SharedPreferences getPreferences() {
2993		return PreferenceManager
2994				.getDefaultSharedPreferences(getApplicationContext());
2995	}
2996
2997	public boolean confirmMessages() {
2998		return getPreferences().getBoolean("confirm_messages", true);
2999	}
3000
3001	public boolean allowMessageCorrection() {
3002		return getPreferences().getBoolean("allow_message_correction", true);
3003	}
3004
3005	public boolean sendChatStates() {
3006		return getPreferences().getBoolean("chat_states", false);
3007	}
3008
3009	public boolean saveEncryptedMessages() {
3010		return !getPreferences().getBoolean("dont_save_encrypted", false);
3011	}
3012
3013	private boolean respectAutojoin() {
3014		return getPreferences().getBoolean("autojoin", true);
3015	}
3016
3017	public boolean indicateReceived() {
3018		return getPreferences().getBoolean("indicate_received", false);
3019	}
3020
3021	public boolean useTorToConnect() {
3022		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
3023	}
3024
3025	public boolean showExtendedConnectionOptions() {
3026		return getPreferences().getBoolean("show_connection_options", false);
3027	}
3028
3029	public boolean broadcastLastActivity() {
3030		return getPreferences().getBoolean("last_activity", false);
3031	}
3032
3033	public int unreadCount() {
3034		int count = 0;
3035		for (Conversation conversation : getConversations()) {
3036			count += conversation.unreadCount();
3037		}
3038		return count;
3039	}
3040
3041
3042	public void showErrorToastInUi(int resId) {
3043		if (mOnShowErrorToast != null) {
3044			mOnShowErrorToast.onShowErrorToast(resId);
3045		}
3046	}
3047
3048	public void updateConversationUi() {
3049		if (mOnConversationUpdate != null) {
3050			mOnConversationUpdate.onConversationUpdate();
3051		}
3052	}
3053
3054	public void updateAccountUi() {
3055		if (mOnAccountUpdate != null) {
3056			mOnAccountUpdate.onAccountUpdate();
3057		}
3058	}
3059
3060	public void updateRosterUi() {
3061		if (mOnRosterUpdate != null) {
3062			mOnRosterUpdate.onRosterUpdate();
3063		}
3064	}
3065
3066	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3067		if (mOnCaptchaRequested != null) {
3068			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3069			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3070					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3071
3072			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3073			return true;
3074		}
3075		return false;
3076	}
3077
3078	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3079		if (mOnUpdateBlocklist != null) {
3080			mOnUpdateBlocklist.OnUpdateBlocklist(status);
3081		}
3082	}
3083
3084	public void updateMucRosterUi() {
3085		if (mOnMucRosterUpdate != null) {
3086			mOnMucRosterUpdate.onMucRosterUpdate();
3087		}
3088	}
3089
3090	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3091		if (mOnKeyStatusUpdated != null) {
3092			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3093		}
3094	}
3095
3096	public Account findAccountByJid(final Jid accountJid) {
3097		for (Account account : this.accounts) {
3098			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3099				return account;
3100			}
3101		}
3102		return null;
3103	}
3104
3105	public Conversation findConversationByUuid(String uuid) {
3106		for (Conversation conversation : getConversations()) {
3107			if (conversation.getUuid().equals(uuid)) {
3108				return conversation;
3109			}
3110		}
3111		return null;
3112	}
3113
3114	public boolean markRead(final Conversation conversation) {
3115		return markRead(conversation,true);
3116	}
3117
3118	public boolean markRead(final Conversation conversation, boolean clear) {
3119		if (clear) {
3120			mNotificationService.clear(conversation);
3121		}
3122		final List<Message> readMessages = conversation.markRead();
3123		if (readMessages.size() > 0) {
3124			Runnable runnable = new Runnable() {
3125				@Override
3126				public void run() {
3127					for (Message message : readMessages) {
3128						databaseBackend.updateMessage(message);
3129					}
3130				}
3131			};
3132			mDatabaseExecutor.execute(runnable);
3133			updateUnreadCountBadge();
3134			return true;
3135		} else {
3136			return false;
3137		}
3138	}
3139
3140	public synchronized void updateUnreadCountBadge() {
3141		int count = unreadCount();
3142		if (unreadCount != count) {
3143			Log.d(Config.LOGTAG, "update unread count to " + count);
3144			if (count > 0) {
3145				ShortcutBadger.applyCount(getApplicationContext(), count);
3146			} else {
3147				ShortcutBadger.removeCount(getApplicationContext());
3148			}
3149			unreadCount = count;
3150		}
3151	}
3152
3153	public void sendReadMarker(final Conversation conversation) {
3154		final Message markable = conversation.getLatestMarkableMessage();
3155		if (this.markRead(conversation)) {
3156			updateConversationUi();
3157		}
3158		if (confirmMessages()
3159				&& markable != null
3160				&& markable.trusted()
3161				&& markable.getRemoteMsgId() != null) {
3162			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3163			Account account = conversation.getAccount();
3164			final Jid to = markable.getCounterpart();
3165			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
3166			this.sendMessagePacket(conversation.getAccount(), packet);
3167		}
3168	}
3169
3170	public SecureRandom getRNG() {
3171		return this.mRandom;
3172	}
3173
3174	public MemorizingTrustManager getMemorizingTrustManager() {
3175		return this.mMemorizingTrustManager;
3176	}
3177
3178	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3179		this.mMemorizingTrustManager = trustManager;
3180	}
3181
3182	public void updateMemorizingTrustmanager() {
3183		final MemorizingTrustManager tm;
3184		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
3185		if (dontTrustSystemCAs) {
3186			tm = new MemorizingTrustManager(getApplicationContext(), null);
3187		} else {
3188			tm = new MemorizingTrustManager(getApplicationContext());
3189		}
3190		setMemorizingTrustManager(tm);
3191	}
3192
3193	public PowerManager getPowerManager() {
3194		return this.pm;
3195	}
3196
3197	public LruCache<String, Bitmap> getBitmapCache() {
3198		return this.mBitmapCache;
3199	}
3200
3201	public void syncRosterToDisk(final Account account) {
3202		Runnable runnable = new Runnable() {
3203
3204			@Override
3205			public void run() {
3206				databaseBackend.writeRoster(account.getRoster());
3207			}
3208		};
3209		mDatabaseExecutor.execute(runnable);
3210
3211	}
3212
3213	public List<String> getKnownHosts() {
3214		final List<String> hosts = new ArrayList<>();
3215		for (final Account account : getAccounts()) {
3216			if (!hosts.contains(account.getServer().toString())) {
3217				hosts.add(account.getServer().toString());
3218			}
3219			for (final Contact contact : account.getRoster().getContacts()) {
3220				if (contact.showInRoster()) {
3221					final String server = contact.getServer().toString();
3222					if (server != null && !hosts.contains(server)) {
3223						hosts.add(server);
3224					}
3225				}
3226			}
3227		}
3228		if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3229			hosts.add(Config.DOMAIN_LOCK);
3230		}
3231		if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3232			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3233		}
3234		return hosts;
3235	}
3236
3237	public List<String> getKnownConferenceHosts() {
3238		final ArrayList<String> mucServers = new ArrayList<>();
3239		for (final Account account : accounts) {
3240			if (account.getXmppConnection() != null) {
3241				final String server = account.getXmppConnection().getMucServer();
3242				if (server != null && !mucServers.contains(server)) {
3243					mucServers.add(server);
3244				}
3245			}
3246		}
3247		return mucServers;
3248	}
3249
3250	public void sendMessagePacket(Account account, MessagePacket packet) {
3251		XmppConnection connection = account.getXmppConnection();
3252		if (connection != null) {
3253			connection.sendMessagePacket(packet);
3254		}
3255	}
3256
3257	public void sendPresencePacket(Account account, PresencePacket packet) {
3258		XmppConnection connection = account.getXmppConnection();
3259		if (connection != null) {
3260			connection.sendPresencePacket(packet);
3261		}
3262	}
3263
3264	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3265		final XmppConnection connection = account.getXmppConnection();
3266		if (connection != null) {
3267			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3268			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3269		}
3270	}
3271
3272	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3273		final XmppConnection connection = account.getXmppConnection();
3274		if (connection != null) {
3275			connection.sendIqPacket(packet, callback);
3276		}
3277	}
3278
3279	public void sendPresence(final Account account) {
3280		sendPresence(account, checkListeners() && broadcastLastActivity());
3281	}
3282
3283	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3284		PresencePacket packet;
3285		if (manuallyChangePresence()) {
3286			packet =  mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3287			String message = account.getPresenceStatusMessage();
3288			if (message != null && !message.isEmpty()) {
3289				packet.addChild(new Element("status").setContent(message));
3290			}
3291		} else {
3292			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3293		}
3294		if (mLastActivity > 0 && includeIdleTimestamp) {
3295			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3296			packet.addChild("idle","urn:xmpp:idle:1").setAttribute("since", AbstractGenerator.getTimestamp(since));
3297		}
3298		sendPresencePacket(account, packet);
3299	}
3300
3301	private void deactivateGracePeriod() {
3302		for(Account account : getAccounts()) {
3303			account.deactivateGracePeriod();
3304		}
3305	}
3306
3307	public void refreshAllPresences() {
3308		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3309		for (Account account : getAccounts()) {
3310			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3311				sendPresence(account, includeIdleTimestamp);
3312			}
3313		}
3314	}
3315
3316	private void refreshAllGcmTokens() {
3317		for(Account account : getAccounts()) {
3318			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3319				mPushManagementService.registerPushTokenOnServer(account);
3320			}
3321		}
3322	}
3323
3324	private void sendOfflinePresence(final Account account) {
3325		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending offline presence");
3326		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3327	}
3328
3329	public MessageGenerator getMessageGenerator() {
3330		return this.mMessageGenerator;
3331	}
3332
3333	public PresenceGenerator getPresenceGenerator() {
3334		return this.mPresenceGenerator;
3335	}
3336
3337	public IqGenerator getIqGenerator() {
3338		return this.mIqGenerator;
3339	}
3340
3341	public IqParser getIqParser() {
3342		return this.mIqParser;
3343	}
3344
3345	public JingleConnectionManager getJingleConnectionManager() {
3346		return this.mJingleConnectionManager;
3347	}
3348
3349	public MessageArchiveService getMessageArchiveService() {
3350		return this.mMessageArchiveService;
3351	}
3352
3353	public List<Contact> findContacts(Jid jid) {
3354		ArrayList<Contact> contacts = new ArrayList<>();
3355		for (Account account : getAccounts()) {
3356			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3357				Contact contact = account.getRoster().getContactFromRoster(jid);
3358				if (contact != null) {
3359					contacts.add(contact);
3360				}
3361			}
3362		}
3363		return contacts;
3364	}
3365
3366	public Conversation findFirstMuc(Jid jid) {
3367		for(Conversation conversation : getConversations()) {
3368			if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3369					&& conversation.getMode() == Conversation.MODE_MULTI) {
3370				return conversation;
3371			}
3372		}
3373		return null;
3374	}
3375
3376	public NotificationService getNotificationService() {
3377		return this.mNotificationService;
3378	}
3379
3380	public HttpConnectionManager getHttpConnectionManager() {
3381		return this.mHttpConnectionManager;
3382	}
3383
3384	public void resendFailedMessages(final Message message) {
3385		final Collection<Message> messages = new ArrayList<>();
3386		Message current = message;
3387		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3388			messages.add(current);
3389			if (current.mergeable(current.next())) {
3390				current = current.next();
3391			} else {
3392				break;
3393			}
3394		}
3395		for (final Message msg : messages) {
3396			msg.setTime(System.currentTimeMillis());
3397			markMessage(msg, Message.STATUS_WAITING);
3398			this.resendMessage(msg, false);
3399		}
3400	}
3401
3402	public void clearConversationHistory(final Conversation conversation) {
3403		conversation.clearMessages();
3404		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3405		conversation.setLastClearHistory(System.currentTimeMillis());
3406		Runnable runnable = new Runnable() {
3407			@Override
3408			public void run() {
3409				databaseBackend.deleteMessagesInConversation(conversation);
3410				databaseBackend.updateConversation(conversation);
3411			}
3412		};
3413		mDatabaseExecutor.execute(runnable);
3414	}
3415
3416	public void sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3417		if (blockable != null && blockable.getBlockedJid() != null) {
3418			final Jid jid = blockable.getBlockedJid();
3419			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3420
3421				@Override
3422				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3423					if (packet.getType() == IqPacket.TYPE.RESULT) {
3424						account.getBlocklist().add(jid);
3425						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3426					}
3427				}
3428			});
3429		}
3430	}
3431
3432	public void sendUnblockRequest(final Blockable blockable) {
3433		if (blockable != null && blockable.getJid() != null) {
3434			final Jid jid = blockable.getBlockedJid();
3435			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3436				@Override
3437				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3438					if (packet.getType() == IqPacket.TYPE.RESULT) {
3439						account.getBlocklist().remove(jid);
3440						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3441					}
3442				}
3443			});
3444		}
3445	}
3446
3447	public void publishDisplayName(Account account) {
3448		String displayName = account.getDisplayName();
3449		if (displayName != null && !displayName.isEmpty()) {
3450			IqPacket publish = mIqGenerator.publishNick(displayName);
3451			sendIqPacket(account, publish, new OnIqPacketReceived() {
3452				@Override
3453				public void onIqPacketReceived(Account account, IqPacket packet) {
3454					if (packet.getType() == IqPacket.TYPE.ERROR) {
3455						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3456					}
3457				}
3458			});
3459		}
3460	}
3461
3462	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3463		ServiceDiscoveryResult result = discoCache.get(key);
3464		if (result != null) {
3465			return result;
3466		} else {
3467			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3468			if (result != null) {
3469				discoCache.put(key, result);
3470			}
3471			return result;
3472		}
3473	}
3474
3475	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3476		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3477		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3478		if (disco != null) {
3479			presence.setServiceDiscoveryResult(disco);
3480		} else {
3481			if (!account.inProgressDiscoFetches.contains(key)) {
3482				account.inProgressDiscoFetches.add(key);
3483				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3484				request.setTo(jid);
3485				request.query("http://jabber.org/protocol/disco#info");
3486				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3487				sendIqPacket(account, request, new OnIqPacketReceived() {
3488					@Override
3489					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3490						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3491							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3492							if (presence.getVer().equals(disco.getVer())) {
3493								databaseBackend.insertDiscoveryResult(disco);
3494								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3495							} else {
3496								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3497							}
3498						}
3499						account.inProgressDiscoFetches.remove(key);
3500					}
3501				});
3502			}
3503		}
3504	}
3505
3506	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3507		for(Contact contact : roster.getContacts()) {
3508			for(Presence presence : contact.getPresences().getPresences().values()) {
3509				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3510					presence.setServiceDiscoveryResult(disco);
3511				}
3512			}
3513		}
3514	}
3515
3516	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3517		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3518		request.addChild("prefs","urn:xmpp:mam:0");
3519		sendIqPacket(account, request, new OnIqPacketReceived() {
3520			@Override
3521			public void onIqPacketReceived(Account account, IqPacket packet) {
3522				Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3523				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3524					callback.onPreferencesFetched(prefs);
3525				} else {
3526					callback.onPreferencesFetchFailed();
3527				}
3528			}
3529		});
3530	}
3531
3532	public PushManagementService getPushManagementService() {
3533		return mPushManagementService;
3534	}
3535
3536	public Account getPendingAccount() {
3537		Account pending = null;
3538		for(Account account : getAccounts()) {
3539			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3540				pending = account;
3541			} else {
3542				return null;
3543			}
3544		}
3545		return pending;
3546	}
3547
3548	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3549		if (!statusMessage.isEmpty()) {
3550			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3551		}
3552		changeStatusReal(account, status, statusMessage, send);
3553	}
3554
3555	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3556		account.setPresenceStatus(status);
3557		account.setPresenceStatusMessage(statusMessage);
3558		databaseBackend.updateAccount(account);
3559		if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3560			sendPresence(account);
3561		}
3562	}
3563
3564	public void changeStatus(Presence.Status status, String statusMessage) {
3565		if (!statusMessage.isEmpty()) {
3566			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3567		}
3568		for(Account account : getAccounts()) {
3569			changeStatusReal(account, status, statusMessage, true);
3570		}
3571	}
3572
3573	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3574		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3575		for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3576			if (!templates.contains(template)) {
3577				templates.add(0, template);
3578			}
3579		}
3580		return templates;
3581	}
3582
3583	public void saveConversationAsBookmark(Conversation conversation, String name) {
3584		Account account = conversation.getAccount();
3585		Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3586		if (!conversation.getJid().isBareJid()) {
3587			bookmark.setNick(conversation.getJid().getResourcepart());
3588		}
3589		if (name != null && !name.trim().isEmpty()) {
3590			bookmark.setBookmarkName(name.trim());
3591		}
3592		bookmark.setAutojoin(getPreferences().getBoolean("autojoin",true));
3593		account.getBookmarks().add(bookmark);
3594		pushBookmarks(account);
3595		conversation.setBookmark(bookmark);
3596	}
3597
3598	public interface OnMamPreferencesFetched {
3599		void onPreferencesFetched(Element prefs);
3600		void onPreferencesFetchFailed();
3601	}
3602
3603	public void pushMamPreferences(Account account, Element prefs) {
3604		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3605		set.addChild(prefs);
3606		sendIqPacket(account, set, null);
3607	}
3608
3609	public interface OnAccountCreated {
3610		void onAccountCreated(Account account);
3611
3612		void informUser(int r);
3613	}
3614
3615	public interface OnMoreMessagesLoaded {
3616		void onMoreMessagesLoaded(int count, Conversation conversation);
3617
3618		void informUser(int r);
3619	}
3620
3621	public interface OnAccountPasswordChanged {
3622		void onPasswordChangeSucceeded();
3623
3624		void onPasswordChangeFailed();
3625	}
3626
3627	public interface OnAffiliationChanged {
3628		void onAffiliationChangedSuccessful(Jid jid);
3629
3630		void onAffiliationChangeFailed(Jid jid, int resId);
3631	}
3632
3633	public interface OnRoleChanged {
3634		void onRoleChangedSuccessful(String nick);
3635
3636		void onRoleChangeFailed(String nick, int resid);
3637	}
3638
3639	public interface OnConversationUpdate {
3640		void onConversationUpdate();
3641	}
3642
3643	public interface OnAccountUpdate {
3644		void onAccountUpdate();
3645	}
3646
3647	public interface OnCaptchaRequested {
3648		void onCaptchaRequested(Account account,
3649								String id,
3650								Data data,
3651								Bitmap captcha);
3652	}
3653
3654	public interface OnRosterUpdate {
3655		void onRosterUpdate();
3656	}
3657
3658	public interface OnMucRosterUpdate {
3659		void onMucRosterUpdate();
3660	}
3661
3662	public interface OnConferenceConfigurationFetched {
3663		void onConferenceConfigurationFetched(Conversation conversation);
3664
3665		void onFetchFailed(Conversation conversation, Element error);
3666	}
3667
3668	public interface OnConferenceJoined {
3669		void onConferenceJoined(Conversation conversation);
3670	}
3671
3672	public interface OnConferenceOptionsPushed {
3673		void onPushSucceeded();
3674
3675		void onPushFailed();
3676	}
3677
3678	public interface OnShowErrorToast {
3679		void onShowErrorToast(int resId);
3680	}
3681
3682	public class XmppConnectionBinder extends Binder {
3683		public XmppConnectionService getService() {
3684			return XmppConnectionService.this;
3685		}
3686	}
3687}