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