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