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(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(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();
 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();
 791		}
 792	}
 793
 794	private void logoutAndSave() {
 795		for (final Account account : accounts) {
 796			databaseBackend.writeRoster(account.getRoster());
 797			if (account.getXmppConnection() != null) {
 798				new Thread(new Runnable() {
 799					@Override
 800					public void run() {
 801						disconnect(account, false);
 802					}
 803				}).start();
 804				cancelWakeUpCall(account.getUuid().hashCode());
 805			}
 806		}
 807		Log.d(Config.LOGTAG, "good bye");
 808		stopSelf();
 809	}
 810
 811	private void cancelWakeUpCall(int requestCode) {
 812		final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
 813		final Intent intent = new Intent(this, EventReceiver.class);
 814		intent.setAction("ping");
 815		alarmManager.cancel(PendingIntent.getBroadcast(this, requestCode, intent, 0));
 816	}
 817
 818	public void scheduleWakeUpCall(int seconds, int requestCode) {
 819		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
 820
 821		Context context = getApplicationContext();
 822		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 823
 824		Intent intent = new Intent(context, EventReceiver.class);
 825		intent.setAction("ping");
 826		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
 827		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 828	}
 829
 830	public XmppConnection createConnection(final Account account) {
 831		final SharedPreferences sharedPref = getPreferences();
 832		account.setResource(sharedPref.getString("resource", "mobile")
 833				.toLowerCase(Locale.getDefault()));
 834		final XmppConnection connection = new XmppConnection(account, this);
 835		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 836		connection.setOnStatusChangedListener(this.statusListener);
 837		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 838		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 839		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 840		connection.setOnBindListener(this.mOnBindListener);
 841		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 842		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 843		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
 844		AxolotlService axolotlService = account.getAxolotlService();
 845		if (axolotlService != null) {
 846			connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
 847		}
 848		return connection;
 849	}
 850
 851	public void sendChatState(Conversation conversation) {
 852		if (sendChatStates()) {
 853			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
 854			sendMessagePacket(conversation.getAccount(), packet);
 855		}
 856	}
 857
 858	private void sendFileMessage(final Message message, final boolean delay) {
 859		Log.d(Config.LOGTAG, "send file message");
 860		final Account account = message.getConversation().getAccount();
 861		if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())) {
 862			mHttpConnectionManager.createNewUploadConnection(message, delay);
 863		} else {
 864			mJingleConnectionManager.createNewConnection(message);
 865		}
 866	}
 867
 868	public void sendMessage(final Message message) {
 869		sendMessage(message, false, false);
 870	}
 871
 872	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
 873		final Account account = message.getConversation().getAccount();
 874		final Conversation conversation = message.getConversation();
 875		account.deactivateGracePeriod();
 876		MessagePacket packet = null;
 877		final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
 878				|| account.getServerIdentity() != XmppConnection.Identity.SLACK)
 879				&& !message.edited();
 880		boolean saveInDb = addToConversation;
 881		message.setStatus(Message.STATUS_WAITING);
 882
 883		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
 884			message.getConversation().endOtrIfNeeded();
 885			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
 886					new Conversation.OnMessageFound() {
 887						@Override
 888						public void onMessageFound(Message message) {
 889							markMessage(message, Message.STATUS_SEND_FAILED);
 890						}
 891					});
 892		}
 893
 894		if (account.isOnlineAndConnected()) {
 895			switch (message.getEncryption()) {
 896				case Message.ENCRYPTION_NONE:
 897					if (message.needsUploading()) {
 898						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
 899								|| message.fixCounterpart()) {
 900							this.sendFileMessage(message, delay);
 901						} else {
 902							break;
 903						}
 904					} else {
 905						packet = mMessageGenerator.generateChat(message);
 906					}
 907					break;
 908				case Message.ENCRYPTION_PGP:
 909				case Message.ENCRYPTION_DECRYPTED:
 910					if (message.needsUploading()) {
 911						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
 912								|| message.fixCounterpart()) {
 913							this.sendFileMessage(message, delay);
 914						} else {
 915							break;
 916						}
 917					} else {
 918						packet = mMessageGenerator.generatePgpChat(message);
 919					}
 920					break;
 921				case Message.ENCRYPTION_OTR:
 922					SessionImpl otrSession = conversation.getOtrSession();
 923					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
 924						try {
 925							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
 926						} catch (InvalidJidException e) {
 927							break;
 928						}
 929						if (message.needsUploading()) {
 930							mJingleConnectionManager.createNewConnection(message);
 931						} else {
 932							packet = mMessageGenerator.generateOtrChat(message);
 933						}
 934					} else if (otrSession == null) {
 935						if (message.fixCounterpart()) {
 936							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
 937						} else {
 938							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fix counterpart for OTR message to contact "+message.getContact().getJid());
 939							break;
 940						}
 941					} else {
 942						Log.d(Config.LOGTAG,account.getJid().toBareJid()+" OTR session with "+message.getContact()+" is in wrong state: "+otrSession.getSessionStatus().toString());
 943					}
 944					break;
 945				case Message.ENCRYPTION_AXOLOTL:
 946					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
 947					if (message.needsUploading()) {
 948						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
 949								|| message.fixCounterpart()) {
 950							this.sendFileMessage(message, delay);
 951						} else {
 952							break;
 953						}
 954					} else {
 955						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
 956						if (axolotlMessage == null) {
 957							account.getAxolotlService().preparePayloadMessage(message, delay);
 958						} else {
 959							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
 960						}
 961					}
 962					break;
 963
 964			}
 965			if (packet != null) {
 966				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 967					message.setStatus(Message.STATUS_UNSEND);
 968				} else {
 969					message.setStatus(Message.STATUS_SEND);
 970				}
 971			}
 972		} else {
 973			switch (message.getEncryption()) {
 974				case Message.ENCRYPTION_DECRYPTED:
 975					if (!message.needsUploading()) {
 976						String pgpBody = message.getEncryptedBody();
 977						String decryptedBody = message.getBody();
 978						message.setBody(pgpBody);
 979						message.setEncryption(Message.ENCRYPTION_PGP);
 980						databaseBackend.createMessage(message);
 981						saveInDb = false;
 982						message.setBody(decryptedBody);
 983						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 984					}
 985					break;
 986				case Message.ENCRYPTION_OTR:
 987					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
 988						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": create otr session without starting for "+message.getContact().getJid());
 989						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
 990					}
 991					break;
 992				case Message.ENCRYPTION_AXOLOTL:
 993					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
 994					break;
 995			}
 996		}
 997
 998		if (resend) {
 999			if (packet != null && addToConversation) {
1000				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
1001					markMessage(message, Message.STATUS_UNSEND);
1002				} else {
1003					markMessage(message, Message.STATUS_SEND);
1004				}
1005			}
1006		} else {
1007			if (addToConversation) {
1008				conversation.add(message);
1009			}
1010			if (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages()) {
1011				if (saveInDb) {
1012					databaseBackend.createMessage(message);
1013				} else if (message.edited()) {
1014					databaseBackend.updateMessage(message, message.getEditedId());
1015				}
1016			}
1017			updateConversationUi();
1018		}
1019		if (packet != null) {
1020			if (delay) {
1021				mMessageGenerator.addDelay(packet, message.getTimeSent());
1022			}
1023			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1024				if (this.sendChatStates()) {
1025					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1026				}
1027			}
1028			sendMessagePacket(account, packet);
1029		}
1030	}
1031
1032	private void sendUnsentMessages(final Conversation conversation) {
1033		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
1034
1035			@Override
1036			public void onMessageFound(Message message) {
1037				resendMessage(message, true);
1038			}
1039		});
1040	}
1041
1042	public void resendMessage(final Message message, final boolean delay) {
1043		sendMessage(message, true, delay);
1044	}
1045
1046	public void fetchRosterFromServer(final Account account) {
1047		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1048		if (!"".equals(account.getRosterVersion())) {
1049			Log.d(Config.LOGTAG, account.getJid().toBareJid()
1050					+ ": fetching roster version " + account.getRosterVersion());
1051		} else {
1052			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1053		}
1054		iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
1055		sendIqPacket(account, iqPacket, mIqParser);
1056	}
1057
1058	public void fetchBookmarks(final Account account) {
1059		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1060		final Element query = iqPacket.query("jabber:iq:private");
1061		query.addChild("storage", "storage:bookmarks");
1062		final OnIqPacketReceived callback = new OnIqPacketReceived() {
1063
1064			@Override
1065			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1066				if (packet.getType() == IqPacket.TYPE.RESULT) {
1067					final Element query = packet.query();
1068					final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1069					final Element storage = query.findChild("storage", "storage:bookmarks");
1070					final boolean autojoin = respectAutojoin();
1071					if (storage != null) {
1072						for (final Element item : storage.getChildren()) {
1073							if (item.getName().equals("conference")) {
1074								final Bookmark bookmark = Bookmark.parse(item, account);
1075								Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1076								if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1077									bookmark.setBookmarkName(old.getBookmarkName());
1078								}
1079								Conversation conversation = find(bookmark);
1080								if (conversation != null) {
1081									conversation.setBookmark(bookmark);
1082								} else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1083									conversation = findOrCreateConversation(
1084											account, bookmark.getJid(), true);
1085									conversation.setBookmark(bookmark);
1086									joinMuc(conversation);
1087								}
1088							}
1089						}
1090					}
1091					account.setBookmarks(new ArrayList<>(bookmarks.values()));
1092				} else {
1093					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1094				}
1095			}
1096		};
1097		sendIqPacket(account, iqPacket, callback);
1098	}
1099
1100	public void pushBookmarks(Account account) {
1101		Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1102		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1103		Element query = iqPacket.query("jabber:iq:private");
1104		Element storage = query.addChild("storage", "storage:bookmarks");
1105		for (Bookmark bookmark : account.getBookmarks()) {
1106			storage.addChild(bookmark);
1107		}
1108		sendIqPacket(account, iqPacket, mDefaultIqHandler);
1109	}
1110
1111	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
1112		if (mPhoneContactMergerThread != null) {
1113			mPhoneContactMergerThread.interrupt();
1114		}
1115		mPhoneContactMergerThread = new Thread(new Runnable() {
1116			@Override
1117			public void run() {
1118				Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1119				for (Account account : accounts) {
1120					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1121					for (Bundle phoneContact : phoneContacts) {
1122						if (Thread.interrupted()) {
1123							Log.d(Config.LOGTAG, "interrupted merging phone contacts");
1124							return;
1125						}
1126						Jid jid;
1127						try {
1128							jid = Jid.fromString(phoneContact.getString("jid"));
1129						} catch (final InvalidJidException e) {
1130							continue;
1131						}
1132						final Contact contact = account.getRoster().getContact(jid);
1133						String systemAccount = phoneContact.getInt("phoneid")
1134								+ "#"
1135								+ phoneContact.getString("lookup");
1136						contact.setSystemAccount(systemAccount);
1137						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1138							getAvatarService().clear(contact);
1139						}
1140						contact.setSystemName(phoneContact.getString("displayname"));
1141						withSystemAccounts.remove(contact);
1142					}
1143					for (Contact contact : withSystemAccounts) {
1144						contact.setSystemAccount(null);
1145						contact.setSystemName(null);
1146						if (contact.setPhotoUri(null)) {
1147							getAvatarService().clear(contact);
1148						}
1149					}
1150				}
1151				Log.d(Config.LOGTAG, "finished merging phone contacts");
1152				updateAccountUi();
1153			}
1154		});
1155		mPhoneContactMergerThread.start();
1156	}
1157
1158	private void restoreFromDatabase() {
1159		synchronized (this.conversations) {
1160			final Map<String, Account> accountLookupTable = new Hashtable<>();
1161			for (Account account : this.accounts) {
1162				accountLookupTable.put(account.getUuid(), account);
1163			}
1164			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1165			for (Conversation conversation : this.conversations) {
1166				Account account = accountLookupTable.get(conversation.getAccountUuid());
1167				conversation.setAccount(account);
1168			}
1169			Runnable runnable = new Runnable() {
1170				@Override
1171				public void run() {
1172					Log.d(Config.LOGTAG, "restoring roster");
1173					for (Account account : accounts) {
1174						databaseBackend.readRoster(account.getRoster());
1175						account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1176					}
1177					getBitmapCache().evictAll();
1178					Looper.prepare();
1179					loadPhoneContacts();
1180					Log.d(Config.LOGTAG, "restoring messages");
1181					for (Conversation conversation : conversations) {
1182						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1183						checkDeletedFiles(conversation);
1184						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1185							@Override
1186							public void onMessageFound(Message message) {
1187								mNotificationService.pushFromBacklog(message);
1188							}
1189						});
1190					}
1191					mNotificationService.finishBacklog(false);
1192					mRestoredFromDatabase = true;
1193					Log.d(Config.LOGTAG, "restored all messages");
1194					updateConversationUi();
1195				}
1196			};
1197			mDatabaseExecutor.execute(runnable);
1198		}
1199	}
1200
1201	public void loadPhoneContacts() {
1202		PhoneHelper.loadPhoneContacts(getApplicationContext(),
1203				new CopyOnWriteArrayList<Bundle>(),
1204				XmppConnectionService.this);
1205	}
1206
1207	public List<Conversation> getConversations() {
1208		return this.conversations;
1209	}
1210
1211	private void checkDeletedFiles(Conversation conversation) {
1212		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1213
1214			@Override
1215			public void onMessageFound(Message message) {
1216				if (!getFileBackend().isFileAvailable(message)) {
1217					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1218					final int s = message.getStatus();
1219					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1220						markMessage(message, Message.STATUS_SEND_FAILED);
1221					}
1222				}
1223			}
1224		});
1225	}
1226
1227	private void markFileDeleted(String uuid) {
1228		for (Conversation conversation : getConversations()) {
1229			Message message = conversation.findMessageWithFileAndUuid(uuid);
1230			if (message != null) {
1231				if (!getFileBackend().isFileAvailable(message)) {
1232					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1233					final int s = message.getStatus();
1234					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1235						markMessage(message, Message.STATUS_SEND_FAILED);
1236					} else {
1237						updateConversationUi();
1238					}
1239				}
1240				return;
1241			}
1242		}
1243	}
1244
1245	public void populateWithOrderedConversations(final List<Conversation> list) {
1246		populateWithOrderedConversations(list, true);
1247	}
1248
1249	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1250		list.clear();
1251		if (includeNoFileUpload) {
1252			list.addAll(getConversations());
1253		} else {
1254			for (Conversation conversation : getConversations()) {
1255				if (conversation.getMode() == Conversation.MODE_SINGLE
1256						|| conversation.getAccount().httpUploadAvailable()) {
1257					list.add(conversation);
1258				}
1259			}
1260		}
1261		Collections.sort(list, new Comparator<Conversation>() {
1262			@Override
1263			public int compare(Conversation lhs, Conversation rhs) {
1264				Message left = lhs.getLatestMessage();
1265				Message right = rhs.getLatestMessage();
1266				if (left.getTimeSent() > right.getTimeSent()) {
1267					return -1;
1268				} else if (left.getTimeSent() < right.getTimeSent()) {
1269					return 1;
1270				} else {
1271					return 0;
1272				}
1273			}
1274		});
1275	}
1276
1277	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1278		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1279			return;
1280		} else if (timestamp == 0) {
1281			return;
1282		}
1283		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1284		Runnable runnable = new Runnable() {
1285			@Override
1286			public void run() {
1287				final Account account = conversation.getAccount();
1288				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1289				if (messages.size() > 0) {
1290					conversation.addAll(0, messages);
1291					checkDeletedFiles(conversation);
1292					callback.onMoreMessagesLoaded(messages.size(), conversation);
1293				} else if (conversation.hasMessagesLeftOnServer()
1294						&& account.isOnlineAndConnected()
1295						&& conversation.getLastClearHistory() == 0) {
1296					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1297							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1298						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1299						if (query != null) {
1300							query.setCallback(callback);
1301						}
1302						callback.informUser(R.string.fetching_history_from_server);
1303					}
1304				}
1305			}
1306		};
1307		mDatabaseExecutor.execute(runnable);
1308	}
1309
1310	public List<Account> getAccounts() {
1311		return this.accounts;
1312	}
1313
1314	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1315		for (final Conversation conversation : haystack) {
1316			if (conversation.getContact() == contact) {
1317				return conversation;
1318			}
1319		}
1320		return null;
1321	}
1322
1323	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1324		if (jid == null) {
1325			return null;
1326		}
1327		for (final Conversation conversation : haystack) {
1328			if ((account == null || conversation.getAccount() == account)
1329					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1330				return conversation;
1331			}
1332		}
1333		return null;
1334	}
1335
1336	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1337		return this.findOrCreateConversation(account, jid, muc, null);
1338	}
1339
1340	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1341		synchronized (this.conversations) {
1342			Conversation conversation = find(account, jid);
1343			if (conversation != null) {
1344				return conversation;
1345			}
1346			conversation = databaseBackend.findConversation(account, jid);
1347			if (conversation != null) {
1348				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1349				conversation.setAccount(account);
1350				if (muc) {
1351					conversation.setMode(Conversation.MODE_MULTI);
1352					conversation.setContactJid(jid);
1353				} else {
1354					conversation.setMode(Conversation.MODE_SINGLE);
1355					conversation.setContactJid(jid.toBareJid());
1356				}
1357				conversation.setNextEncryption(-1);
1358				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1359				this.databaseBackend.updateConversation(conversation);
1360			} else {
1361				String conversationName;
1362				Contact contact = account.getRoster().getContact(jid);
1363				if (contact != null) {
1364					conversationName = contact.getDisplayName();
1365				} else {
1366					conversationName = jid.getLocalpart();
1367				}
1368				if (muc) {
1369					conversation = new Conversation(conversationName, account, jid,
1370							Conversation.MODE_MULTI);
1371				} else {
1372					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1373							Conversation.MODE_SINGLE);
1374				}
1375				this.databaseBackend.createConversation(conversation);
1376			}
1377			if (account.getXmppConnection() != null
1378					&& account.getXmppConnection().getFeatures().mam()
1379					&& !muc) {
1380				if (query == null) {
1381					this.mMessageArchiveService.query(conversation);
1382				} else {
1383					if (query.getConversation() == null) {
1384						this.mMessageArchiveService.query(conversation, query.getStart());
1385					}
1386				}
1387			}
1388			checkDeletedFiles(conversation);
1389			this.conversations.add(conversation);
1390			updateConversationUi();
1391			return conversation;
1392		}
1393	}
1394
1395	public void archiveConversation(Conversation conversation) {
1396		getNotificationService().clear(conversation);
1397		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1398		conversation.setNextEncryption(-1);
1399		synchronized (this.conversations) {
1400			if (conversation.getMode() == Conversation.MODE_MULTI) {
1401				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1402					Bookmark bookmark = conversation.getBookmark();
1403					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1404						bookmark.setAutojoin(false);
1405						pushBookmarks(bookmark.getAccount());
1406					}
1407				}
1408				leaveMuc(conversation);
1409			} else {
1410				conversation.endOtrIfNeeded();
1411				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1412					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1413					sendPresencePacket(
1414							conversation.getAccount(),
1415							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1416					);
1417				}
1418			}
1419			this.databaseBackend.updateConversation(conversation);
1420			this.conversations.remove(conversation);
1421			updateConversationUi();
1422		}
1423	}
1424
1425	public void createAccount(final Account account) {
1426		account.initAccountServices(this);
1427		databaseBackend.createAccount(account);
1428		this.accounts.add(account);
1429		this.reconnectAccountInBackground(account);
1430		updateAccountUi();
1431	}
1432
1433	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1434		new Thread(new Runnable() {
1435			@Override
1436			public void run() {
1437				try {
1438					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1439					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1440					if (findAccountByJid(info.first) == null) {
1441						Account account = new Account(info.first, "");
1442						account.setPrivateKeyAlias(alias);
1443						account.setOption(Account.OPTION_DISABLED, true);
1444						account.setDisplayName(info.second);
1445						createAccount(account);
1446						callback.onAccountCreated(account);
1447						if (Config.X509_VERIFICATION) {
1448							try {
1449								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1450							} catch (CertificateException e) {
1451								callback.informUser(R.string.certificate_chain_is_not_trusted);
1452							}
1453						}
1454					} else {
1455						callback.informUser(R.string.account_already_exists);
1456					}
1457				} catch (Exception e) {
1458					e.printStackTrace();
1459					callback.informUser(R.string.unable_to_parse_certificate);
1460				}
1461			}
1462		}).start();
1463
1464	}
1465
1466	public void updateKeyInAccount(final Account account, final String alias) {
1467		Log.d(Config.LOGTAG, "update key in account " + alias);
1468		try {
1469			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1470			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1471			if (account.getJid().toBareJid().equals(info.first)) {
1472				account.setPrivateKeyAlias(alias);
1473				account.setDisplayName(info.second);
1474				databaseBackend.updateAccount(account);
1475				if (Config.X509_VERIFICATION) {
1476					try {
1477						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1478					} catch (CertificateException e) {
1479						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1480					}
1481					account.getAxolotlService().regenerateKeys(true);
1482				}
1483			} else {
1484				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1485			}
1486		} catch (Exception e) {
1487			e.printStackTrace();
1488		}
1489	}
1490
1491	public void updateAccount(final Account account) {
1492		this.statusListener.onStatusChanged(account);
1493		databaseBackend.updateAccount(account);
1494		reconnectAccountInBackground(account);
1495		updateAccountUi();
1496		getNotificationService().updateErrorNotification();
1497	}
1498
1499	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1500		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1501		sendIqPacket(account, iq, new OnIqPacketReceived() {
1502			@Override
1503			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1504				if (packet.getType() == IqPacket.TYPE.RESULT) {
1505					account.setPassword(newPassword);
1506					databaseBackend.updateAccount(account);
1507					callback.onPasswordChangeSucceeded();
1508				} else {
1509					callback.onPasswordChangeFailed();
1510				}
1511			}
1512		});
1513	}
1514
1515	public void deleteAccount(final Account account) {
1516		synchronized (this.conversations) {
1517			for (final Conversation conversation : conversations) {
1518				if (conversation.getAccount() == account) {
1519					if (conversation.getMode() == Conversation.MODE_MULTI) {
1520						leaveMuc(conversation);
1521					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1522						conversation.endOtrIfNeeded();
1523					}
1524					conversations.remove(conversation);
1525				}
1526			}
1527			if (account.getXmppConnection() != null) {
1528				this.disconnect(account, true);
1529			}
1530			Runnable runnable = new Runnable() {
1531				@Override
1532				public void run() {
1533					databaseBackend.deleteAccount(account);
1534				}
1535			};
1536			mDatabaseExecutor.execute(runnable);
1537			this.accounts.remove(account);
1538			updateAccountUi();
1539			getNotificationService().updateErrorNotification();
1540		}
1541	}
1542
1543	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1544		synchronized (this) {
1545			if (checkListeners()) {
1546				switchToForeground();
1547			}
1548			this.mOnConversationUpdate = listener;
1549			this.mNotificationService.setIsInForeground(true);
1550			if (this.convChangedListenerCount < 2) {
1551				this.convChangedListenerCount++;
1552			}
1553		}
1554	}
1555
1556	public void removeOnConversationListChangedListener() {
1557		synchronized (this) {
1558			this.convChangedListenerCount--;
1559			if (this.convChangedListenerCount <= 0) {
1560				this.convChangedListenerCount = 0;
1561				this.mOnConversationUpdate = null;
1562				this.mNotificationService.setIsInForeground(false);
1563				if (checkListeners()) {
1564					switchToBackground();
1565				}
1566			}
1567		}
1568	}
1569
1570	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1571		synchronized (this) {
1572			if (checkListeners()) {
1573				switchToForeground();
1574			}
1575			this.mOnShowErrorToast = onShowErrorToast;
1576			if (this.showErrorToastListenerCount < 2) {
1577				this.showErrorToastListenerCount++;
1578			}
1579		}
1580		this.mOnShowErrorToast = onShowErrorToast;
1581	}
1582
1583	public void removeOnShowErrorToastListener() {
1584		synchronized (this) {
1585			this.showErrorToastListenerCount--;
1586			if (this.showErrorToastListenerCount <= 0) {
1587				this.showErrorToastListenerCount = 0;
1588				this.mOnShowErrorToast = null;
1589				if (checkListeners()) {
1590					switchToBackground();
1591				}
1592			}
1593		}
1594	}
1595
1596	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1597		synchronized (this) {
1598			if (checkListeners()) {
1599				switchToForeground();
1600			}
1601			this.mOnAccountUpdate = listener;
1602			if (this.accountChangedListenerCount < 2) {
1603				this.accountChangedListenerCount++;
1604			}
1605		}
1606	}
1607
1608	public void removeOnAccountListChangedListener() {
1609		synchronized (this) {
1610			this.accountChangedListenerCount--;
1611			if (this.accountChangedListenerCount <= 0) {
1612				this.mOnAccountUpdate = null;
1613				this.accountChangedListenerCount = 0;
1614				if (checkListeners()) {
1615					switchToBackground();
1616				}
1617			}
1618		}
1619	}
1620
1621	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1622		synchronized (this) {
1623			if (checkListeners()) {
1624				switchToForeground();
1625			}
1626			this.mOnCaptchaRequested = listener;
1627			if (this.captchaRequestedListenerCount < 2) {
1628				this.captchaRequestedListenerCount++;
1629			}
1630		}
1631	}
1632
1633	public void removeOnCaptchaRequestedListener() {
1634		synchronized (this) {
1635			this.captchaRequestedListenerCount--;
1636			if (this.captchaRequestedListenerCount <= 0) {
1637				this.mOnCaptchaRequested = null;
1638				this.captchaRequestedListenerCount = 0;
1639				if (checkListeners()) {
1640					switchToBackground();
1641				}
1642			}
1643		}
1644	}
1645
1646	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1647		synchronized (this) {
1648			if (checkListeners()) {
1649				switchToForeground();
1650			}
1651			this.mOnRosterUpdate = listener;
1652			if (this.rosterChangedListenerCount < 2) {
1653				this.rosterChangedListenerCount++;
1654			}
1655		}
1656	}
1657
1658	public void removeOnRosterUpdateListener() {
1659		synchronized (this) {
1660			this.rosterChangedListenerCount--;
1661			if (this.rosterChangedListenerCount <= 0) {
1662				this.rosterChangedListenerCount = 0;
1663				this.mOnRosterUpdate = null;
1664				if (checkListeners()) {
1665					switchToBackground();
1666				}
1667			}
1668		}
1669	}
1670
1671	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1672		synchronized (this) {
1673			if (checkListeners()) {
1674				switchToForeground();
1675			}
1676			this.mOnUpdateBlocklist = listener;
1677			if (this.updateBlocklistListenerCount < 2) {
1678				this.updateBlocklistListenerCount++;
1679			}
1680		}
1681	}
1682
1683	public void removeOnUpdateBlocklistListener() {
1684		synchronized (this) {
1685			this.updateBlocklistListenerCount--;
1686			if (this.updateBlocklistListenerCount <= 0) {
1687				this.updateBlocklistListenerCount = 0;
1688				this.mOnUpdateBlocklist = null;
1689				if (checkListeners()) {
1690					switchToBackground();
1691				}
1692			}
1693		}
1694	}
1695
1696	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1697		synchronized (this) {
1698			if (checkListeners()) {
1699				switchToForeground();
1700			}
1701			this.mOnKeyStatusUpdated = listener;
1702			if (this.keyStatusUpdatedListenerCount < 2) {
1703				this.keyStatusUpdatedListenerCount++;
1704			}
1705		}
1706	}
1707
1708	public void removeOnNewKeysAvailableListener() {
1709		synchronized (this) {
1710			this.keyStatusUpdatedListenerCount--;
1711			if (this.keyStatusUpdatedListenerCount <= 0) {
1712				this.keyStatusUpdatedListenerCount = 0;
1713				this.mOnKeyStatusUpdated = null;
1714				if (checkListeners()) {
1715					switchToBackground();
1716				}
1717			}
1718		}
1719	}
1720
1721	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1722		synchronized (this) {
1723			if (checkListeners()) {
1724				switchToForeground();
1725			}
1726			this.mOnMucRosterUpdate = listener;
1727			if (this.mucRosterChangedListenerCount < 2) {
1728				this.mucRosterChangedListenerCount++;
1729			}
1730		}
1731	}
1732
1733	public void removeOnMucRosterUpdateListener() {
1734		synchronized (this) {
1735			this.mucRosterChangedListenerCount--;
1736			if (this.mucRosterChangedListenerCount <= 0) {
1737				this.mucRosterChangedListenerCount = 0;
1738				this.mOnMucRosterUpdate = null;
1739				if (checkListeners()) {
1740					switchToBackground();
1741				}
1742			}
1743		}
1744	}
1745
1746	private boolean checkListeners() {
1747		return (this.mOnAccountUpdate == null
1748				&& this.mOnConversationUpdate == null
1749				&& this.mOnRosterUpdate == null
1750				&& this.mOnCaptchaRequested == null
1751				&& this.mOnUpdateBlocklist == null
1752				&& this.mOnShowErrorToast == null
1753				&& this.mOnKeyStatusUpdated == null);
1754	}
1755
1756	private void switchToForeground() {
1757		for (Conversation conversation : getConversations()) {
1758			conversation.setIncomingChatState(ChatState.ACTIVE);
1759		}
1760		for (Account account : getAccounts()) {
1761			if (account.getStatus() == Account.State.ONLINE) {
1762				XmppConnection connection = account.getXmppConnection();
1763				if (connection != null && connection.getFeatures().csi()) {
1764					connection.sendActive();
1765				}
1766			}
1767		}
1768		Log.d(Config.LOGTAG, "app switched into foreground");
1769	}
1770
1771	private void switchToBackground() {
1772		for (Account account : getAccounts()) {
1773			if (account.getStatus() == Account.State.ONLINE) {
1774				XmppConnection connection = account.getXmppConnection();
1775				if (connection != null) {
1776					if (connection.getFeatures().csi()) {
1777						connection.sendInactive();
1778					}
1779					if (Config.CLOSE_TCP_WHEN_SWITCHING_TO_BACKGROUND && mPushManagementService.available(account)) {
1780						connection.waitForPush();
1781						cancelWakeUpCall(account.getUuid().hashCode());
1782					}
1783				}
1784			}
1785		}
1786		this.mNotificationService.setIsInForeground(false);
1787		Log.d(Config.LOGTAG, "app switched into background");
1788	}
1789
1790	private void connectMultiModeConversations(Account account) {
1791		List<Conversation> conversations = getConversations();
1792		for (Conversation conversation : conversations) {
1793			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1794				joinMuc(conversation);
1795			}
1796		}
1797	}
1798
1799	public void joinMuc(Conversation conversation) {
1800		joinMuc(conversation, null);
1801	}
1802
1803	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
1804		Account account = conversation.getAccount();
1805		account.pendingConferenceJoins.remove(conversation);
1806		account.pendingConferenceLeaves.remove(conversation);
1807		if (account.getStatus() == Account.State.ONLINE) {
1808			conversation.resetMucOptions();
1809			conversation.setHasMessagesLeftOnServer(false);
1810			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1811
1812				private void join(Conversation conversation) {
1813					Account account = conversation.getAccount();
1814					final MucOptions mucOptions = conversation.getMucOptions();
1815					final Jid joinJid = mucOptions.getSelf().getFullJid();
1816					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1817					PresencePacket packet = new PresencePacket();
1818					packet.setFrom(conversation.getAccount().getJid());
1819					packet.setTo(joinJid);
1820					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1821					if (conversation.getMucOptions().getPassword() != null) {
1822						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1823					}
1824
1825					if (mucOptions.mamSupport()) {
1826						// Use MAM instead of the limited muc history to get history
1827						x.addChild("history").setAttribute("maxchars", "0");
1828					} else {
1829						// Fallback to muc history
1830						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1831					}
1832					String sig = account.getPgpSignature();
1833					if (sig != null) {
1834						packet.addChild("x", "jabber:x:signed").setContent(sig);
1835					}
1836					sendPresencePacket(account, packet);
1837					if (onConferenceJoined != null) {
1838						onConferenceJoined.onConferenceJoined(conversation);
1839					}
1840					if (!joinJid.equals(conversation.getJid())) {
1841						conversation.setContactJid(joinJid);
1842						databaseBackend.updateConversation(conversation);
1843					}
1844
1845					if (mucOptions.mamSupport()) {
1846						getMessageArchiveService().catchupMUC(conversation);
1847					}
1848					if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
1849						fetchConferenceMembers(conversation);
1850					}
1851					sendUnsentMessages(conversation);
1852				}
1853
1854				@Override
1855				public void onConferenceConfigurationFetched(Conversation conversation) {
1856					join(conversation);
1857				}
1858
1859				@Override
1860				public void onFetchFailed(final Conversation conversation, Element error) {
1861					join(conversation);
1862					fetchConferenceConfiguration(conversation);
1863				}
1864			});
1865			updateConversationUi();
1866		} else {
1867			account.pendingConferenceJoins.add(conversation);
1868			conversation.resetMucOptions();
1869			conversation.setHasMessagesLeftOnServer(false);
1870			updateConversationUi();
1871		}
1872	}
1873
1874	private void fetchConferenceMembers(final Conversation conversation) {
1875		final Account account = conversation.getAccount();
1876		final String[] affiliations = {"member","admin","owner"};
1877		OnIqPacketReceived callback = new OnIqPacketReceived() {
1878
1879			private int i = 0;
1880
1881			@Override
1882			public void onIqPacketReceived(Account account, IqPacket packet) {
1883				Element query = packet.query("http://jabber.org/protocol/muc#admin");
1884				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
1885					for(Element child : query.getChildren()) {
1886						if ("item".equals(child.getName())) {
1887							conversation.getMucOptions().putMember(child.getAttributeAsJid("jid"));
1888						}
1889					}
1890				} else {
1891					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
1892				}
1893				++i;
1894				if (i >= affiliations.length) {
1895					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
1896				}
1897			}
1898		};
1899		for(String affiliation : affiliations) {
1900			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
1901		}
1902		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
1903	}
1904
1905	public void providePasswordForMuc(Conversation conversation, String password) {
1906		if (conversation.getMode() == Conversation.MODE_MULTI) {
1907			conversation.getMucOptions().setPassword(password);
1908			if (conversation.getBookmark() != null) {
1909				if (respectAutojoin()) {
1910					conversation.getBookmark().setAutojoin(true);
1911				}
1912				pushBookmarks(conversation.getAccount());
1913			}
1914			databaseBackend.updateConversation(conversation);
1915			joinMuc(conversation);
1916		}
1917	}
1918
1919	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1920		final MucOptions options = conversation.getMucOptions();
1921		final Jid joinJid = options.createJoinJid(nick);
1922		if (options.online()) {
1923			Account account = conversation.getAccount();
1924			options.setOnRenameListener(new OnRenameListener() {
1925
1926				@Override
1927				public void onSuccess() {
1928					conversation.setContactJid(joinJid);
1929					databaseBackend.updateConversation(conversation);
1930					Bookmark bookmark = conversation.getBookmark();
1931					if (bookmark != null) {
1932						bookmark.setNick(nick);
1933						pushBookmarks(bookmark.getAccount());
1934					}
1935					callback.success(conversation);
1936				}
1937
1938				@Override
1939				public void onFailure() {
1940					callback.error(R.string.nick_in_use, conversation);
1941				}
1942			});
1943
1944			PresencePacket packet = new PresencePacket();
1945			packet.setTo(joinJid);
1946			packet.setFrom(conversation.getAccount().getJid());
1947
1948			String sig = account.getPgpSignature();
1949			if (sig != null) {
1950				packet.addChild("status").setContent("online");
1951				packet.addChild("x", "jabber:x:signed").setContent(sig);
1952			}
1953			sendPresencePacket(account, packet);
1954		} else {
1955			conversation.setContactJid(joinJid);
1956			databaseBackend.updateConversation(conversation);
1957			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1958				Bookmark bookmark = conversation.getBookmark();
1959				if (bookmark != null) {
1960					bookmark.setNick(nick);
1961					pushBookmarks(bookmark.getAccount());
1962				}
1963				joinMuc(conversation);
1964			}
1965		}
1966	}
1967
1968	public void leaveMuc(Conversation conversation) {
1969		leaveMuc(conversation, false);
1970	}
1971
1972	private void leaveMuc(Conversation conversation, boolean now) {
1973		Account account = conversation.getAccount();
1974		account.pendingConferenceJoins.remove(conversation);
1975		account.pendingConferenceLeaves.remove(conversation);
1976		if (account.getStatus() == Account.State.ONLINE || now) {
1977			PresencePacket packet = new PresencePacket();
1978			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
1979			packet.setFrom(conversation.getAccount().getJid());
1980			packet.setAttribute("type", "unavailable");
1981			sendPresencePacket(conversation.getAccount(), packet);
1982			conversation.getMucOptions().setOffline();
1983			conversation.deregisterWithBookmark();
1984			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1985					+ ": leaving muc " + conversation.getJid());
1986		} else {
1987			account.pendingConferenceLeaves.add(conversation);
1988		}
1989	}
1990
1991	private String findConferenceServer(final Account account) {
1992		String server;
1993		if (account.getXmppConnection() != null) {
1994			server = account.getXmppConnection().getMucServer();
1995			if (server != null) {
1996				return server;
1997			}
1998		}
1999		for (Account other : getAccounts()) {
2000			if (other != account && other.getXmppConnection() != null) {
2001				server = other.getXmppConnection().getMucServer();
2002				if (server != null) {
2003					return server;
2004				}
2005			}
2006		}
2007		return null;
2008	}
2009
2010	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
2011		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2012		if (account.getStatus() == Account.State.ONLINE) {
2013			try {
2014				String server = findConferenceServer(account);
2015				if (server == null) {
2016					if (callback != null) {
2017						callback.error(R.string.no_conference_server_found, null);
2018					}
2019					return;
2020				}
2021				String name = new BigInteger(75, getRNG()).toString(32);
2022				Jid jid = Jid.fromParts(name, server, null);
2023				final Conversation conversation = findOrCreateConversation(account, jid, true);
2024				joinMuc(conversation, new OnConferenceJoined() {
2025					@Override
2026					public void onConferenceJoined(final Conversation conversation) {
2027						Bundle options = new Bundle();
2028						options.putString("muc#roomconfig_persistentroom", "1");
2029						options.putString("muc#roomconfig_membersonly", "1");
2030						options.putString("muc#roomconfig_publicroom", "0");
2031						options.putString("muc#roomconfig_whois", "anyone");
2032						pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
2033							@Override
2034							public void onPushSucceeded() {
2035								for (Jid invite : jids) {
2036									invite(conversation, invite);
2037								}
2038								if (account.countPresences() > 1) {
2039									directInvite(conversation, account.getJid().toBareJid());
2040								}
2041								if (callback != null) {
2042									callback.success(conversation);
2043								}
2044							}
2045
2046							@Override
2047							public void onPushFailed() {
2048								if (callback != null) {
2049									callback.error(R.string.conference_creation_failed, conversation);
2050								}
2051							}
2052						});
2053					}
2054				});
2055			} catch (InvalidJidException e) {
2056				if (callback != null) {
2057					callback.error(R.string.conference_creation_failed, null);
2058				}
2059			}
2060		} else {
2061			if (callback != null) {
2062				callback.error(R.string.not_connected_try_again, null);
2063			}
2064		}
2065	}
2066
2067	public void fetchConferenceConfiguration(final Conversation conversation) {
2068		fetchConferenceConfiguration(conversation, null);
2069	}
2070
2071	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2072		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2073		request.setTo(conversation.getJid().toBareJid());
2074		request.query("http://jabber.org/protocol/disco#info");
2075		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2076			@Override
2077			public void onIqPacketReceived(Account account, IqPacket packet) {
2078				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2079				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2080					ArrayList<String> features = new ArrayList<>();
2081					for (Element child : query.getChildren()) {
2082						if (child != null && child.getName().equals("feature")) {
2083							String var = child.getAttribute("var");
2084							if (var != null) {
2085								features.add(var);
2086							}
2087						}
2088					}
2089					Element form = query.findChild("x", "jabber:x:data");
2090					if (form != null) {
2091						conversation.getMucOptions().updateFormData(Data.parse(form));
2092					}
2093					conversation.getMucOptions().updateFeatures(features);
2094					if (callback != null) {
2095						callback.onConferenceConfigurationFetched(conversation);
2096					}
2097					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2098					updateConversationUi();
2099				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2100					if (callback != null) {
2101						callback.onFetchFailed(conversation, packet.getError());
2102					}
2103				}
2104			}
2105		});
2106	}
2107
2108	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2109		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2110		request.setTo(conversation.getJid().toBareJid());
2111		request.query("http://jabber.org/protocol/muc#owner");
2112		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2113			@Override
2114			public void onIqPacketReceived(Account account, IqPacket packet) {
2115				if (packet.getType() == IqPacket.TYPE.RESULT) {
2116					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2117					for (Field field : data.getFields()) {
2118						if (options.containsKey(field.getFieldName())) {
2119							field.setValue(options.getString(field.getFieldName()));
2120						}
2121					}
2122					data.submit();
2123					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2124					set.setTo(conversation.getJid().toBareJid());
2125					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2126					sendIqPacket(account, set, new OnIqPacketReceived() {
2127						@Override
2128						public void onIqPacketReceived(Account account, IqPacket packet) {
2129							if (callback != null) {
2130								if (packet.getType() == IqPacket.TYPE.RESULT) {
2131									callback.onPushSucceeded();
2132								} else {
2133									callback.onPushFailed();
2134								}
2135							}
2136						}
2137					});
2138				} else {
2139					if (callback != null) {
2140						callback.onPushFailed();
2141					}
2142				}
2143			}
2144		});
2145	}
2146
2147	public void pushSubjectToConference(final Conversation conference, final String subject) {
2148		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2149		this.sendMessagePacket(conference.getAccount(), packet);
2150		final MucOptions mucOptions = conference.getMucOptions();
2151		final MucOptions.User self = mucOptions.getSelf();
2152		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2153			Bundle options = new Bundle();
2154			options.putString("muc#roomconfig_persistentroom", "1");
2155			this.pushConferenceConfiguration(conference, options, null);
2156		}
2157	}
2158
2159	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2160		final Jid jid = user.toBareJid();
2161		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2162		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2163			@Override
2164			public void onIqPacketReceived(Account account, IqPacket packet) {
2165				if (packet.getType() == IqPacket.TYPE.RESULT) {
2166					callback.onAffiliationChangedSuccessful(jid);
2167				} else {
2168					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2169				}
2170			}
2171		});
2172	}
2173
2174	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2175		List<Jid> jids = new ArrayList<>();
2176		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2177			if (user.getAffiliation() == before && user.getJid() != null) {
2178				jids.add(user.getJid());
2179			}
2180		}
2181		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2182		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2183	}
2184
2185	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2186		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2187		Log.d(Config.LOGTAG, request.toString());
2188		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2189			@Override
2190			public void onIqPacketReceived(Account account, IqPacket packet) {
2191				Log.d(Config.LOGTAG, packet.toString());
2192				if (packet.getType() == IqPacket.TYPE.RESULT) {
2193					callback.onRoleChangedSuccessful(nick);
2194				} else {
2195					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2196				}
2197			}
2198		});
2199	}
2200
2201	private void disconnect(Account account, boolean force) {
2202		if ((account.getStatus() == Account.State.ONLINE)
2203				|| (account.getStatus() == Account.State.DISABLED)) {
2204			if (!force) {
2205				List<Conversation> conversations = getConversations();
2206				for (Conversation conversation : conversations) {
2207					if (conversation.getAccount() == account) {
2208						if (conversation.getMode() == Conversation.MODE_MULTI) {
2209							leaveMuc(conversation, true);
2210						} else {
2211							if (conversation.endOtrIfNeeded()) {
2212								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2213										+ ": ended otr session with "
2214										+ conversation.getJid());
2215							}
2216						}
2217					}
2218				}
2219				sendOfflinePresence(account);
2220			}
2221			account.getXmppConnection().disconnect(force);
2222		}
2223	}
2224
2225	@Override
2226	public IBinder onBind(Intent intent) {
2227		return mBinder;
2228	}
2229
2230	public void updateMessage(Message message) {
2231		databaseBackend.updateMessage(message);
2232		updateConversationUi();
2233	}
2234
2235	public void updateMessage(Message message, String uuid) {
2236		databaseBackend.updateMessage(message, uuid);
2237		updateConversationUi();
2238	}
2239
2240	protected void syncDirtyContacts(Account account) {
2241		for (Contact contact : account.getRoster().getContacts()) {
2242			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2243				pushContactToServer(contact);
2244			}
2245			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2246				deleteContactOnServer(contact);
2247			}
2248		}
2249	}
2250
2251	public void createContact(Contact contact) {
2252		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2253		if (autoGrant) {
2254			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2255			contact.setOption(Contact.Options.ASKING);
2256		}
2257		pushContactToServer(contact);
2258	}
2259
2260	public void onOtrSessionEstablished(Conversation conversation) {
2261		final Account account = conversation.getAccount();
2262		final Session otrSession = conversation.getOtrSession();
2263		Log.d(Config.LOGTAG,
2264				account.getJid().toBareJid() + " otr session established with "
2265						+ conversation.getJid() + "/"
2266						+ otrSession.getSessionID().getUserID());
2267		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2268
2269			@Override
2270			public void onMessageFound(Message message) {
2271				SessionID id = otrSession.getSessionID();
2272				try {
2273					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2274				} catch (InvalidJidException e) {
2275					return;
2276				}
2277				if (message.needsUploading()) {
2278					mJingleConnectionManager.createNewConnection(message);
2279				} else {
2280					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2281					if (outPacket != null) {
2282						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2283						message.setStatus(Message.STATUS_SEND);
2284						databaseBackend.updateMessage(message);
2285						sendMessagePacket(account, outPacket);
2286					}
2287				}
2288				updateConversationUi();
2289			}
2290		});
2291	}
2292
2293	public boolean renewSymmetricKey(Conversation conversation) {
2294		Account account = conversation.getAccount();
2295		byte[] symmetricKey = new byte[32];
2296		this.mRandom.nextBytes(symmetricKey);
2297		Session otrSession = conversation.getOtrSession();
2298		if (otrSession != null) {
2299			MessagePacket packet = new MessagePacket();
2300			packet.setType(MessagePacket.TYPE_CHAT);
2301			packet.setFrom(account.getJid());
2302			MessageGenerator.addMessageHints(packet);
2303			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2304					+ otrSession.getSessionID().getUserID());
2305			try {
2306				packet.setBody(otrSession
2307						.transformSending(CryptoHelper.FILETRANSFER
2308								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2309				sendMessagePacket(account, packet);
2310				conversation.setSymmetricKey(symmetricKey);
2311				return true;
2312			} catch (OtrException e) {
2313				return false;
2314			}
2315		}
2316		return false;
2317	}
2318
2319	public void pushContactToServer(final Contact contact) {
2320		contact.resetOption(Contact.Options.DIRTY_DELETE);
2321		contact.setOption(Contact.Options.DIRTY_PUSH);
2322		final Account account = contact.getAccount();
2323		if (account.getStatus() == Account.State.ONLINE) {
2324			final boolean ask = contact.getOption(Contact.Options.ASKING);
2325			final boolean sendUpdates = contact
2326					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2327					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2328			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2329			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2330			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2331			if (sendUpdates) {
2332				sendPresencePacket(account,
2333						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2334			}
2335			if (ask) {
2336				sendPresencePacket(account,
2337						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2338			}
2339		}
2340	}
2341
2342	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2343		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2344		final int size = Config.AVATAR_SIZE;
2345		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2346		if (avatar != null) {
2347			avatar.height = size;
2348			avatar.width = size;
2349			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2350				avatar.type = "image/webp";
2351			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2352				avatar.type = "image/jpeg";
2353			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2354				avatar.type = "image/png";
2355			}
2356			if (!getFileBackend().save(avatar)) {
2357				callback.error(R.string.error_saving_avatar, avatar);
2358				return;
2359			}
2360			publishAvatar(account, avatar, callback);
2361		} else {
2362			callback.error(R.string.error_publish_avatar_converting, null);
2363		}
2364	}
2365
2366	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2367		final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2368		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2369
2370			@Override
2371			public void onIqPacketReceived(Account account, IqPacket result) {
2372				if (result.getType() == IqPacket.TYPE.RESULT) {
2373					final IqPacket packet = XmppConnectionService.this.mIqGenerator
2374							.publishAvatarMetadata(avatar);
2375					sendIqPacket(account, packet, new OnIqPacketReceived() {
2376						@Override
2377						public void onIqPacketReceived(Account account, IqPacket result) {
2378							if (result.getType() == IqPacket.TYPE.RESULT) {
2379								if (account.setAvatar(avatar.getFilename())) {
2380									getAvatarService().clear(account);
2381									databaseBackend.updateAccount(account);
2382								}
2383								if (callback != null) {
2384									callback.success(avatar);
2385								} else {
2386									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
2387								}
2388							} else {
2389								if (callback != null) {
2390									callback.error(
2391											R.string.error_publish_avatar_server_reject,
2392											avatar);
2393								}
2394							}
2395						}
2396					});
2397				} else {
2398					if (callback != null) {
2399						callback.error(
2400								R.string.error_publish_avatar_server_reject,
2401								avatar);
2402					}
2403				}
2404			}
2405		});
2406	}
2407
2408	public void republishAvatarIfNeeded(Account account) {
2409		if (account.getAxolotlService().isPepBroken()) {
2410			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2411			return;
2412		}
2413		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2414		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2415
2416			private Avatar parseAvatar(IqPacket packet) {
2417				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2418				if (pubsub != null) {
2419					Element items = pubsub.findChild("items");
2420					if (items != null) {
2421						return Avatar.parseMetadata(items);
2422					}
2423				}
2424				return null;
2425			}
2426
2427			private boolean errorIsItemNotFound(IqPacket packet) {
2428				Element error = packet.findChild("error");
2429				return packet.getType() == IqPacket.TYPE.ERROR
2430						&& error != null
2431						&& error.hasChild("item-not-found");
2432			}
2433
2434			@Override
2435			public void onIqPacketReceived(Account account, IqPacket packet) {
2436				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2437					Avatar serverAvatar = parseAvatar(packet);
2438					if (serverAvatar == null && account.getAvatar() != null) {
2439						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2440						if (avatar != null) {
2441							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2442							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2443						} else {
2444							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2445						}
2446					}
2447				}
2448			}
2449		});
2450	}
2451
2452	public void fetchAvatar(Account account, Avatar avatar) {
2453		fetchAvatar(account, avatar, null);
2454	}
2455
2456	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2457		final String KEY = generateFetchKey(account, avatar);
2458		synchronized (this.mInProgressAvatarFetches) {
2459			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2460				switch (avatar.origin) {
2461					case PEP:
2462						this.mInProgressAvatarFetches.add(KEY);
2463						fetchAvatarPep(account, avatar, callback);
2464						break;
2465					case VCARD:
2466						this.mInProgressAvatarFetches.add(KEY);
2467						fetchAvatarVcard(account, avatar, callback);
2468						break;
2469				}
2470			}
2471		}
2472	}
2473
2474	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2475		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2476		sendIqPacket(account, packet, new OnIqPacketReceived() {
2477
2478			@Override
2479			public void onIqPacketReceived(Account account, IqPacket result) {
2480				synchronized (mInProgressAvatarFetches) {
2481					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2482				}
2483				final String ERROR = account.getJid().toBareJid()
2484						+ ": fetching avatar for " + avatar.owner + " failed ";
2485				if (result.getType() == IqPacket.TYPE.RESULT) {
2486					avatar.image = mIqParser.avatarData(result);
2487					if (avatar.image != null) {
2488						if (getFileBackend().save(avatar)) {
2489							if (account.getJid().toBareJid().equals(avatar.owner)) {
2490								if (account.setAvatar(avatar.getFilename())) {
2491									databaseBackend.updateAccount(account);
2492								}
2493								getAvatarService().clear(account);
2494								updateConversationUi();
2495								updateAccountUi();
2496							} else {
2497								Contact contact = account.getRoster()
2498										.getContact(avatar.owner);
2499								contact.setAvatar(avatar);
2500								getAvatarService().clear(contact);
2501								updateConversationUi();
2502								updateRosterUi();
2503							}
2504							if (callback != null) {
2505								callback.success(avatar);
2506							}
2507							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2508									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2509							return;
2510						}
2511					} else {
2512
2513						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2514					}
2515				} else {
2516					Element error = result.findChild("error");
2517					if (error == null) {
2518						Log.d(Config.LOGTAG, ERROR + "(server error)");
2519					} else {
2520						Log.d(Config.LOGTAG, ERROR + error.toString());
2521					}
2522				}
2523				if (callback != null) {
2524					callback.error(0, null);
2525				}
2526
2527			}
2528		});
2529	}
2530
2531	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2532		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2533		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2534			@Override
2535			public void onIqPacketReceived(Account account, IqPacket packet) {
2536				synchronized (mInProgressAvatarFetches) {
2537					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2538				}
2539				if (packet.getType() == IqPacket.TYPE.RESULT) {
2540					Element vCard = packet.findChild("vCard", "vcard-temp");
2541					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2542					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2543					if (image != null) {
2544						avatar.image = image;
2545						if (getFileBackend().save(avatar)) {
2546							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2547									+ ": successfully fetched vCard avatar for " + avatar.owner);
2548							if (avatar.owner.isBareJid()) {
2549								Contact contact = account.getRoster()
2550										.getContact(avatar.owner);
2551								contact.setAvatar(avatar);
2552								getAvatarService().clear(contact);
2553								updateConversationUi();
2554								updateRosterUi();
2555							} else {
2556								Conversation conversation = find(account, avatar.owner.toBareJid());
2557								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2558									MucOptions.User user = conversation.getMucOptions().findUser(avatar.owner.getResourcepart());
2559									if (user != null) {
2560										if (user.setAvatar(avatar)) {
2561											getAvatarService().clear(user);
2562											updateConversationUi();
2563											updateMucRosterUi();
2564										}
2565									}
2566								}
2567							}
2568						}
2569					}
2570				}
2571			}
2572		});
2573	}
2574
2575	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2576		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2577		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2578
2579			@Override
2580			public void onIqPacketReceived(Account account, IqPacket packet) {
2581				if (packet.getType() == IqPacket.TYPE.RESULT) {
2582					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2583					if (pubsub != null) {
2584						Element items = pubsub.findChild("items");
2585						if (items != null) {
2586							Avatar avatar = Avatar.parseMetadata(items);
2587							if (avatar != null) {
2588								avatar.owner = account.getJid().toBareJid();
2589								if (fileBackend.isAvatarCached(avatar)) {
2590									if (account.setAvatar(avatar.getFilename())) {
2591										databaseBackend.updateAccount(account);
2592									}
2593									getAvatarService().clear(account);
2594									callback.success(avatar);
2595								} else {
2596									fetchAvatarPep(account, avatar, callback);
2597								}
2598								return;
2599							}
2600						}
2601					}
2602				}
2603				callback.error(0, null);
2604			}
2605		});
2606	}
2607
2608	public void deleteContactOnServer(Contact contact) {
2609		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2610		contact.resetOption(Contact.Options.DIRTY_PUSH);
2611		contact.setOption(Contact.Options.DIRTY_DELETE);
2612		Account account = contact.getAccount();
2613		if (account.getStatus() == Account.State.ONLINE) {
2614			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2615			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2616			item.setAttribute("jid", contact.getJid().toString());
2617			item.setAttribute("subscription", "remove");
2618			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2619		}
2620	}
2621
2622	public void updateConversation(Conversation conversation) {
2623		this.databaseBackend.updateConversation(conversation);
2624	}
2625
2626	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2627		synchronized (account) {
2628			XmppConnection connection = account.getXmppConnection();
2629			if (connection == null) {
2630				connection = createConnection(account);
2631				account.setXmppConnection(connection);
2632			}
2633			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2634				if (!force) {
2635					disconnect(account, false);
2636				}
2637				Thread thread = new Thread(connection);
2638				connection.setInteractive(interactive);
2639				connection.prepareNewConnection();
2640				thread.start();
2641				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2642			} else {
2643				disconnect(account, force);
2644				account.getRoster().clearPresences();
2645				connection.resetEverything();
2646				account.getAxolotlService().resetBrokenness();
2647			}
2648		}
2649	}
2650
2651	public void reconnectAccountInBackground(final Account account) {
2652		new Thread(new Runnable() {
2653			@Override
2654			public void run() {
2655				reconnectAccount(account, false, true);
2656			}
2657		}).start();
2658	}
2659
2660	public void invite(Conversation conversation, Jid contact) {
2661		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2662		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2663		sendMessagePacket(conversation.getAccount(), packet);
2664	}
2665
2666	public void directInvite(Conversation conversation, Jid jid) {
2667		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2668		sendMessagePacket(conversation.getAccount(), packet);
2669	}
2670
2671	public void resetSendingToWaiting(Account account) {
2672		for (Conversation conversation : getConversations()) {
2673			if (conversation.getAccount() == account) {
2674				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2675
2676					@Override
2677					public void onMessageFound(Message message) {
2678						markMessage(message, Message.STATUS_WAITING);
2679					}
2680				});
2681			}
2682		}
2683	}
2684
2685	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2686		if (uuid == null) {
2687			return null;
2688		}
2689		for (Conversation conversation : getConversations()) {
2690			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2691				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2692				if (message != null) {
2693					markMessage(message, status);
2694				}
2695				return message;
2696			}
2697		}
2698		return null;
2699	}
2700
2701	public boolean markMessage(Conversation conversation, String uuid, int status) {
2702		if (uuid == null) {
2703			return false;
2704		} else {
2705			Message message = conversation.findSentMessageWithUuid(uuid);
2706			if (message != null) {
2707				markMessage(message, status);
2708				return true;
2709			} else {
2710				return false;
2711			}
2712		}
2713	}
2714
2715	public void markMessage(Message message, int status) {
2716		if (status == Message.STATUS_SEND_FAILED
2717				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2718				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2719			return;
2720		}
2721		message.setStatus(status);
2722		databaseBackend.updateMessage(message);
2723		updateConversationUi();
2724	}
2725
2726	public SharedPreferences getPreferences() {
2727		return PreferenceManager
2728				.getDefaultSharedPreferences(getApplicationContext());
2729	}
2730
2731	public boolean confirmMessages() {
2732		return getPreferences().getBoolean("confirm_messages", true);
2733	}
2734
2735	public boolean allowMessageCorrection() {
2736		return getPreferences().getBoolean("allow_message_correction", false);
2737	}
2738
2739	public boolean sendChatStates() {
2740		return getPreferences().getBoolean("chat_states", false);
2741	}
2742
2743	public boolean saveEncryptedMessages() {
2744		return !getPreferences().getBoolean("dont_save_encrypted", false);
2745	}
2746
2747	private boolean respectAutojoin() {
2748		return getPreferences().getBoolean("autojoin", true);
2749	}
2750
2751	public boolean indicateReceived() {
2752		return getPreferences().getBoolean("indicate_received", false);
2753	}
2754
2755	public boolean useTorToConnect() {
2756		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2757	}
2758
2759	public boolean showExtendedConnectionOptions() {
2760		return getPreferences().getBoolean("show_connection_options", false);
2761	}
2762
2763	public int unreadCount() {
2764		int count = 0;
2765		for (Conversation conversation : getConversations()) {
2766			count += conversation.unreadCount();
2767		}
2768		return count;
2769	}
2770
2771
2772	public void showErrorToastInUi(int resId) {
2773		if (mOnShowErrorToast != null) {
2774			mOnShowErrorToast.onShowErrorToast(resId);
2775		}
2776	}
2777
2778	public void updateConversationUi() {
2779		if (mOnConversationUpdate != null) {
2780			mOnConversationUpdate.onConversationUpdate();
2781		}
2782	}
2783
2784	public void updateAccountUi() {
2785		if (mOnAccountUpdate != null) {
2786			mOnAccountUpdate.onAccountUpdate();
2787		}
2788	}
2789
2790	public void updateRosterUi() {
2791		if (mOnRosterUpdate != null) {
2792			mOnRosterUpdate.onRosterUpdate();
2793		}
2794	}
2795
2796	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2797		boolean rc = false;
2798		if (mOnCaptchaRequested != null) {
2799			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2800			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2801					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2802
2803			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2804			rc = true;
2805		}
2806
2807		return rc;
2808	}
2809
2810	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2811		if (mOnUpdateBlocklist != null) {
2812			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2813		}
2814	}
2815
2816	public void updateMucRosterUi() {
2817		if (mOnMucRosterUpdate != null) {
2818			mOnMucRosterUpdate.onMucRosterUpdate();
2819		}
2820	}
2821
2822	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2823		if (mOnKeyStatusUpdated != null) {
2824			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2825		}
2826	}
2827
2828	public Account findAccountByJid(final Jid accountJid) {
2829		for (Account account : this.accounts) {
2830			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2831				return account;
2832			}
2833		}
2834		return null;
2835	}
2836
2837	public Conversation findConversationByUuid(String uuid) {
2838		for (Conversation conversation : getConversations()) {
2839			if (conversation.getUuid().equals(uuid)) {
2840				return conversation;
2841			}
2842		}
2843		return null;
2844	}
2845
2846	public boolean markRead(final Conversation conversation) {
2847		mNotificationService.clear(conversation);
2848		final List<Message> readMessages = conversation.markRead();
2849		if (readMessages.size() > 0) {
2850			Runnable runnable = new Runnable() {
2851				@Override
2852				public void run() {
2853					for (Message message : readMessages) {
2854						databaseBackend.updateMessage(message);
2855					}
2856				}
2857			};
2858			mDatabaseExecutor.execute(runnable);
2859			updateUnreadCountBadge();
2860			return true;
2861		} else {
2862			return false;
2863		}
2864	}
2865
2866	public synchronized void updateUnreadCountBadge() {
2867		int count = unreadCount();
2868		if (unreadCount != count) {
2869			Log.d(Config.LOGTAG, "update unread count to " + count);
2870			if (count > 0) {
2871				ShortcutBadger.applyCount(getApplicationContext(), count);
2872			} else {
2873				ShortcutBadger.removeCount(getApplicationContext());
2874			}
2875			unreadCount = count;
2876		}
2877	}
2878
2879	public void sendReadMarker(final Conversation conversation) {
2880		final Message markable = conversation.getLatestMarkableMessage();
2881		if (this.markRead(conversation)) {
2882			updateConversationUi();
2883		}
2884		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2885			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2886			Account account = conversation.getAccount();
2887			final Jid to = markable.getCounterpart();
2888			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2889			this.sendMessagePacket(conversation.getAccount(), packet);
2890		}
2891	}
2892
2893	public SecureRandom getRNG() {
2894		return this.mRandom;
2895	}
2896
2897	public MemorizingTrustManager getMemorizingTrustManager() {
2898		return this.mMemorizingTrustManager;
2899	}
2900
2901	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2902		this.mMemorizingTrustManager = trustManager;
2903	}
2904
2905	public void updateMemorizingTrustmanager() {
2906		final MemorizingTrustManager tm;
2907		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2908		if (dontTrustSystemCAs) {
2909			tm = new MemorizingTrustManager(getApplicationContext(), null);
2910		} else {
2911			tm = new MemorizingTrustManager(getApplicationContext());
2912		}
2913		setMemorizingTrustManager(tm);
2914	}
2915
2916	public PowerManager getPowerManager() {
2917		return this.pm;
2918	}
2919
2920	public LruCache<String, Bitmap> getBitmapCache() {
2921		return this.mBitmapCache;
2922	}
2923
2924	public void syncRosterToDisk(final Account account) {
2925		Runnable runnable = new Runnable() {
2926
2927			@Override
2928			public void run() {
2929				databaseBackend.writeRoster(account.getRoster());
2930			}
2931		};
2932		mDatabaseExecutor.execute(runnable);
2933
2934	}
2935
2936	public List<String> getKnownHosts() {
2937		final List<String> hosts = new ArrayList<>();
2938		for (final Account account : getAccounts()) {
2939			if (!hosts.contains(account.getServer().toString())) {
2940				hosts.add(account.getServer().toString());
2941			}
2942			for (final Contact contact : account.getRoster().getContacts()) {
2943				if (contact.showInRoster()) {
2944					final String server = contact.getServer().toString();
2945					if (server != null && !hosts.contains(server)) {
2946						hosts.add(server);
2947					}
2948				}
2949			}
2950		}
2951		return hosts;
2952	}
2953
2954	public List<String> getKnownConferenceHosts() {
2955		final ArrayList<String> mucServers = new ArrayList<>();
2956		for (final Account account : accounts) {
2957			if (account.getXmppConnection() != null) {
2958				final String server = account.getXmppConnection().getMucServer();
2959				if (server != null && !mucServers.contains(server)) {
2960					mucServers.add(server);
2961				}
2962			}
2963		}
2964		return mucServers;
2965	}
2966
2967	public void sendMessagePacket(Account account, MessagePacket packet) {
2968		XmppConnection connection = account.getXmppConnection();
2969		if (connection != null) {
2970			connection.sendMessagePacket(packet);
2971		}
2972	}
2973
2974	public void sendPresencePacket(Account account, PresencePacket packet) {
2975		XmppConnection connection = account.getXmppConnection();
2976		if (connection != null) {
2977			connection.sendPresencePacket(packet);
2978		}
2979	}
2980
2981	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2982		XmppConnection connection = account.getXmppConnection();
2983		if (connection != null) {
2984			connection.sendCaptchaRegistryRequest(id, data);
2985		}
2986	}
2987
2988	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2989		final XmppConnection connection = account.getXmppConnection();
2990		if (connection != null) {
2991			connection.sendIqPacket(packet, callback);
2992		}
2993	}
2994
2995	public void sendPresence(final Account account) {
2996		sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2997	}
2998
2999	public void refreshAllPresences() {
3000		for (Account account : getAccounts()) {
3001			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3002				sendPresence(account);
3003			}
3004		}
3005	}
3006
3007	private void refreshAllGcmTokens() {
3008		for(Account account : getAccounts()) {
3009			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3010				mPushManagementService.registerPushTokenOnServer(account);
3011			}
3012		}
3013	}
3014
3015	public void sendOfflinePresence(final Account account) {
3016		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3017	}
3018
3019	public MessageGenerator getMessageGenerator() {
3020		return this.mMessageGenerator;
3021	}
3022
3023	public PresenceGenerator getPresenceGenerator() {
3024		return this.mPresenceGenerator;
3025	}
3026
3027	public IqGenerator getIqGenerator() {
3028		return this.mIqGenerator;
3029	}
3030
3031	public IqParser getIqParser() {
3032		return this.mIqParser;
3033	}
3034
3035	public JingleConnectionManager getJingleConnectionManager() {
3036		return this.mJingleConnectionManager;
3037	}
3038
3039	public MessageArchiveService getMessageArchiveService() {
3040		return this.mMessageArchiveService;
3041	}
3042
3043	public List<Contact> findContacts(Jid jid) {
3044		ArrayList<Contact> contacts = new ArrayList<>();
3045		for (Account account : getAccounts()) {
3046			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3047				Contact contact = account.getRoster().getContactFromRoster(jid);
3048				if (contact != null) {
3049					contacts.add(contact);
3050				}
3051			}
3052		}
3053		return contacts;
3054	}
3055
3056	public NotificationService getNotificationService() {
3057		return this.mNotificationService;
3058	}
3059
3060	public HttpConnectionManager getHttpConnectionManager() {
3061		return this.mHttpConnectionManager;
3062	}
3063
3064	public void resendFailedMessages(final Message message) {
3065		final Collection<Message> messages = new ArrayList<>();
3066		Message current = message;
3067		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3068			messages.add(current);
3069			if (current.mergeable(current.next())) {
3070				current = current.next();
3071			} else {
3072				break;
3073			}
3074		}
3075		for (final Message msg : messages) {
3076			msg.setTime(System.currentTimeMillis());
3077			markMessage(msg, Message.STATUS_WAITING);
3078			this.resendMessage(msg, false);
3079		}
3080	}
3081
3082	public void clearConversationHistory(final Conversation conversation) {
3083		conversation.clearMessages();
3084		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3085		conversation.setLastClearHistory(System.currentTimeMillis());
3086		Runnable runnable = new Runnable() {
3087			@Override
3088			public void run() {
3089				databaseBackend.deleteMessagesInConversation(conversation);
3090			}
3091		};
3092		mDatabaseExecutor.execute(runnable);
3093	}
3094
3095	public void sendBlockRequest(final Blockable blockable) {
3096		if (blockable != null && blockable.getBlockedJid() != null) {
3097			final Jid jid = blockable.getBlockedJid();
3098			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
3099
3100				@Override
3101				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3102					if (packet.getType() == IqPacket.TYPE.RESULT) {
3103						account.getBlocklist().add(jid);
3104						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3105					}
3106				}
3107			});
3108		}
3109	}
3110
3111	public void sendUnblockRequest(final Blockable blockable) {
3112		if (blockable != null && blockable.getJid() != null) {
3113			final Jid jid = blockable.getBlockedJid();
3114			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3115				@Override
3116				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3117					if (packet.getType() == IqPacket.TYPE.RESULT) {
3118						account.getBlocklist().remove(jid);
3119						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3120					}
3121				}
3122			});
3123		}
3124	}
3125
3126	public void publishDisplayName(Account account) {
3127		String displayName = account.getDisplayName();
3128		if (displayName != null && !displayName.isEmpty()) {
3129			IqPacket publish = mIqGenerator.publishNick(displayName);
3130			sendIqPacket(account, publish, new OnIqPacketReceived() {
3131				@Override
3132				public void onIqPacketReceived(Account account, IqPacket packet) {
3133					if (packet.getType() == IqPacket.TYPE.ERROR) {
3134						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3135					}
3136				}
3137			});
3138		}
3139	}
3140
3141	private ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String,String> key) {
3142		ServiceDiscoveryResult result = discoCache.get(key);
3143		if (result != null) {
3144			return result;
3145		} else {
3146			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3147			if (result != null) {
3148				discoCache.put(key, result);
3149			}
3150			return result;
3151		}
3152	}
3153
3154	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3155		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3156		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3157		if (disco != null) {
3158			presence.setServiceDiscoveryResult(disco);
3159		} else {
3160			if (!account.inProgressDiscoFetches.contains(key)) {
3161				account.inProgressDiscoFetches.add(key);
3162				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3163				request.setTo(jid);
3164				request.query("http://jabber.org/protocol/disco#info");
3165				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3166				sendIqPacket(account, request, new OnIqPacketReceived() {
3167					@Override
3168					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3169						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3170							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3171							if (presence.getVer().equals(disco.getVer())) {
3172								databaseBackend.insertDiscoveryResult(disco);
3173								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3174							} else {
3175								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3176							}
3177						}
3178						account.inProgressDiscoFetches.remove(key);
3179					}
3180				});
3181			}
3182		}
3183	}
3184
3185	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3186		for(Contact contact : roster.getContacts()) {
3187			for(Presence presence : contact.getPresences().getPresences().values()) {
3188				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3189					presence.setServiceDiscoveryResult(disco);
3190				}
3191			}
3192		}
3193	}
3194
3195	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3196		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3197		request.addChild("prefs","urn:xmpp:mam:0");
3198		sendIqPacket(account, request, new OnIqPacketReceived() {
3199			@Override
3200			public void onIqPacketReceived(Account account, IqPacket packet) {
3201				Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3202				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3203					callback.onPreferencesFetched(prefs);
3204				} else {
3205					callback.onPreferencesFetchFailed();
3206				}
3207			}
3208		});
3209	}
3210
3211	public PushManagementService getPushManagementService() {
3212		return mPushManagementService;
3213	}
3214
3215	public interface OnMamPreferencesFetched {
3216		void onPreferencesFetched(Element prefs);
3217		void onPreferencesFetchFailed();
3218	}
3219
3220	public void pushMamPreferences(Account account, Element prefs) {
3221		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3222		set.addChild(prefs);
3223		sendIqPacket(account, set, null);
3224	}
3225
3226	public interface OnAccountCreated {
3227		void onAccountCreated(Account account);
3228
3229		void informUser(int r);
3230	}
3231
3232	public interface OnMoreMessagesLoaded {
3233		void onMoreMessagesLoaded(int count, Conversation conversation);
3234
3235		void informUser(int r);
3236	}
3237
3238	public interface OnAccountPasswordChanged {
3239		void onPasswordChangeSucceeded();
3240
3241		void onPasswordChangeFailed();
3242	}
3243
3244	public interface OnAffiliationChanged {
3245		void onAffiliationChangedSuccessful(Jid jid);
3246
3247		void onAffiliationChangeFailed(Jid jid, int resId);
3248	}
3249
3250	public interface OnRoleChanged {
3251		void onRoleChangedSuccessful(String nick);
3252
3253		void onRoleChangeFailed(String nick, int resid);
3254	}
3255
3256	public interface OnConversationUpdate {
3257		void onConversationUpdate();
3258	}
3259
3260	public interface OnAccountUpdate {
3261		void onAccountUpdate();
3262	}
3263
3264	public interface OnCaptchaRequested {
3265		void onCaptchaRequested(Account account,
3266								String id,
3267								Data data,
3268								Bitmap captcha);
3269	}
3270
3271	public interface OnRosterUpdate {
3272		void onRosterUpdate();
3273	}
3274
3275	public interface OnMucRosterUpdate {
3276		void onMucRosterUpdate();
3277	}
3278
3279	public interface OnConferenceConfigurationFetched {
3280		void onConferenceConfigurationFetched(Conversation conversation);
3281
3282		void onFetchFailed(Conversation conversation, Element error);
3283	}
3284
3285	public interface OnConferenceJoined {
3286		void onConferenceJoined(Conversation conversation);
3287	}
3288
3289	public interface OnConferenceOptionsPushed {
3290		void onPushSucceeded();
3291
3292		void onPushFailed();
3293	}
3294
3295	public interface OnShowErrorToast {
3296		void onShowErrorToast(int resId);
3297	}
3298
3299	public class XmppConnectionBinder extends Binder {
3300		public XmppConnectionService getService() {
3301			return XmppConnectionService.this;
3302		}
3303	}
3304}