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