XmppConnectionService.java

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