XmppConnectionService.java

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