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