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