XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.annotation.SuppressLint;
   4import android.annotation.TargetApi;
   5import android.app.AlarmManager;
   6import android.app.PendingIntent;
   7import android.app.Service;
   8import android.content.Context;
   9import android.content.Intent;
  10import android.content.IntentFilter;
  11import android.content.SharedPreferences;
  12import android.database.ContentObserver;
  13import android.graphics.Bitmap;
  14import android.media.AudioManager;
  15import android.net.ConnectivityManager;
  16import android.net.NetworkInfo;
  17import android.net.Uri;
  18import android.os.Binder;
  19import android.os.Build;
  20import android.os.Bundle;
  21import android.os.Environment;
  22import android.os.IBinder;
  23import android.os.ParcelFileDescriptor;
  24import android.os.PowerManager;
  25import android.os.PowerManager.WakeLock;
  26import android.os.SystemClock;
  27import android.preference.PreferenceManager;
  28import android.provider.ContactsContract;
  29import android.security.KeyChain;
  30import android.support.v4.app.RemoteInput;
  31import android.util.DisplayMetrics;
  32import android.util.Log;
  33import android.util.LruCache;
  34import android.util.Pair;
  35
  36import net.java.otr4j.OtrException;
  37import net.java.otr4j.session.Session;
  38import net.java.otr4j.session.SessionID;
  39import net.java.otr4j.session.SessionImpl;
  40import net.java.otr4j.session.SessionStatus;
  41import net.ypresto.androidtranscoder.MediaTranscoder;
  42import net.ypresto.androidtranscoder.format.MediaFormatStrategyPresets;
  43
  44import org.openintents.openpgp.IOpenPgpService2;
  45import org.openintents.openpgp.util.OpenPgpApi;
  46import org.openintents.openpgp.util.OpenPgpServiceConnection;
  47
  48import java.io.FileDescriptor;
  49import java.io.FileNotFoundException;
  50import java.math.BigInteger;
  51import java.net.URL;
  52import java.security.SecureRandom;
  53import java.security.cert.CertificateException;
  54import java.security.cert.X509Certificate;
  55import java.util.ArrayList;
  56import java.util.Arrays;
  57import java.util.Collection;
  58import java.util.Collections;
  59import java.util.HashMap;
  60import java.util.HashSet;
  61import java.util.Hashtable;
  62import java.util.Iterator;
  63import java.util.List;
  64import java.util.ListIterator;
  65import java.util.Locale;
  66import java.util.Map;
  67import java.util.concurrent.CopyOnWriteArrayList;
  68import java.util.concurrent.ExecutionException;
  69import java.util.concurrent.atomic.AtomicLong;
  70
  71import de.duenndns.ssl.MemorizingTrustManager;
  72import eu.siacs.conversations.Config;
  73import eu.siacs.conversations.R;
  74import eu.siacs.conversations.crypto.PgpDecryptionService;
  75import eu.siacs.conversations.crypto.PgpEngine;
  76import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  77import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  78import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  79import eu.siacs.conversations.entities.Account;
  80import eu.siacs.conversations.entities.Blockable;
  81import eu.siacs.conversations.entities.Bookmark;
  82import eu.siacs.conversations.entities.Contact;
  83import eu.siacs.conversations.entities.Conversation;
  84import eu.siacs.conversations.entities.DownloadableFile;
  85import eu.siacs.conversations.entities.Message;
  86import eu.siacs.conversations.entities.MucOptions;
  87import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  88import eu.siacs.conversations.entities.Presence;
  89import eu.siacs.conversations.entities.PresenceTemplate;
  90import eu.siacs.conversations.entities.Roster;
  91import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  92import eu.siacs.conversations.entities.Transferable;
  93import eu.siacs.conversations.entities.TransferablePlaceholder;
  94import eu.siacs.conversations.generator.AbstractGenerator;
  95import eu.siacs.conversations.generator.IqGenerator;
  96import eu.siacs.conversations.generator.MessageGenerator;
  97import eu.siacs.conversations.generator.PresenceGenerator;
  98import eu.siacs.conversations.http.HttpConnectionManager;
  99import eu.siacs.conversations.http.OmemoURLStreamHandlerFactory;
 100import eu.siacs.conversations.parser.AbstractParser;
 101import eu.siacs.conversations.parser.IqParser;
 102import eu.siacs.conversations.parser.MessageParser;
 103import eu.siacs.conversations.parser.PresenceParser;
 104import eu.siacs.conversations.persistance.DatabaseBackend;
 105import eu.siacs.conversations.persistance.FileBackend;
 106import eu.siacs.conversations.ui.SettingsActivity;
 107import eu.siacs.conversations.ui.UiCallback;
 108import eu.siacs.conversations.ui.UiInformableCallback;
 109import eu.siacs.conversations.utils.ConversationsFileObserver;
 110import eu.siacs.conversations.utils.CryptoHelper;
 111import eu.siacs.conversations.utils.ExceptionHelper;
 112import eu.siacs.conversations.utils.MimeUtils;
 113import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
 114import eu.siacs.conversations.utils.PRNGFixes;
 115import eu.siacs.conversations.utils.PhoneHelper;
 116import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
 117import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 118import eu.siacs.conversations.utils.Xmlns;
 119import eu.siacs.conversations.utils.XmppUri;
 120import eu.siacs.conversations.xml.Element;
 121import eu.siacs.conversations.xmpp.OnBindListener;
 122import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 123import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 124import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 125import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
 126import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 127import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 128import eu.siacs.conversations.xmpp.OnStatusChanged;
 129import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 130import eu.siacs.conversations.xmpp.XmppConnection;
 131import eu.siacs.conversations.xmpp.chatstate.ChatState;
 132import eu.siacs.conversations.xmpp.forms.Data;
 133import eu.siacs.conversations.xmpp.forms.Field;
 134import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 135import eu.siacs.conversations.xmpp.jid.Jid;
 136import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 137import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 138import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 139import eu.siacs.conversations.xmpp.pep.Avatar;
 140import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 141import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 142import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 143import me.leolin.shortcutbadger.ShortcutBadger;
 144
 145public class XmppConnectionService extends Service {
 146
 147	static {
 148		URL.setURLStreamHandlerFactory(new OmemoURLStreamHandlerFactory());
 149	}
 150
 151	public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
 152	public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 153	public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
 154	public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
 155	public static final String ACTION_TRY_AGAIN = "try_again";
 156	public static final String ACTION_IDLE_PING = "idle_ping";
 157	private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
 158	public static final String ACTION_GCM_TOKEN_REFRESH = "gcm_token_refresh";
 159	public static final String ACTION_GCM_MESSAGE_RECEIVED = "gcm_message_received";
 160	private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
 161	private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
 162	private ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor(true);
 163	private final IBinder mBinder = new XmppConnectionBinder();
 164	private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 165	private final IqGenerator mIqGenerator = new IqGenerator(this);
 166	private final List<String> mInProgressAvatarFetches = new ArrayList<>();
 167	private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
 168
 169	private long mLastActivity = 0;
 170
 171	public DatabaseBackend databaseBackend;
 172	private ContentObserver contactObserver = new ContentObserver(null) {
 173		@Override
 174		public void onChange(boolean selfChange) {
 175			super.onChange(selfChange);
 176			Intent intent = new Intent(getApplicationContext(),
 177					XmppConnectionService.class);
 178			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 179			startService(intent);
 180		}
 181	};
 182	private FileBackend fileBackend = new FileBackend(this);
 183	private MemorizingTrustManager mMemorizingTrustManager;
 184	private NotificationService mNotificationService = new NotificationService(
 185			this);
 186	private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 187	private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 188	private IqParser mIqParser = new IqParser(this);
 189	private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
 190		@Override
 191		public void onIqPacketReceived(Account account, IqPacket packet) {
 192			if (packet.getType() != IqPacket.TYPE.RESULT) {
 193				Element error = packet.findChild("error");
 194				String text = error != null ? error.findChildContent("text") : null;
 195				if (text != null) {
 196					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
 197				}
 198			}
 199		}
 200	};
 201	private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 202	private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 203	private List<Account> accounts;
 204	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 205			this);
 206	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
 207
 208		@Override
 209		public void onContactStatusChanged(Contact contact, boolean online) {
 210			Conversation conversation = find(getConversations(), contact);
 211			if (conversation != null) {
 212				if (online) {
 213					conversation.endOtrIfNeeded();
 214					if (contact.getPresences().size() == 1) {
 215						sendUnsentMessages(conversation);
 216					}
 217				} else {
 218					//check if the resource we are haveing a conversation with is still online
 219					if (conversation.hasValidOtrSession()) {
 220						String otrResource = conversation.getOtrSession().getSessionID().getUserID();
 221						if (!(Arrays.asList(contact.getPresences().toResourceArray()).contains(otrResource))) {
 222							conversation.endOtrIfNeeded();
 223						}
 224					}
 225				}
 226			}
 227		}
 228	};
 229	private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 230			this);
 231	private AvatarService mAvatarService = new AvatarService(this);
 232	private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 233	private PushManagementService mPushManagementService = new PushManagementService(this);
 234	private OnConversationUpdate mOnConversationUpdate = null;
 235
 236
 237	private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
 238			Environment.getExternalStorageDirectory().getAbsolutePath()
 239	) {
 240		@Override
 241		public void onEvent(int event, String path) {
 242			markFileDeleted(path);
 243		}
 244	};
 245	private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 246
 247		@Override
 248		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 249			mJingleConnectionManager.deliverPacket(account, packet);
 250		}
 251	};
 252	private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 253
 254		@Override
 255		public void onMessageAcknowledged(Account account, String uuid) {
 256			for (final Conversation conversation : getConversations()) {
 257				if (conversation.getAccount() == account) {
 258					Message message = conversation.findUnsentMessageWithUuid(uuid);
 259					if (message != null) {
 260						markMessage(message, Message.STATUS_SEND);
 261					}
 262				}
 263			}
 264		}
 265	};
 266	private int convChangedListenerCount = 0;
 267	private OnShowErrorToast mOnShowErrorToast = null;
 268	private int showErrorToastListenerCount = 0;
 269	private int unreadCount = -1;
 270	private OnAccountUpdate mOnAccountUpdate = null;
 271	private OnCaptchaRequested mOnCaptchaRequested = null;
 272	private int accountChangedListenerCount = 0;
 273	private int captchaRequestedListenerCount = 0;
 274	private OnRosterUpdate mOnRosterUpdate = null;
 275	private OnUpdateBlocklist mOnUpdateBlocklist = null;
 276	private int updateBlocklistListenerCount = 0;
 277	private int rosterChangedListenerCount = 0;
 278	private OnMucRosterUpdate mOnMucRosterUpdate = null;
 279	private int mucRosterChangedListenerCount = 0;
 280	private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
 281	private int keyStatusUpdatedListenerCount = 0;
 282	private AtomicLong mLastExpiryRun = new AtomicLong(0);
 283	private SecureRandom mRandom;
 284	private LruCache<Pair<String,String>,ServiceDiscoveryResult> discoCache = new LruCache<>(20);
 285	private final OnBindListener mOnBindListener = new OnBindListener() {
 286
 287		@Override
 288		public void onBind(final Account account) {
 289			synchronized (mInProgressAvatarFetches) {
 290				for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
 291					final String KEY = iterator.next();
 292					if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
 293						iterator.remove();
 294					}
 295				}
 296			}
 297			account.getRoster().clearPresences();
 298			mJingleConnectionManager.cancelInTransmission();
 299			fetchRosterFromServer(account);
 300			fetchBookmarks(account);
 301			sendPresence(account);
 302			if (mPushManagementService.available(account)) {
 303				mPushManagementService.registerPushTokenOnServer(account);
 304			}
 305			connectMultiModeConversations(account);
 306			syncDirtyContacts(account);
 307		}
 308	};
 309	private OnStatusChanged statusListener = new OnStatusChanged() {
 310
 311		@Override
 312		public void onStatusChanged(final Account account) {
 313			XmppConnection connection = account.getXmppConnection();
 314			if (mOnAccountUpdate != null) {
 315				mOnAccountUpdate.onAccountUpdate();
 316			}
 317			if (account.getStatus() == Account.State.ONLINE) {
 318				synchronized (mLowPingTimeoutMode) {
 319					if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) {
 320						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode");
 321					}
 322				}
 323				if (account.setShowErrorNotification(true)) {
 324					databaseBackend.updateAccount(account);
 325				}
 326				mMessageArchiveService.executePendingQueries(account);
 327				if (connection != null && connection.getFeatures().csi()) {
 328					if (checkListeners()) {
 329						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
 330						connection.sendInactive();
 331					} else {
 332						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
 333						connection.sendActive();
 334					}
 335				}
 336				List<Conversation> conversations = getConversations();
 337				for (Conversation conversation : conversations) {
 338					if (conversation.getAccount() == account
 339							&& !account.pendingConferenceJoins.contains(conversation)) {
 340						if (!conversation.startOtrIfNeeded()) {
 341							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": couldn't start OTR with "+conversation.getContact().getJid()+" when needed");
 342						}
 343						sendUnsentMessages(conversation);
 344					}
 345				}
 346				for (Conversation conversation : account.pendingConferenceLeaves) {
 347					leaveMuc(conversation);
 348				}
 349				account.pendingConferenceLeaves.clear();
 350				for (Conversation conversation : account.pendingConferenceJoins) {
 351					joinMuc(conversation);
 352				}
 353				account.pendingConferenceJoins.clear();
 354				scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 355			} else {
 356				if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
 357					resetSendingToWaiting(account);
 358					if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 359						synchronized (mLowPingTimeoutMode) {
 360							if (mLowPingTimeoutMode.contains(account.getJid().toBareJid())) {
 361								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": went into offline state during low ping mode. reconnecting now");
 362								reconnectAccount(account, true, false);
 363							} else {
 364								int timeToReconnect = mRandom.nextInt(10) + 2;
 365								scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 366							}
 367						}
 368					}
 369				} else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 370					databaseBackend.updateAccount(account);
 371					reconnectAccount(account, true, false);
 372				} else if ((account.getStatus() != Account.State.CONNECTING)
 373						&& (account.getStatus() != Account.State.NO_INTERNET)) {
 374					resetSendingToWaiting(account);
 375					if (connection != null) {
 376						int next = connection.getTimeToNextAttempt();
 377						Log.d(Config.LOGTAG, account.getJid().toBareJid()
 378								+ ": error connecting account. try again in "
 379								+ next + "s for the "
 380								+ (connection.getAttempt() + 1) + " time");
 381						scheduleWakeUpCall(next, account.getUuid().hashCode());
 382					}
 383				}
 384			}
 385			getNotificationService().updateErrorNotification();
 386		}
 387	};
 388	private OpenPgpServiceConnection pgpServiceConnection;
 389	private PgpEngine mPgpEngine = null;
 390	private WakeLock wakeLock;
 391	private PowerManager pm;
 392	private LruCache<String, Bitmap> mBitmapCache;
 393	private EventReceiver mEventReceiver = new EventReceiver();
 394
 395	private boolean mRestoredFromDatabase = false;
 396
 397	private static String generateFetchKey(Account account, final Avatar avatar) {
 398		return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 399	}
 400
 401	public boolean areMessagesInitialized() {
 402		return this.mRestoredFromDatabase;
 403	}
 404
 405	public PgpEngine getPgpEngine() {
 406		if (!Config.supportOpenPgp()) {
 407			return null;
 408		} else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 409			if (this.mPgpEngine == null) {
 410				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 411						getApplicationContext(),
 412						pgpServiceConnection.getService()), this);
 413			}
 414			return mPgpEngine;
 415		} else {
 416			return null;
 417		}
 418
 419	}
 420
 421	public OpenPgpApi getOpenPgpApi() {
 422		if (!Config.supportOpenPgp()) {
 423			return null;
 424		} else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 425			return new OpenPgpApi(this, pgpServiceConnection.getService());
 426		} else {
 427			return null;
 428		}
 429	}
 430
 431	public FileBackend getFileBackend() {
 432		return this.fileBackend;
 433	}
 434
 435	public AvatarService getAvatarService() {
 436		return this.mAvatarService;
 437	}
 438
 439	public void attachLocationToConversation(final Conversation conversation,
 440											 final Uri uri,
 441											 final UiCallback<Message> callback) {
 442		int encryption = conversation.getNextEncryption();
 443		if (encryption == Message.ENCRYPTION_PGP) {
 444			encryption = Message.ENCRYPTION_DECRYPTED;
 445		}
 446		Message message = new Message(conversation, uri.toString(), encryption);
 447		if (conversation.getNextCounterpart() != null) {
 448			message.setCounterpart(conversation.getNextCounterpart());
 449		}
 450		if (encryption == Message.ENCRYPTION_DECRYPTED) {
 451			getPgpEngine().encrypt(message, callback);
 452		} else {
 453			callback.success(message);
 454		}
 455	}
 456
 457	public void attachFileToConversation(final Conversation conversation,
 458										 final Uri uri,
 459										 final UiCallback<Message> callback) {
 460		if (FileBackend.weOwnFile(this, uri)) {
 461			Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
 462			callback.error(R.string.security_error_invalid_file_access, null);
 463			return;
 464		}
 465		final Message message;
 466		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 467			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 468		} else {
 469			message = new Message(conversation, "", conversation.getNextEncryption());
 470		}
 471		message.setCounterpart(conversation.getNextCounterpart());
 472		message.setType(Message.TYPE_FILE);
 473		mFileAddingExecutor.execute(new Runnable() {
 474
 475			private void processAsFile() {
 476				final String path = getFileBackend().getOriginalPath(uri);
 477				if (path != null) {
 478					message.setRelativeFilePath(path);
 479					getFileBackend().updateFileParams(message);
 480					if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 481						getPgpEngine().encrypt(message, callback);
 482					} else {
 483						callback.success(message);
 484					}
 485				} else {
 486					try {
 487						getFileBackend().copyFileToPrivateStorage(message, uri);
 488						getFileBackend().updateFileParams(message);
 489						if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 490							final PgpEngine pgpEngine = getPgpEngine();
 491							if (pgpEngine != null) {
 492								pgpEngine.encrypt(message, callback);
 493							} else if (callback != null) {
 494								callback.error(R.string.unable_to_connect_to_keychain, null);
 495							}
 496						} else {
 497							callback.success(message);
 498						}
 499					} catch (FileBackend.FileCopyException e) {
 500						callback.error(e.getResId(), message);
 501					}
 502				}
 503			}
 504
 505			private void processAsVideo() throws FileNotFoundException {
 506				Log.d(Config.LOGTAG,"processing file as video");
 507				message.setRelativeFilePath(message.getUuid() + ".mp4");
 508				final DownloadableFile file = getFileBackend().getFile(message);
 509				file.getParentFile().mkdirs();
 510				ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
 511				FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
 512				final ArrayList<Integer> progressTracker = new ArrayList<>();
 513				final UiInformableCallback<Message> informableCallback;
 514				if (callback instanceof UiInformableCallback) {
 515					informableCallback = (UiInformableCallback<Message>) callback;
 516				} else {
 517					informableCallback = null;
 518				}
 519				MediaTranscoder.Listener listener = new MediaTranscoder.Listener() {
 520					@Override
 521					public void onTranscodeProgress(double progress) {
 522						int p = ((int) Math.round(progress * 100) / 20) * 20;
 523						if (!progressTracker.contains(p) && p != 100 && p != 0) {
 524							progressTracker.add(p);
 525							if (informableCallback != null) {
 526
 527								informableCallback.inform(getString(R.string.transcoding_video_progress, p));
 528							}
 529						}
 530					}
 531
 532					@Override
 533					public void onTranscodeCompleted() {
 534						if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 535							getPgpEngine().encrypt(message, callback);
 536						} else {
 537							callback.success(message);
 538						}
 539					}
 540
 541					@Override
 542					public void onTranscodeCanceled() {
 543						processAsFile();
 544					}
 545
 546					@Override
 547					public void onTranscodeFailed(Exception e) {
 548						Log.d(Config.LOGTAG,"video transcoding failed "+e.getMessage());
 549						processAsFile();
 550					}
 551				};
 552				MediaTranscoder.getInstance().transcodeVideo(fileDescriptor, file.getAbsolutePath(),
 553						MediaFormatStrategyPresets.createAndroid720pStrategy(), listener);
 554			}
 555
 556			@Override
 557			public void run() {
 558				final String mimeType = MimeUtils.guessMimeTypeFromUri(XmppConnectionService.this, uri);
 559				if (mimeType != null && mimeType.startsWith("video/") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 560					try {
 561						processAsVideo();
 562					} catch (Throwable e) {
 563						processAsFile();
 564					}
 565				} else {
 566					processAsFile();
 567				}
 568
 569			}
 570		});
 571	}
 572
 573	public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 574		if (FileBackend.weOwnFile(this, uri)) {
 575			Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
 576			callback.error(R.string.security_error_invalid_file_access, null);
 577			return;
 578		}
 579
 580		final String mimeType = MimeUtils.guessMimeTypeFromUri(this, uri);
 581		final String compressPictures = getCompressPicturesPreference();
 582
 583		if ("never".equals(compressPictures)
 584				|| ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
 585				|| (mimeType != null && mimeType.endsWith("/gif"))) {
 586			Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+ ": not compressing picture. sending as file");
 587			attachFileToConversation(conversation, uri, callback);
 588			return;
 589		}
 590		final Message message;
 591		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 592			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 593		} else {
 594			message = new Message(conversation, "", conversation.getNextEncryption());
 595		}
 596		message.setCounterpart(conversation.getNextCounterpart());
 597		message.setType(Message.TYPE_IMAGE);
 598		mFileAddingExecutor.execute(new Runnable() {
 599
 600			@Override
 601			public void run() {
 602				try {
 603					getFileBackend().copyImageToPrivateStorage(message, uri);
 604					if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 605						final PgpEngine pgpEngine = getPgpEngine();
 606						if (pgpEngine != null) {
 607							pgpEngine.encrypt(message, callback);
 608						} else if (callback != null){
 609							callback.error(R.string.unable_to_connect_to_keychain, null);
 610						}
 611					} else {
 612						callback.success(message);
 613					}
 614				} catch (final FileBackend.FileCopyException e) {
 615					callback.error(e.getResId(), message);
 616				}
 617			}
 618		});
 619	}
 620
 621	public Conversation find(Bookmark bookmark) {
 622		return find(bookmark.getAccount(), bookmark.getJid());
 623	}
 624
 625	public Conversation find(final Account account, final Jid jid) {
 626		return find(getConversations(), account, jid);
 627	}
 628
 629	@Override
 630	public int onStartCommand(Intent intent, int flags, int startId) {
 631		final String action = intent == null ? null : intent.getAction();
 632		String pushedAccountHash = null;
 633		boolean interactive = false;
 634		if (action != null) {
 635			final Conversation c = findConversationByUuid(intent.getStringExtra("uuid"));
 636			switch (action) {
 637				case ConnectivityManager.CONNECTIVITY_ACTION:
 638					if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 639						resetAllAttemptCounts(true, false);
 640					}
 641					break;
 642				case ACTION_MERGE_PHONE_CONTACTS:
 643					if (mRestoredFromDatabase) {
 644						loadPhoneContacts();
 645					}
 646					return START_STICKY;
 647				case Intent.ACTION_SHUTDOWN:
 648					logoutAndSave(true);
 649					return START_NOT_STICKY;
 650				case ACTION_CLEAR_NOTIFICATION:
 651					if (c != null) {
 652						mNotificationService.clear(c);
 653					} else {
 654						mNotificationService.clear();
 655					}
 656					break;
 657				case ACTION_DISABLE_FOREGROUND:
 658					getPreferences().edit().putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, false).commit();
 659					toggleForegroundService();
 660					break;
 661				case ACTION_DISMISS_ERROR_NOTIFICATIONS:
 662					dismissErrorNotifications();
 663					break;
 664				case ACTION_TRY_AGAIN:
 665					resetAllAttemptCounts(false, true);
 666					interactive = true;
 667					break;
 668				case ACTION_REPLY_TO_CONVERSATION:
 669					Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
 670					if (remoteInput != null && c != null) {
 671						final CharSequence body = remoteInput.getCharSequence("text_reply");
 672						if (body != null && body.length() > 0) {
 673							directReply(c, body.toString(),intent.getBooleanExtra("dismiss_notification",false));
 674						}
 675					}
 676					break;
 677				case AudioManager.RINGER_MODE_CHANGED_ACTION:
 678					if (xaOnSilentMode()) {
 679						refreshAllPresences();
 680					}
 681					break;
 682				case Intent.ACTION_SCREEN_ON:
 683					deactivateGracePeriod();
 684				case Intent.ACTION_SCREEN_OFF:
 685					if (awayWhenScreenOff()) {
 686						refreshAllPresences();
 687					}
 688					break;
 689				case ACTION_GCM_TOKEN_REFRESH:
 690					refreshAllGcmTokens();
 691					break;
 692				case ACTION_IDLE_PING:
 693					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 694						scheduleNextIdlePing();
 695					}
 696					break;
 697				case ACTION_GCM_MESSAGE_RECEIVED:
 698					Log.d(Config.LOGTAG,"gcm push message arrived in service. extras="+intent.getExtras());
 699					pushedAccountHash = intent.getStringExtra("account");
 700					break;
 701			}
 702		}
 703		synchronized (this) {
 704			this.wakeLock.acquire();
 705			boolean pingNow = ConnectivityManager.CONNECTIVITY_ACTION.equals(action);
 706			HashSet<Account> pingCandidates = new HashSet<>();
 707			for (Account account : accounts) {
 708				pingNow |= processAccountState(account,
 709						interactive,
 710						"ui".equals(action),
 711						CryptoHelper.getAccountFingerprint(account).equals(pushedAccountHash),
 712						pingCandidates);
 713			}
 714			if (pingNow) {
 715				for (Account account : pingCandidates) {
 716					final boolean lowTimeout = mLowPingTimeoutMode.contains(account.getJid().toBareJid());
 717					account.getXmppConnection().sendPing();
 718					Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")");
 719					scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
 720				}
 721			}
 722			if (wakeLock.isHeld()) {
 723				try {
 724					wakeLock.release();
 725				} catch (final RuntimeException ignored) {
 726				}
 727			}
 728		}
 729		if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
 730			expireOldMessages();
 731		}
 732		return START_STICKY;
 733	}
 734
 735	private boolean processAccountState(Account account, boolean interactive, boolean isUiAction, boolean isAccountPushed, HashSet<Account> pingCandidates) {
 736		boolean pingNow = false;
 737		if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 738			if (!hasInternetConnection()) {
 739				account.setStatus(Account.State.NO_INTERNET);
 740				if (statusListener != null) {
 741					statusListener.onStatusChanged(account);
 742				}
 743			} else {
 744				if (account.getStatus() == Account.State.NO_INTERNET) {
 745					account.setStatus(Account.State.OFFLINE);
 746					if (statusListener != null) {
 747						statusListener.onStatusChanged(account);
 748					}
 749				}
 750				if (account.getStatus() == Account.State.ONLINE) {
 751					synchronized (mLowPingTimeoutMode) {
 752						long lastReceived = account.getXmppConnection().getLastPacketReceived();
 753						long lastSent = account.getXmppConnection().getLastPingSent();
 754						long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 755						long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 756						int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().toBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
 757						long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
 758						if (lastSent > lastReceived) {
 759							if (pingTimeoutIn < 0) {
 760								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
 761								this.reconnectAccount(account, true, interactive);
 762							} else {
 763								int secs = (int) (pingTimeoutIn / 1000);
 764								this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
 765							}
 766						} else {
 767							pingCandidates.add(account);
 768							if (isAccountPushed) {
 769								pingNow = true;
 770								if (mLowPingTimeoutMode.add(account.getJid().toBareJid())) {
 771									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": entering low ping timeout mode");
 772								}
 773							} else if (msToNextPing <= 0) {
 774								pingNow = true;
 775							} else {
 776								this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 777								if (mLowPingTimeoutMode.remove(account.getJid().toBareJid())) {
 778									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": leaving low ping timeout mode");
 779								}
 780							}
 781						}
 782					}
 783				} else if (account.getStatus() == Account.State.OFFLINE) {
 784					reconnectAccount(account, true, interactive);
 785				} else if (account.getStatus() == Account.State.CONNECTING) {
 786					long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
 787					long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
 788					long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
 789					long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
 790					if (timeout < 0) {
 791						Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast="+secondsSinceLastConnect+")");
 792						account.getXmppConnection().resetAttemptCount(false);
 793						reconnectAccount(account, true, interactive);
 794					} else if (discoTimeout < 0) {
 795						account.getXmppConnection().sendDiscoTimeout();
 796						scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
 797					} else {
 798						scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
 799					}
 800				} else {
 801					if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 802						reconnectAccount(account, true, interactive);
 803					}
 804				}
 805			}
 806		}
 807		return pingNow;
 808	}
 809
 810	public boolean isDataSaverDisabled() {
 811		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 812			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
 813			return !connectivityManager.isActiveNetworkMetered()
 814					|| connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
 815		} else {
 816			return true;
 817		}
 818	}
 819
 820	private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) {
 821		Message message = new Message(conversation,body,conversation.getNextEncryption());
 822		message.markUnread();
 823		if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 824			getPgpEngine().encrypt(message, new UiCallback<Message>() {
 825				@Override
 826				public void success(Message message) {
 827					message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 828					sendMessage(message);
 829					if (dismissAfterReply) {
 830						markRead(message.getConversation(),true);
 831					} else {
 832						mNotificationService.pushFromDirectReply(message);
 833					}
 834				}
 835
 836				@Override
 837				public void error(int errorCode, Message object) {
 838
 839				}
 840
 841				@Override
 842				public void userInputRequried(PendingIntent pi, Message object) {
 843
 844				}
 845			});
 846		} else {
 847			sendMessage(message);
 848			if (dismissAfterReply) {
 849				markRead(conversation,true);
 850			} else {
 851				mNotificationService.pushFromDirectReply(message);
 852			}
 853		}
 854	}
 855
 856	private boolean xaOnSilentMode() {
 857		return getPreferences().getBoolean("xa_on_silent_mode", false);
 858	}
 859
 860	private boolean manuallyChangePresence() {
 861		return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, false);
 862	}
 863
 864	private boolean treatVibrateAsSilent() {
 865		return getPreferences().getBoolean(SettingsActivity.TREAT_VIBRATE_AS_SILENT, false);
 866	}
 867
 868	private boolean awayWhenScreenOff() {
 869		return getPreferences().getBoolean(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, false);
 870	}
 871
 872	private String getCompressPicturesPreference() {
 873		return getPreferences().getString("picture_compression", "auto");
 874	}
 875
 876	private Presence.Status getTargetPresence() {
 877		if (xaOnSilentMode() && isPhoneSilenced()) {
 878			return Presence.Status.XA;
 879		} else if (awayWhenScreenOff() && !isInteractive()) {
 880			return Presence.Status.AWAY;
 881		} else {
 882			return Presence.Status.ONLINE;
 883		}
 884	}
 885
 886	@SuppressLint("NewApi")
 887	@SuppressWarnings("deprecation")
 888	public boolean isInteractive() {
 889		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 890
 891		final boolean isScreenOn;
 892		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 893			isScreenOn = pm.isScreenOn();
 894		} else {
 895			isScreenOn = pm.isInteractive();
 896		}
 897		return isScreenOn;
 898	}
 899
 900	private boolean isPhoneSilenced() {
 901		AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
 902		try {
 903			if (treatVibrateAsSilent()) {
 904				return audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
 905			} else {
 906				return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
 907			}
 908		} catch (Throwable throwable) {
 909			Log.d(Config.LOGTAG,"platform bug in isPhoneSilenced ("+ throwable.getMessage()+")");
 910			return false;
 911		}
 912	}
 913
 914	private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
 915		Log.d(Config.LOGTAG, "resetting all attempt counts");
 916		for (Account account : accounts) {
 917			if (account.hasErrorStatus() || reallyAll) {
 918				final XmppConnection connection = account.getXmppConnection();
 919				if (connection != null) {
 920					connection.resetAttemptCount(retryImmediately);
 921				}
 922			}
 923			if (account.setShowErrorNotification(true)) {
 924				databaseBackend.updateAccount(account);
 925			}
 926		}
 927		mNotificationService.updateErrorNotification();
 928	}
 929
 930	private void dismissErrorNotifications() {
 931		for (final Account account : this.accounts) {
 932			if (account.hasErrorStatus()) {
 933				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": dismissing error notification");
 934				if (account.setShowErrorNotification(false)) {
 935					databaseBackend.updateAccount(account);
 936				}
 937			}
 938		}
 939	}
 940
 941	private void expireOldMessages() {
 942		expireOldMessages(false);
 943	}
 944
 945	public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
 946		mLastExpiryRun.set(SystemClock.elapsedRealtime());
 947		mDatabaseExecutor.execute(new Runnable() {
 948			@Override
 949			public void run() {
 950				long timestamp = getAutomaticMessageDeletionDate();
 951				if (timestamp > 0) {
 952					databaseBackend.expireOldMessages(timestamp);
 953					synchronized (XmppConnectionService.this.conversations) {
 954						for (Conversation conversation : XmppConnectionService.this.conversations) {
 955							conversation.expireOldMessages(timestamp);
 956							if (resetHasMessagesLeftOnServer) {
 957								conversation.messagesLoaded.set(true);
 958								conversation.setHasMessagesLeftOnServer(true);
 959							}
 960						}
 961					}
 962					updateConversationUi();
 963				}
 964			}
 965		});
 966	}
 967
 968	public boolean hasInternetConnection() {
 969		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 970				.getSystemService(Context.CONNECTIVITY_SERVICE);
 971		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 972		return activeNetwork != null && activeNetwork.isConnected();
 973	}
 974
 975	@SuppressLint("TrulyRandom")
 976	@Override
 977	public void onCreate() {
 978		ExceptionHelper.init(getApplicationContext());
 979		PRNGFixes.apply();
 980		this.mRandom = new SecureRandom();
 981		updateMemorizingTrustmanager();
 982		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 983		final int cacheSize = maxMemory / 8;
 984		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 985			@Override
 986			protected int sizeOf(final String key, final Bitmap bitmap) {
 987				return bitmap.getByteCount() / 1024;
 988			}
 989		};
 990
 991		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 992		this.accounts = databaseBackend.getAccounts();
 993
 994		if (Config.FREQUENT_RESTARTS_THRESHOLD != 0
 995				&& Config.FREQUENT_RESTARTS_DETECTION_WINDOW != 0
 996				&& !keepForegroundService()
 997				&& databaseBackend.startTimeCountExceedsThreshold()) {
 998			getPreferences().edit().putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE,true).commit();
 999			Log.d(Config.LOGTAG,"number of restarts exceeds threshold. enabling foreground service");
1000		}
1001
1002		restoreFromDatabase();
1003
1004		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
1005		new Thread(new Runnable() {
1006			@Override
1007			public void run() {
1008				fileObserver.startWatching();
1009			}
1010		}).start();
1011		if (Config.supportOpenPgp()) {
1012			this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
1013				@Override
1014				public void onBound(IOpenPgpService2 service) {
1015					for (Account account : accounts) {
1016						final PgpDecryptionService pgp = account.getPgpDecryptionService();
1017						if(pgp != null) {
1018							pgp.continueDecryption(true);
1019						}
1020					}
1021				}
1022
1023				@Override
1024				public void onError(Exception e) {
1025				}
1026			});
1027			this.pgpServiceConnection.bindToService();
1028		}
1029
1030		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
1031		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
1032
1033		toggleForegroundService();
1034		updateUnreadCountBadge();
1035		toggleScreenEventReceiver();
1036		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1037			scheduleNextIdlePing();
1038		}
1039		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1040			registerReceiver(this.mEventReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
1041		}
1042	}
1043
1044	@Override
1045	public void onTrimMemory(int level) {
1046		super.onTrimMemory(level);
1047		if (level >= TRIM_MEMORY_COMPLETE) {
1048			Log.d(Config.LOGTAG, "clear cache due to low memory");
1049			getBitmapCache().evictAll();
1050		}
1051	}
1052
1053	@Override
1054	public void onDestroy() {
1055		try {
1056			unregisterReceiver(this.mEventReceiver);
1057		} catch (IllegalArgumentException e) {
1058			//ignored
1059		}
1060		fileObserver.stopWatching();
1061		super.onDestroy();
1062	}
1063
1064	public void toggleScreenEventReceiver() {
1065		if (awayWhenScreenOff() && !manuallyChangePresence()) {
1066			final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
1067			filter.addAction(Intent.ACTION_SCREEN_OFF);
1068			registerReceiver(this.mEventReceiver, filter);
1069		} else {
1070			try {
1071				unregisterReceiver(this.mEventReceiver);
1072			} catch (IllegalArgumentException e) {
1073				//ignored
1074			}
1075		}
1076	}
1077
1078	public void toggleForegroundService() {
1079		if (keepForegroundService()) {
1080			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
1081		} else {
1082			stopForeground(true);
1083		}
1084	}
1085
1086	private boolean keepForegroundService() {
1087		return getPreferences().getBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE,false);
1088	}
1089
1090	@Override
1091	public void onTaskRemoved(final Intent rootIntent) {
1092		super.onTaskRemoved(rootIntent);
1093		if (!keepForegroundService()) {
1094			this.logoutAndSave(false);
1095		} else {
1096			Log.d(Config.LOGTAG,"ignoring onTaskRemoved because foreground service is activated");
1097		}
1098	}
1099
1100	private void logoutAndSave(boolean stop) {
1101		int activeAccounts = 0;
1102		databaseBackend.clearStartTimeCounter(true); // regular swipes don't count towards restart counter
1103		for (final Account account : accounts) {
1104			if (account.getStatus() != Account.State.DISABLED) {
1105				activeAccounts++;
1106			}
1107			databaseBackend.writeRoster(account.getRoster());
1108			if (account.getXmppConnection() != null) {
1109				new Thread(new Runnable() {
1110					@Override
1111					public void run() {
1112						disconnect(account, false);
1113					}
1114				}).start();
1115			}
1116		}
1117		if (stop || activeAccounts == 0) {
1118			Log.d(Config.LOGTAG, "good bye");
1119			stopSelf();
1120		}
1121	}
1122
1123	public void scheduleWakeUpCall(int seconds, int requestCode) {
1124		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1125		AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1126		Intent intent = new Intent(this, EventReceiver.class);
1127		intent.setAction("ping");
1128		PendingIntent alarmIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1129		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
1130	}
1131
1132	@TargetApi(Build.VERSION_CODES.M)
1133	private void scheduleNextIdlePing() {
1134		Log.d(Config.LOGTAG,"schedule next idle ping");
1135		AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1136		Intent intent = new Intent(this, EventReceiver.class);
1137		intent.setAction(ACTION_IDLE_PING);
1138		alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1139				SystemClock.elapsedRealtime()+(Config.IDLE_PING_INTERVAL * 1000),
1140				PendingIntent.getBroadcast(this,0,intent,0)
1141				);
1142	}
1143
1144	public XmppConnection createConnection(final Account account) {
1145		final SharedPreferences sharedPref = getPreferences();
1146		String resource;
1147		try {
1148			resource = sharedPref.getString("resource", getString(R.string.default_resource)).toLowerCase(Locale.ENGLISH);
1149			if (resource.trim().isEmpty()) {
1150				throw new Exception();
1151			}
1152		} catch (Exception e) {
1153			resource = "conversations";
1154		}
1155		account.setResource(resource);
1156		final XmppConnection connection = new XmppConnection(account, this);
1157		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1158		connection.setOnStatusChangedListener(this.statusListener);
1159		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1160		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1161		connection.setOnJinglePacketReceivedListener(this.jingleListener);
1162		connection.setOnBindListener(this.mOnBindListener);
1163		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1164		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1165		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1166		AxolotlService axolotlService = account.getAxolotlService();
1167		if (axolotlService != null) {
1168			connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1169		}
1170		return connection;
1171	}
1172
1173	public void sendChatState(Conversation conversation) {
1174		if (sendChatStates()) {
1175			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1176			sendMessagePacket(conversation.getAccount(), packet);
1177		}
1178	}
1179
1180	private void sendFileMessage(final Message message, final boolean delay) {
1181		Log.d(Config.LOGTAG, "send file message");
1182		final Account account = message.getConversation().getAccount();
1183		if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())) {
1184			mHttpConnectionManager.createNewUploadConnection(message, delay);
1185		} else {
1186			mJingleConnectionManager.createNewConnection(message);
1187		}
1188	}
1189
1190	public void sendMessage(final Message message) {
1191		sendMessage(message, false, false);
1192	}
1193
1194	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1195		final Account account = message.getConversation().getAccount();
1196		if (account.setShowErrorNotification(true)) {
1197			databaseBackend.updateAccount(account);
1198			mNotificationService.updateErrorNotification();
1199		}
1200		final Conversation conversation = message.getConversation();
1201		account.deactivateGracePeriod();
1202		MessagePacket packet = null;
1203		final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1204				|| account.getServerIdentity() != XmppConnection.Identity.SLACK)
1205				&& !message.edited();
1206		boolean saveInDb = addToConversation;
1207		message.setStatus(Message.STATUS_WAITING);
1208
1209		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
1210			message.getConversation().endOtrIfNeeded();
1211			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
1212					new Conversation.OnMessageFound() {
1213						@Override
1214						public void onMessageFound(Message message) {
1215							markMessage(message, Message.STATUS_SEND_FAILED);
1216						}
1217					});
1218		}
1219
1220		if (account.isOnlineAndConnected()) {
1221			switch (message.getEncryption()) {
1222				case Message.ENCRYPTION_NONE:
1223					if (message.needsUploading()) {
1224						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1225								|| message.fixCounterpart()) {
1226							this.sendFileMessage(message, delay);
1227						} else {
1228							break;
1229						}
1230					} else {
1231						packet = mMessageGenerator.generateChat(message);
1232					}
1233					break;
1234				case Message.ENCRYPTION_PGP:
1235				case Message.ENCRYPTION_DECRYPTED:
1236					if (message.needsUploading()) {
1237						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1238								|| message.fixCounterpart()) {
1239							this.sendFileMessage(message, delay);
1240						} else {
1241							break;
1242						}
1243					} else {
1244						packet = mMessageGenerator.generatePgpChat(message);
1245					}
1246					break;
1247				case Message.ENCRYPTION_OTR:
1248					SessionImpl otrSession = conversation.getOtrSession();
1249					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
1250						try {
1251							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
1252						} catch (InvalidJidException e) {
1253							break;
1254						}
1255						if (message.needsUploading()) {
1256							mJingleConnectionManager.createNewConnection(message);
1257						} else {
1258							packet = mMessageGenerator.generateOtrChat(message);
1259						}
1260					} else if (otrSession == null) {
1261						if (message.fixCounterpart()) {
1262							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
1263						} else {
1264							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fix counterpart for OTR message to contact "+message.getContact().getJid());
1265							break;
1266						}
1267					} else {
1268						Log.d(Config.LOGTAG,account.getJid().toBareJid()+" OTR session with "+message.getContact()+" is in wrong state: "+otrSession.getSessionStatus().toString());
1269					}
1270					break;
1271				case Message.ENCRYPTION_AXOLOTL:
1272					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1273					if (message.needsUploading()) {
1274						if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1275								|| message.fixCounterpart()) {
1276							this.sendFileMessage(message, delay);
1277						} else {
1278							break;
1279						}
1280					} else {
1281						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1282						if (axolotlMessage == null) {
1283							account.getAxolotlService().preparePayloadMessage(message, delay);
1284						} else {
1285							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1286						}
1287					}
1288					break;
1289
1290			}
1291			if (packet != null) {
1292				if (account.getXmppConnection().getFeatures().sm()
1293						|| (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1294					message.setStatus(Message.STATUS_UNSEND);
1295				} else {
1296					message.setStatus(Message.STATUS_SEND);
1297				}
1298			}
1299		} else {
1300			switch (message.getEncryption()) {
1301				case Message.ENCRYPTION_DECRYPTED:
1302					if (!message.needsUploading()) {
1303						String pgpBody = message.getEncryptedBody();
1304						String decryptedBody = message.getBody();
1305						message.setBody(pgpBody);
1306						message.setEncryption(Message.ENCRYPTION_PGP);
1307						if (message.edited()) {
1308							message.setBody(decryptedBody);
1309							message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1310							databaseBackend.updateMessage(message, message.getEditedId());
1311							updateConversationUi();
1312							return;
1313						} else {
1314							databaseBackend.createMessage(message);
1315							saveInDb = false;
1316							message.setBody(decryptedBody);
1317							message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1318						}
1319					}
1320					break;
1321				case Message.ENCRYPTION_OTR:
1322					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
1323						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": create otr session without starting for "+message.getContact().getJid());
1324						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
1325					}
1326					break;
1327				case Message.ENCRYPTION_AXOLOTL:
1328					message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1329					break;
1330			}
1331		}
1332
1333		if (resend) {
1334			if (packet != null && addToConversation) {
1335				if (account.getXmppConnection().getFeatures().sm()
1336						|| (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1337					markMessage(message, Message.STATUS_UNSEND);
1338				} else {
1339					markMessage(message, Message.STATUS_SEND);
1340				}
1341			}
1342		} else {
1343			if (addToConversation) {
1344				conversation.add(message);
1345			}
1346			if (saveInDb) {
1347				databaseBackend.createMessage(message);
1348			} else if (message.edited()) {
1349				databaseBackend.updateMessage(message, message.getEditedId());
1350			}
1351			updateConversationUi();
1352		}
1353		if (packet != null) {
1354			if (delay) {
1355				mMessageGenerator.addDelay(packet, message.getTimeSent());
1356			}
1357			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1358				if (this.sendChatStates()) {
1359					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1360				}
1361			}
1362			sendMessagePacket(account, packet);
1363		}
1364	}
1365
1366	private void sendUnsentMessages(final Conversation conversation) {
1367		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
1368
1369			@Override
1370			public void onMessageFound(Message message) {
1371				resendMessage(message, true);
1372			}
1373		});
1374	}
1375
1376	public void resendMessage(final Message message, final boolean delay) {
1377		sendMessage(message, true, delay);
1378	}
1379
1380	public void fetchRosterFromServer(final Account account) {
1381		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1382		if (!"".equals(account.getRosterVersion())) {
1383			Log.d(Config.LOGTAG, account.getJid().toBareJid()
1384					+ ": fetching roster version " + account.getRosterVersion());
1385		} else {
1386			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1387		}
1388		iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
1389		sendIqPacket(account, iqPacket, mIqParser);
1390	}
1391
1392	public void fetchBookmarks(final Account account) {
1393		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1394		final Element query = iqPacket.query("jabber:iq:private");
1395		query.addChild("storage", "storage:bookmarks");
1396		final OnIqPacketReceived callback = new OnIqPacketReceived() {
1397
1398			@Override
1399			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1400				if (packet.getType() == IqPacket.TYPE.RESULT) {
1401					final Element query = packet.query();
1402					final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1403					final Element storage = query.findChild("storage", "storage:bookmarks");
1404					final boolean autojoin = respectAutojoin();
1405					if (storage != null) {
1406						for (final Element item : storage.getChildren()) {
1407							if (item.getName().equals("conference")) {
1408								final Bookmark bookmark = Bookmark.parse(item, account);
1409								Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1410								if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1411									bookmark.setBookmarkName(old.getBookmarkName());
1412								}
1413								Conversation conversation = find(bookmark);
1414								if (conversation != null) {
1415									conversation.setBookmark(bookmark);
1416								} else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1417									conversation = findOrCreateConversation(
1418											account, bookmark.getJid(), true);
1419									conversation.setBookmark(bookmark);
1420									joinMuc(conversation);
1421								}
1422							}
1423						}
1424					}
1425					account.setBookmarks(new ArrayList<>(bookmarks.values()));
1426				} else {
1427					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1428				}
1429			}
1430		};
1431		sendIqPacket(account, iqPacket, callback);
1432	}
1433
1434	public void pushBookmarks(Account account) {
1435		Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1436		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1437		Element query = iqPacket.query("jabber:iq:private");
1438		Element storage = query.addChild("storage", "storage:bookmarks");
1439		for (Bookmark bookmark : account.getBookmarks()) {
1440			storage.addChild(bookmark);
1441		}
1442		sendIqPacket(account, iqPacket, mDefaultIqHandler);
1443	}
1444
1445	private void restoreFromDatabase() {
1446		synchronized (this.conversations) {
1447			final Map<String, Account> accountLookupTable = new Hashtable<>();
1448			for (Account account : this.accounts) {
1449				accountLookupTable.put(account.getUuid(), account);
1450			}
1451			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1452			for (Conversation conversation : this.conversations) {
1453				Account account = accountLookupTable.get(conversation.getAccountUuid());
1454				conversation.setAccount(account);
1455			}
1456			Runnable runnable = new Runnable() {
1457				@Override
1458				public void run() {
1459					long deletionDate = getAutomaticMessageDeletionDate();
1460					mLastExpiryRun.set(SystemClock.elapsedRealtime());
1461					if (deletionDate > 0) {
1462						Log.d(Config.LOGTAG, "deleting messages that are older than "+AbstractGenerator.getTimestamp(deletionDate));
1463						databaseBackend.expireOldMessages(deletionDate);
1464					}
1465					Log.d(Config.LOGTAG, "restoring roster");
1466					for (Account account : accounts) {
1467						databaseBackend.readRoster(account.getRoster());
1468						account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1469					}
1470					getBitmapCache().evictAll();
1471					loadPhoneContacts();
1472					Log.d(Config.LOGTAG, "restoring messages");
1473					for (Conversation conversation : conversations) {
1474						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1475						checkDeletedFiles(conversation);
1476						conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
1477
1478							@Override
1479							public void onMessageFound(Message message) {
1480								markMessage(message, Message.STATUS_WAITING);
1481							}
1482						});
1483						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1484							@Override
1485							public void onMessageFound(Message message) {
1486								mNotificationService.pushFromBacklog(message);
1487							}
1488						});
1489					}
1490					mNotificationService.finishBacklog(false);
1491					mRestoredFromDatabase = true;
1492					Log.d(Config.LOGTAG, "restored all messages");
1493					updateConversationUi();
1494				}
1495			};
1496			mDatabaseExecutor.execute(runnable);
1497		}
1498	}
1499
1500	public void loadPhoneContacts() {
1501		mContactMergerExecutor.execute(new Runnable() {
1502			@Override
1503			public void run() {
1504				PhoneHelper.loadPhoneContacts(XmppConnectionService.this, new OnPhoneContactsLoadedListener() {
1505					@Override
1506					public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
1507						Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1508						for (Account account : accounts) {
1509							List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1510							for (Bundle phoneContact : phoneContacts) {
1511								Jid jid;
1512								try {
1513									jid = Jid.fromString(phoneContact.getString("jid"));
1514								} catch (final InvalidJidException e) {
1515									continue;
1516								}
1517								final Contact contact = account.getRoster().getContact(jid);
1518								String systemAccount = phoneContact.getInt("phoneid")
1519										+ "#"
1520										+ phoneContact.getString("lookup");
1521								contact.setSystemAccount(systemAccount);
1522								if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1523									getAvatarService().clear(contact);
1524								}
1525								contact.setSystemName(phoneContact.getString("displayname"));
1526								withSystemAccounts.remove(contact);
1527							}
1528							for (Contact contact : withSystemAccounts) {
1529								contact.setSystemAccount(null);
1530								contact.setSystemName(null);
1531								if (contact.setPhotoUri(null)) {
1532									getAvatarService().clear(contact);
1533								}
1534							}
1535						}
1536						Log.d(Config.LOGTAG, "finished merging phone contacts");
1537						updateAccountUi();
1538					}
1539				});
1540			}
1541		});
1542	}
1543
1544	public List<Conversation> getConversations() {
1545		return this.conversations;
1546	}
1547
1548	private void checkDeletedFiles(Conversation conversation) {
1549		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1550
1551			@Override
1552			public void onMessageFound(Message message) {
1553				if (!getFileBackend().isFileAvailable(message)) {
1554					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1555					final int s = message.getStatus();
1556					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1557						markMessage(message, Message.STATUS_SEND_FAILED);
1558					}
1559				}
1560			}
1561		});
1562	}
1563
1564	private void markFileDeleted(final String path) {
1565		Log.d(Config.LOGTAG,"deleted file "+path);
1566		for (Conversation conversation : getConversations()) {
1567			conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1568				@Override
1569				public void onMessageFound(Message message) {
1570					DownloadableFile file = fileBackend.getFile(message);
1571					if (file.getAbsolutePath().equals(path)) {
1572						if (!file.exists()) {
1573							message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1574							final int s = message.getStatus();
1575							if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1576								markMessage(message, Message.STATUS_SEND_FAILED);
1577							} else {
1578								updateConversationUi();
1579							}
1580						} else {
1581							Log.d(Config.LOGTAG,"found matching message for file "+path+" but file still exists");
1582						}
1583					}
1584				}
1585			});
1586		}
1587	}
1588
1589	public void populateWithOrderedConversations(final List<Conversation> list) {
1590		populateWithOrderedConversations(list, true);
1591	}
1592
1593	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1594		list.clear();
1595		if (includeNoFileUpload) {
1596			list.addAll(getConversations());
1597		} else {
1598			for (Conversation conversation : getConversations()) {
1599				if (conversation.getMode() == Conversation.MODE_SINGLE
1600						|| conversation.getAccount().httpUploadAvailable()) {
1601					list.add(conversation);
1602				}
1603			}
1604		}
1605		try {
1606			Collections.sort(list);
1607		} catch (IllegalArgumentException e) {
1608			//ignore
1609		}
1610	}
1611
1612	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1613		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1614			return;
1615		} else if (timestamp == 0) {
1616			return;
1617		}
1618		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1619		Runnable runnable = new Runnable() {
1620			@Override
1621			public void run() {
1622				final Account account = conversation.getAccount();
1623				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1624				if (messages.size() > 0) {
1625					conversation.addAll(0, messages);
1626					checkDeletedFiles(conversation);
1627					callback.onMoreMessagesLoaded(messages.size(), conversation);
1628				} else if (conversation.hasMessagesLeftOnServer()
1629						&& account.isOnlineAndConnected()
1630						&& conversation.getLastClearHistory() == 0) {
1631					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1632							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1633						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1634						if (query != null) {
1635							query.setCallback(callback);
1636							callback.informUser(R.string.fetching_history_from_server);
1637						} else {
1638							callback.informUser(R.string.not_fetching_history_retention_period);
1639						}
1640
1641					}
1642				}
1643			}
1644		};
1645		mDatabaseExecutor.execute(runnable);
1646	}
1647
1648	public List<Account> getAccounts() {
1649		return this.accounts;
1650	}
1651
1652	public List<Conversation> findAllConferencesWith(Contact contact) {
1653		ArrayList<Conversation> results = new ArrayList<>();
1654		for(Conversation conversation : conversations) {
1655			if (conversation.getMode() == Conversation.MODE_MULTI
1656					&& conversation.getMucOptions().isContactInRoom(contact)) {
1657				results.add(conversation);
1658			}
1659		}
1660		return results;
1661	}
1662
1663	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1664		for (final Conversation conversation : haystack) {
1665			if (conversation.getContact() == contact) {
1666				return conversation;
1667			}
1668		}
1669		return null;
1670	}
1671
1672	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1673		if (jid == null) {
1674			return null;
1675		}
1676		for (final Conversation conversation : haystack) {
1677			if ((account == null || conversation.getAccount() == account)
1678					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1679				return conversation;
1680			}
1681		}
1682		return null;
1683	}
1684
1685	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1686		return this.findOrCreateConversation(account, jid, muc, null);
1687	}
1688
1689	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1690		synchronized (this.conversations) {
1691			Conversation conversation = find(account, jid);
1692			if (conversation != null) {
1693				return conversation;
1694			}
1695			conversation = databaseBackend.findConversation(account, jid);
1696			final boolean loadMessagesFromDb;
1697			if (conversation != null) {
1698				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1699				conversation.setAccount(account);
1700				if (muc) {
1701					conversation.setMode(Conversation.MODE_MULTI);
1702					conversation.setContactJid(jid);
1703				} else {
1704					conversation.setMode(Conversation.MODE_SINGLE);
1705					conversation.setContactJid(jid.toBareJid());
1706				}
1707				databaseBackend.updateConversation(conversation);
1708				loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true,false);
1709			} else {
1710				String conversationName;
1711				Contact contact = account.getRoster().getContact(jid);
1712				if (contact != null) {
1713					conversationName = contact.getDisplayName();
1714				} else {
1715					conversationName = jid.getLocalpart();
1716				}
1717				if (muc) {
1718					conversation = new Conversation(conversationName, account, jid,
1719							Conversation.MODE_MULTI);
1720				} else {
1721					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1722							Conversation.MODE_SINGLE);
1723				}
1724				this.databaseBackend.createConversation(conversation);
1725				loadMessagesFromDb = false;
1726			}
1727			final Conversation c = conversation;
1728			mDatabaseExecutor.execute(new Runnable() {
1729				@Override
1730				public void run() {
1731					if (loadMessagesFromDb) {
1732						c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1733						updateConversationUi();
1734						c.messagesLoaded.set(true);
1735					}
1736					if (account.getXmppConnection() != null
1737							&& account.getXmppConnection().getFeatures().mam()
1738							&& !muc) {
1739						if (query == null) {
1740							mMessageArchiveService.query(c);
1741						} else {
1742							if (query.getConversation() == null) {
1743								mMessageArchiveService.query(c, query.getStart());
1744							}
1745						}
1746					}
1747					checkDeletedFiles(c);
1748				}
1749			});
1750			this.conversations.add(conversation);
1751			updateConversationUi();
1752			return conversation;
1753		}
1754	}
1755
1756	public void archiveConversation(Conversation conversation) {
1757		getNotificationService().clear(conversation);
1758		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1759		synchronized (this.conversations) {
1760			if (conversation.getMode() == Conversation.MODE_MULTI) {
1761				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1762					Bookmark bookmark = conversation.getBookmark();
1763					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1764						bookmark.setAutojoin(false);
1765						pushBookmarks(bookmark.getAccount());
1766					}
1767				}
1768				leaveMuc(conversation);
1769			} else {
1770				conversation.endOtrIfNeeded();
1771				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1772					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1773					sendPresencePacket(
1774							conversation.getAccount(),
1775							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1776					);
1777				}
1778			}
1779			updateConversation(conversation);
1780			this.conversations.remove(conversation);
1781			updateConversationUi();
1782		}
1783	}
1784
1785	public void createAccount(final Account account) {
1786		account.initAccountServices(this);
1787		databaseBackend.createAccount(account);
1788		this.accounts.add(account);
1789		this.reconnectAccountInBackground(account);
1790		updateAccountUi();
1791	}
1792
1793	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1794		new Thread(new Runnable() {
1795			@Override
1796			public void run() {
1797				try {
1798					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1799					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1800					if (findAccountByJid(info.first) == null) {
1801						Account account = new Account(info.first, "");
1802						account.setPrivateKeyAlias(alias);
1803						account.setOption(Account.OPTION_DISABLED, true);
1804						account.setDisplayName(info.second);
1805						createAccount(account);
1806						callback.onAccountCreated(account);
1807						if (Config.X509_VERIFICATION) {
1808							try {
1809								getMemorizingTrustManager().getNonInteractive(account.getJid().getDomainpart()).checkClientTrusted(chain, "RSA");
1810							} catch (CertificateException e) {
1811								callback.informUser(R.string.certificate_chain_is_not_trusted);
1812							}
1813						}
1814					} else {
1815						callback.informUser(R.string.account_already_exists);
1816					}
1817				} catch (Exception e) {
1818					e.printStackTrace();
1819					callback.informUser(R.string.unable_to_parse_certificate);
1820				}
1821			}
1822		}).start();
1823
1824	}
1825
1826	public void updateKeyInAccount(final Account account, final String alias) {
1827		Log.d(Config.LOGTAG, "update key in account " + alias);
1828		try {
1829			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1830			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1831			if (account.getJid().toBareJid().equals(info.first)) {
1832				account.setPrivateKeyAlias(alias);
1833				account.setDisplayName(info.second);
1834				databaseBackend.updateAccount(account);
1835				if (Config.X509_VERIFICATION) {
1836					try {
1837						getMemorizingTrustManager().getNonInteractive(account.getJid().getDomainpart()).checkClientTrusted(chain, "RSA");
1838					} catch (CertificateException e) {
1839						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1840					}
1841					account.getAxolotlService().regenerateKeys(true);
1842				}
1843			} else {
1844				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1845			}
1846		} catch (Exception e) {
1847			e.printStackTrace();
1848		}
1849	}
1850
1851	public boolean updateAccount(final Account account) {
1852		if (databaseBackend.updateAccount(account)) {
1853			account.setShowErrorNotification(true);
1854			this.statusListener.onStatusChanged(account);
1855			databaseBackend.updateAccount(account);
1856			reconnectAccountInBackground(account);
1857			updateAccountUi();
1858			getNotificationService().updateErrorNotification();
1859			return true;
1860		} else {
1861			return false;
1862		}
1863	}
1864
1865	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1866		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1867		sendIqPacket(account, iq, new OnIqPacketReceived() {
1868			@Override
1869			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1870				if (packet.getType() == IqPacket.TYPE.RESULT) {
1871					account.setPassword(newPassword);
1872					account.setOption(Account.OPTION_MAGIC_CREATE, false);
1873					databaseBackend.updateAccount(account);
1874					callback.onPasswordChangeSucceeded();
1875				} else {
1876					callback.onPasswordChangeFailed();
1877				}
1878			}
1879		});
1880	}
1881
1882	public void deleteAccount(final Account account) {
1883		synchronized (this.conversations) {
1884			for (final Conversation conversation : conversations) {
1885				if (conversation.getAccount() == account) {
1886					if (conversation.getMode() == Conversation.MODE_MULTI) {
1887						leaveMuc(conversation);
1888					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1889						conversation.endOtrIfNeeded();
1890					}
1891					conversations.remove(conversation);
1892				}
1893			}
1894			if (account.getXmppConnection() != null) {
1895				new Thread(new Runnable() {
1896					@Override
1897					public void run() {
1898						disconnect(account, true);
1899					}
1900				}).start();
1901			}
1902			Runnable runnable = new Runnable() {
1903				@Override
1904				public void run() {
1905					if (!databaseBackend.deleteAccount(account)) {
1906						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": unable to delete account");
1907					}
1908				}
1909			};
1910			mDatabaseExecutor.execute(runnable);
1911			this.accounts.remove(account);
1912			updateAccountUi();
1913			getNotificationService().updateErrorNotification();
1914		}
1915	}
1916
1917	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1918		synchronized (this) {
1919			this.mLastActivity = System.currentTimeMillis();
1920			if (checkListeners()) {
1921				switchToForeground();
1922			}
1923			this.mOnConversationUpdate = listener;
1924			this.mNotificationService.setIsInForeground(true);
1925			if (this.convChangedListenerCount < 2) {
1926				this.convChangedListenerCount++;
1927			}
1928		}
1929	}
1930
1931	public void removeOnConversationListChangedListener() {
1932		synchronized (this) {
1933			this.convChangedListenerCount--;
1934			if (this.convChangedListenerCount <= 0) {
1935				this.convChangedListenerCount = 0;
1936				this.mOnConversationUpdate = null;
1937				this.mNotificationService.setIsInForeground(false);
1938				if (checkListeners()) {
1939					switchToBackground();
1940				}
1941			}
1942		}
1943	}
1944
1945	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1946		synchronized (this) {
1947			if (checkListeners()) {
1948				switchToForeground();
1949			}
1950			this.mOnShowErrorToast = onShowErrorToast;
1951			if (this.showErrorToastListenerCount < 2) {
1952				this.showErrorToastListenerCount++;
1953			}
1954		}
1955		this.mOnShowErrorToast = onShowErrorToast;
1956	}
1957
1958	public void removeOnShowErrorToastListener() {
1959		synchronized (this) {
1960			this.showErrorToastListenerCount--;
1961			if (this.showErrorToastListenerCount <= 0) {
1962				this.showErrorToastListenerCount = 0;
1963				this.mOnShowErrorToast = null;
1964				if (checkListeners()) {
1965					switchToBackground();
1966				}
1967			}
1968		}
1969	}
1970
1971	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1972		synchronized (this) {
1973			if (checkListeners()) {
1974				switchToForeground();
1975			}
1976			this.mOnAccountUpdate = listener;
1977			if (this.accountChangedListenerCount < 2) {
1978				this.accountChangedListenerCount++;
1979			}
1980		}
1981	}
1982
1983	public void removeOnAccountListChangedListener() {
1984		synchronized (this) {
1985			this.accountChangedListenerCount--;
1986			if (this.accountChangedListenerCount <= 0) {
1987				this.mOnAccountUpdate = null;
1988				this.accountChangedListenerCount = 0;
1989				if (checkListeners()) {
1990					switchToBackground();
1991				}
1992			}
1993		}
1994	}
1995
1996	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1997		synchronized (this) {
1998			if (checkListeners()) {
1999				switchToForeground();
2000			}
2001			this.mOnCaptchaRequested = listener;
2002			if (this.captchaRequestedListenerCount < 2) {
2003				this.captchaRequestedListenerCount++;
2004			}
2005		}
2006	}
2007
2008	public void removeOnCaptchaRequestedListener() {
2009		synchronized (this) {
2010			this.captchaRequestedListenerCount--;
2011			if (this.captchaRequestedListenerCount <= 0) {
2012				this.mOnCaptchaRequested = null;
2013				this.captchaRequestedListenerCount = 0;
2014				if (checkListeners()) {
2015					switchToBackground();
2016				}
2017			}
2018		}
2019	}
2020
2021	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2022		synchronized (this) {
2023			if (checkListeners()) {
2024				switchToForeground();
2025			}
2026			this.mOnRosterUpdate = listener;
2027			if (this.rosterChangedListenerCount < 2) {
2028				this.rosterChangedListenerCount++;
2029			}
2030		}
2031	}
2032
2033	public void removeOnRosterUpdateListener() {
2034		synchronized (this) {
2035			this.rosterChangedListenerCount--;
2036			if (this.rosterChangedListenerCount <= 0) {
2037				this.rosterChangedListenerCount = 0;
2038				this.mOnRosterUpdate = null;
2039				if (checkListeners()) {
2040					switchToBackground();
2041				}
2042			}
2043		}
2044	}
2045
2046	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2047		synchronized (this) {
2048			if (checkListeners()) {
2049				switchToForeground();
2050			}
2051			this.mOnUpdateBlocklist = listener;
2052			if (this.updateBlocklistListenerCount < 2) {
2053				this.updateBlocklistListenerCount++;
2054			}
2055		}
2056	}
2057
2058	public void removeOnUpdateBlocklistListener() {
2059		synchronized (this) {
2060			this.updateBlocklistListenerCount--;
2061			if (this.updateBlocklistListenerCount <= 0) {
2062				this.updateBlocklistListenerCount = 0;
2063				this.mOnUpdateBlocklist = null;
2064				if (checkListeners()) {
2065					switchToBackground();
2066				}
2067			}
2068		}
2069	}
2070
2071	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2072		synchronized (this) {
2073			if (checkListeners()) {
2074				switchToForeground();
2075			}
2076			this.mOnKeyStatusUpdated = listener;
2077			if (this.keyStatusUpdatedListenerCount < 2) {
2078				this.keyStatusUpdatedListenerCount++;
2079			}
2080		}
2081	}
2082
2083	public void removeOnNewKeysAvailableListener() {
2084		synchronized (this) {
2085			this.keyStatusUpdatedListenerCount--;
2086			if (this.keyStatusUpdatedListenerCount <= 0) {
2087				this.keyStatusUpdatedListenerCount = 0;
2088				this.mOnKeyStatusUpdated = null;
2089				if (checkListeners()) {
2090					switchToBackground();
2091				}
2092			}
2093		}
2094	}
2095
2096	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2097		synchronized (this) {
2098			if (checkListeners()) {
2099				switchToForeground();
2100			}
2101			this.mOnMucRosterUpdate = listener;
2102			if (this.mucRosterChangedListenerCount < 2) {
2103				this.mucRosterChangedListenerCount++;
2104			}
2105		}
2106	}
2107
2108	public void removeOnMucRosterUpdateListener() {
2109		synchronized (this) {
2110			this.mucRosterChangedListenerCount--;
2111			if (this.mucRosterChangedListenerCount <= 0) {
2112				this.mucRosterChangedListenerCount = 0;
2113				this.mOnMucRosterUpdate = null;
2114				if (checkListeners()) {
2115					switchToBackground();
2116				}
2117			}
2118		}
2119	}
2120
2121	public boolean checkListeners() {
2122		return (this.mOnAccountUpdate == null
2123				&& this.mOnConversationUpdate == null
2124				&& this.mOnRosterUpdate == null
2125				&& this.mOnCaptchaRequested == null
2126				&& this.mOnUpdateBlocklist == null
2127				&& this.mOnShowErrorToast == null
2128				&& this.mOnKeyStatusUpdated == null);
2129	}
2130
2131	private void switchToForeground() {
2132		final boolean broadcastLastActivity = broadcastLastActivity();
2133		for (Conversation conversation : getConversations()) {
2134			conversation.setIncomingChatState(ChatState.ACTIVE);
2135		}
2136		for (Account account : getAccounts()) {
2137			if (account.getStatus() == Account.State.ONLINE) {
2138				account.deactivateGracePeriod();
2139				final XmppConnection connection = account.getXmppConnection();
2140				if (connection != null ) {
2141					if (connection.getFeatures().csi()) {
2142						connection.sendActive();
2143					}
2144					if (broadcastLastActivity) {
2145						sendPresence(account, false); //send new presence but don't include idle because we are not
2146					}
2147				}
2148			}
2149		}
2150		Log.d(Config.LOGTAG, "app switched into foreground");
2151	}
2152
2153	private void switchToBackground() {
2154		final boolean broadcastLastActivity = broadcastLastActivity();
2155		for (Account account : getAccounts()) {
2156			if (account.getStatus() == Account.State.ONLINE) {
2157				XmppConnection connection = account.getXmppConnection();
2158				if (connection != null) {
2159					if (broadcastLastActivity) {
2160						sendPresence(account, broadcastLastActivity);
2161					}
2162					if (connection.getFeatures().csi()) {
2163						connection.sendInactive();
2164					}
2165				}
2166			}
2167		}
2168		this.mNotificationService.setIsInForeground(false);
2169		Log.d(Config.LOGTAG, "app switched into background");
2170	}
2171
2172	private void connectMultiModeConversations(Account account) {
2173		List<Conversation> conversations = getConversations();
2174		for (Conversation conversation : conversations) {
2175			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2176				joinMuc(conversation);
2177			}
2178		}
2179	}
2180
2181	public void joinMuc(Conversation conversation) {
2182		joinMuc(conversation,null, false);
2183	}
2184
2185	public void joinMuc(Conversation conversation, boolean followedInvite) {
2186		joinMuc(conversation, null, followedInvite);
2187	}
2188
2189	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2190		joinMuc(conversation,onConferenceJoined,false);
2191	}
2192
2193	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2194		Account account = conversation.getAccount();
2195		account.pendingConferenceJoins.remove(conversation);
2196		account.pendingConferenceLeaves.remove(conversation);
2197		if (account.getStatus() == Account.State.ONLINE) {
2198			conversation.resetMucOptions();
2199			if (onConferenceJoined != null) {
2200				conversation.getMucOptions().flagNoAutoPushConfiguration();
2201			}
2202			conversation.setHasMessagesLeftOnServer(false);
2203			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2204
2205				private void join(Conversation conversation) {
2206					Account account = conversation.getAccount();
2207					final MucOptions mucOptions = conversation.getMucOptions();
2208					final Jid joinJid = mucOptions.getSelf().getFullJid();
2209					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
2210					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
2211					packet.setTo(joinJid);
2212					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2213					if (conversation.getMucOptions().getPassword() != null) {
2214						x.addChild("password").setContent(mucOptions.getPassword());
2215					}
2216
2217					if (mucOptions.mamSupport()) {
2218						// Use MAM instead of the limited muc history to get history
2219						x.addChild("history").setAttribute("maxchars", "0");
2220					} else {
2221						// Fallback to muc history
2222						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
2223					}
2224					sendPresencePacket(account, packet);
2225					if (onConferenceJoined != null) {
2226						onConferenceJoined.onConferenceJoined(conversation);
2227					}
2228					if (!joinJid.equals(conversation.getJid())) {
2229						conversation.setContactJid(joinJid);
2230						databaseBackend.updateConversation(conversation);
2231					}
2232
2233					if (mucOptions.mamSupport()) {
2234						getMessageArchiveService().catchupMUC(conversation);
2235					}
2236					if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
2237						fetchConferenceMembers(conversation);
2238						if (followedInvite && conversation.getBookmark() == null) {
2239							saveConversationAsBookmark(conversation,null);
2240						}
2241					}
2242					sendUnsentMessages(conversation);
2243				}
2244
2245				@Override
2246				public void onConferenceConfigurationFetched(Conversation conversation) {
2247					join(conversation);
2248				}
2249
2250				@Override
2251				public void onFetchFailed(final Conversation conversation, Element error) {
2252					if (error != null && "remote-server-not-found".equals(error.getName())) {
2253						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2254					} else {
2255						join(conversation);
2256						fetchConferenceConfiguration(conversation);
2257					}
2258				}
2259			});
2260			updateConversationUi();
2261		} else {
2262			account.pendingConferenceJoins.add(conversation);
2263			conversation.resetMucOptions();
2264			conversation.setHasMessagesLeftOnServer(false);
2265			updateConversationUi();
2266		}
2267	}
2268
2269	private void fetchConferenceMembers(final Conversation conversation) {
2270		final Account account = conversation.getAccount();
2271		final String[] affiliations = {"member","admin","owner"};
2272		OnIqPacketReceived callback = new OnIqPacketReceived() {
2273
2274			private int i = 0;
2275			private boolean success = true;
2276
2277			@Override
2278			public void onIqPacketReceived(Account account, IqPacket packet) {
2279
2280				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2281				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2282					for(Element child : query.getChildren()) {
2283						if ("item".equals(child.getName())) {
2284							MucOptions.User user = AbstractParser.parseItem(conversation,child);
2285							if (!user.realJidMatchesAccount()) {
2286								conversation.getMucOptions().updateUser(user);
2287							}
2288						}
2289					}
2290				} else {
2291					success = false;
2292					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
2293				}
2294				++i;
2295				if (i >= affiliations.length) {
2296					List<Jid> members = conversation.getMucOptions().getMembers();
2297					if (success) {
2298						List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2299						boolean changed = false;
2300						for(ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext();) {
2301							Jid jid = iterator.next();
2302							if (!members.contains(jid)) {
2303								iterator.remove();
2304								Log.d(Config.LOGTAG,account.getJid().toBareJid()+": removed "+jid+" from crypto targets of "+conversation.getName());
2305								changed = true;
2306							}
2307						}
2308						if (changed) {
2309							conversation.setAcceptedCryptoTargets(cryptoTargets);
2310							updateConversation(conversation);
2311						}
2312					}
2313					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
2314					getAvatarService().clear(conversation);
2315					updateMucRosterUi();
2316					updateConversationUi();
2317				}
2318			}
2319		};
2320		for(String affiliation : affiliations) {
2321			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2322		}
2323		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
2324	}
2325
2326	public void providePasswordForMuc(Conversation conversation, String password) {
2327		if (conversation.getMode() == Conversation.MODE_MULTI) {
2328			conversation.getMucOptions().setPassword(password);
2329			if (conversation.getBookmark() != null) {
2330				if (respectAutojoin()) {
2331					conversation.getBookmark().setAutojoin(true);
2332				}
2333				pushBookmarks(conversation.getAccount());
2334			}
2335			updateConversation(conversation);
2336			joinMuc(conversation);
2337		}
2338	}
2339
2340	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2341		final MucOptions options = conversation.getMucOptions();
2342		final Jid joinJid = options.createJoinJid(nick);
2343		if (options.online()) {
2344			Account account = conversation.getAccount();
2345			options.setOnRenameListener(new OnRenameListener() {
2346
2347				@Override
2348				public void onSuccess() {
2349					conversation.setContactJid(joinJid);
2350					databaseBackend.updateConversation(conversation);
2351					Bookmark bookmark = conversation.getBookmark();
2352					if (bookmark != null) {
2353						bookmark.setNick(nick);
2354						pushBookmarks(bookmark.getAccount());
2355					}
2356					callback.success(conversation);
2357				}
2358
2359				@Override
2360				public void onFailure() {
2361					callback.error(R.string.nick_in_use, conversation);
2362				}
2363			});
2364
2365			PresencePacket packet = new PresencePacket();
2366			packet.setTo(joinJid);
2367			packet.setFrom(conversation.getAccount().getJid());
2368
2369			String sig = account.getPgpSignature();
2370			if (sig != null) {
2371				packet.addChild("status").setContent("online");
2372				packet.addChild("x", "jabber:x:signed").setContent(sig);
2373			}
2374			sendPresencePacket(account, packet);
2375		} else {
2376			conversation.setContactJid(joinJid);
2377			databaseBackend.updateConversation(conversation);
2378			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2379				Bookmark bookmark = conversation.getBookmark();
2380				if (bookmark != null) {
2381					bookmark.setNick(nick);
2382					pushBookmarks(bookmark.getAccount());
2383				}
2384				joinMuc(conversation);
2385			}
2386		}
2387	}
2388
2389	public void leaveMuc(Conversation conversation) {
2390		leaveMuc(conversation, false);
2391	}
2392
2393	private void leaveMuc(Conversation conversation, boolean now) {
2394		Account account = conversation.getAccount();
2395		account.pendingConferenceJoins.remove(conversation);
2396		account.pendingConferenceLeaves.remove(conversation);
2397		if (account.getStatus() == Account.State.ONLINE || now) {
2398			PresencePacket packet = new PresencePacket();
2399			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2400			packet.setFrom(conversation.getAccount().getJid());
2401			packet.setAttribute("type", "unavailable");
2402			sendPresencePacket(conversation.getAccount(), packet);
2403			conversation.getMucOptions().setOffline();
2404			conversation.deregisterWithBookmark();
2405			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2406					+ ": leaving muc " + conversation.getJid());
2407		} else {
2408			account.pendingConferenceLeaves.add(conversation);
2409		}
2410	}
2411
2412	private String findConferenceServer(final Account account) {
2413		String server;
2414		if (account.getXmppConnection() != null) {
2415			server = account.getXmppConnection().getMucServer();
2416			if (server != null) {
2417				return server;
2418			}
2419		}
2420		for (Account other : getAccounts()) {
2421			if (other != account && other.getXmppConnection() != null) {
2422				server = other.getXmppConnection().getMucServer();
2423				if (server != null) {
2424					return server;
2425				}
2426			}
2427		}
2428		return null;
2429	}
2430
2431	public void createAdhocConference(final Account account,
2432									  final String subject,
2433									  final Iterable<Jid> jids,
2434									  final UiCallback<Conversation> callback) {
2435		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2436		if (account.getStatus() == Account.State.ONLINE) {
2437			try {
2438				String server = findConferenceServer(account);
2439				if (server == null) {
2440					if (callback != null) {
2441						callback.error(R.string.no_conference_server_found, null);
2442					}
2443					return;
2444				}
2445				final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2446				final Conversation conversation = findOrCreateConversation(account, jid, true);
2447				joinMuc(conversation, new OnConferenceJoined() {
2448					@Override
2449					public void onConferenceJoined(final Conversation conversation) {
2450						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConferenceOptionsPushed() {
2451							@Override
2452							public void onPushSucceeded() {
2453								if (subject != null && !subject.trim().isEmpty()) {
2454									pushSubjectToConference(conversation, subject.trim());
2455								}
2456								for (Jid invite : jids) {
2457									invite(conversation, invite);
2458								}
2459								if (account.countPresences() > 1) {
2460									directInvite(conversation, account.getJid().toBareJid());
2461								}
2462								saveConversationAsBookmark(conversation, subject);
2463								if (callback != null) {
2464									callback.success(conversation);
2465								}
2466							}
2467
2468							@Override
2469							public void onPushFailed() {
2470								archiveConversation(conversation);
2471								if (callback != null) {
2472									callback.error(R.string.conference_creation_failed, conversation);
2473								}
2474							}
2475						});
2476					}
2477				});
2478			} catch (InvalidJidException e) {
2479				if (callback != null) {
2480					callback.error(R.string.conference_creation_failed, null);
2481				}
2482			}
2483		} else {
2484			if (callback != null) {
2485				callback.error(R.string.not_connected_try_again, null);
2486			}
2487		}
2488	}
2489
2490	public void fetchConferenceConfiguration(final Conversation conversation) {
2491		fetchConferenceConfiguration(conversation, null);
2492	}
2493
2494	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2495		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2496		request.setTo(conversation.getJid().toBareJid());
2497		request.query("http://jabber.org/protocol/disco#info");
2498		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2499			@Override
2500			public void onIqPacketReceived(Account account, IqPacket packet) {
2501				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2502				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2503					ArrayList<String> features = new ArrayList<>();
2504					for (Element child : query.getChildren()) {
2505						if (child != null && child.getName().equals("feature")) {
2506							String var = child.getAttribute("var");
2507							if (var != null) {
2508								features.add(var);
2509							}
2510						}
2511					}
2512					Element form = query.findChild("x", "jabber:x:data");
2513					if (form != null) {
2514						conversation.getMucOptions().updateFormData(Data.parse(form));
2515					}
2516					conversation.getMucOptions().updateFeatures(features);
2517					if (callback != null) {
2518						callback.onConferenceConfigurationFetched(conversation);
2519					}
2520					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2521					updateConversationUi();
2522				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2523					if (callback != null) {
2524						callback.onFetchFailed(conversation, packet.getError());
2525					}
2526				}
2527			}
2528		});
2529	}
2530
2531	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2532		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2533		request.setTo(conversation.getJid().toBareJid());
2534		request.query("http://jabber.org/protocol/muc#owner");
2535		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2536			@Override
2537			public void onIqPacketReceived(Account account, IqPacket packet) {
2538				if (packet.getType() == IqPacket.TYPE.RESULT) {
2539					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2540					for (Field field : data.getFields()) {
2541						if (options.containsKey(field.getFieldName())) {
2542							field.setValue(options.getString(field.getFieldName()));
2543						}
2544					}
2545					data.submit();
2546					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2547					set.setTo(conversation.getJid().toBareJid());
2548					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2549					sendIqPacket(account, set, new OnIqPacketReceived() {
2550						@Override
2551						public void onIqPacketReceived(Account account, IqPacket packet) {
2552							if (callback != null) {
2553								if (packet.getType() == IqPacket.TYPE.RESULT) {
2554									callback.onPushSucceeded();
2555								} else {
2556									callback.onPushFailed();
2557								}
2558							}
2559						}
2560					});
2561				} else {
2562					if (callback != null) {
2563						callback.onPushFailed();
2564					}
2565				}
2566			}
2567		});
2568	}
2569
2570	public void pushSubjectToConference(final Conversation conference, final String subject) {
2571		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2572		this.sendMessagePacket(conference.getAccount(), packet);
2573		final MucOptions mucOptions = conference.getMucOptions();
2574		final MucOptions.User self = mucOptions.getSelf();
2575		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2576			Bundle options = new Bundle();
2577			options.putString("muc#roomconfig_persistentroom", "1");
2578			this.pushConferenceConfiguration(conference, options, null);
2579		}
2580	}
2581
2582	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2583		final Jid jid = user.toBareJid();
2584		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2585		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2586			@Override
2587			public void onIqPacketReceived(Account account, IqPacket packet) {
2588				if (packet.getType() == IqPacket.TYPE.RESULT) {
2589					conference.getMucOptions().changeAffiliation(jid, affiliation);
2590					getAvatarService().clear(conference);
2591					callback.onAffiliationChangedSuccessful(jid);
2592				} else {
2593					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2594				}
2595			}
2596		});
2597	}
2598
2599	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2600		List<Jid> jids = new ArrayList<>();
2601		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2602			if (user.getAffiliation() == before && user.getRealJid() != null) {
2603				jids.add(user.getRealJid());
2604			}
2605		}
2606		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2607		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2608	}
2609
2610	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2611		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2612		Log.d(Config.LOGTAG, request.toString());
2613		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2614			@Override
2615			public void onIqPacketReceived(Account account, IqPacket packet) {
2616				Log.d(Config.LOGTAG, packet.toString());
2617				if (packet.getType() == IqPacket.TYPE.RESULT) {
2618					callback.onRoleChangedSuccessful(nick);
2619				} else {
2620					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2621				}
2622			}
2623		});
2624	}
2625
2626	private void disconnect(Account account, boolean force) {
2627		if ((account.getStatus() == Account.State.ONLINE)
2628				|| (account.getStatus() == Account.State.DISABLED)) {
2629			final XmppConnection connection = account.getXmppConnection();
2630			if (!force) {
2631				List<Conversation> conversations = getConversations();
2632				for (Conversation conversation : conversations) {
2633					if (conversation.getAccount() == account) {
2634						if (conversation.getMode() == Conversation.MODE_MULTI) {
2635							leaveMuc(conversation, true);
2636						} else {
2637							if (conversation.endOtrIfNeeded()) {
2638								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2639										+ ": ended otr session with "
2640										+ conversation.getJid());
2641							}
2642						}
2643					}
2644				}
2645				sendOfflinePresence(account);
2646			}
2647			connection.disconnect(force);
2648		}
2649	}
2650
2651	@Override
2652	public IBinder onBind(Intent intent) {
2653		return mBinder;
2654	}
2655
2656	public void updateMessage(Message message) {
2657		databaseBackend.updateMessage(message);
2658		updateConversationUi();
2659	}
2660
2661	public void updateMessage(Message message, String uuid) {
2662		databaseBackend.updateMessage(message, uuid);
2663		updateConversationUi();
2664	}
2665
2666	protected void syncDirtyContacts(Account account) {
2667		for (Contact contact : account.getRoster().getContacts()) {
2668			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2669				pushContactToServer(contact);
2670			}
2671			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2672				deleteContactOnServer(contact);
2673			}
2674		}
2675	}
2676
2677	public void createContact(Contact contact) {
2678		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2679		if (autoGrant) {
2680			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2681			contact.setOption(Contact.Options.ASKING);
2682		}
2683		pushContactToServer(contact);
2684	}
2685
2686	public void onOtrSessionEstablished(Conversation conversation) {
2687		final Account account = conversation.getAccount();
2688		final Session otrSession = conversation.getOtrSession();
2689		Log.d(Config.LOGTAG,
2690				account.getJid().toBareJid() + " otr session established with "
2691						+ conversation.getJid() + "/"
2692						+ otrSession.getSessionID().getUserID());
2693		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2694
2695			@Override
2696			public void onMessageFound(Message message) {
2697				SessionID id = otrSession.getSessionID();
2698				try {
2699					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2700				} catch (InvalidJidException e) {
2701					return;
2702				}
2703				if (message.needsUploading()) {
2704					mJingleConnectionManager.createNewConnection(message);
2705				} else {
2706					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2707					if (outPacket != null) {
2708						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2709						message.setStatus(Message.STATUS_SEND);
2710						databaseBackend.updateMessage(message);
2711						sendMessagePacket(account, outPacket);
2712					}
2713				}
2714				updateConversationUi();
2715			}
2716		});
2717	}
2718
2719	public boolean renewSymmetricKey(Conversation conversation) {
2720		Account account = conversation.getAccount();
2721		byte[] symmetricKey = new byte[32];
2722		this.mRandom.nextBytes(symmetricKey);
2723		Session otrSession = conversation.getOtrSession();
2724		if (otrSession != null) {
2725			MessagePacket packet = new MessagePacket();
2726			packet.setType(MessagePacket.TYPE_CHAT);
2727			packet.setFrom(account.getJid());
2728			MessageGenerator.addMessageHints(packet);
2729			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2730					+ otrSession.getSessionID().getUserID());
2731			try {
2732				packet.setBody(otrSession
2733						.transformSending(CryptoHelper.FILETRANSFER
2734								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2735				sendMessagePacket(account, packet);
2736				conversation.setSymmetricKey(symmetricKey);
2737				return true;
2738			} catch (OtrException e) {
2739				return false;
2740			}
2741		}
2742		return false;
2743	}
2744
2745	public void pushContactToServer(final Contact contact) {
2746		contact.resetOption(Contact.Options.DIRTY_DELETE);
2747		contact.setOption(Contact.Options.DIRTY_PUSH);
2748		final Account account = contact.getAccount();
2749		if (account.getStatus() == Account.State.ONLINE) {
2750			final boolean ask = contact.getOption(Contact.Options.ASKING);
2751			final boolean sendUpdates = contact
2752					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2753					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2754			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2755			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2756			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2757			if (sendUpdates) {
2758				sendPresencePacket(account,
2759						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2760			}
2761			if (ask) {
2762				sendPresencePacket(account,
2763						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2764			}
2765		}
2766	}
2767
2768	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2769		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2770		final int size = Config.AVATAR_SIZE;
2771		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2772		if (avatar != null) {
2773			avatar.height = size;
2774			avatar.width = size;
2775			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2776				avatar.type = "image/webp";
2777			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2778				avatar.type = "image/jpeg";
2779			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2780				avatar.type = "image/png";
2781			}
2782			if (!getFileBackend().save(avatar)) {
2783				callback.error(R.string.error_saving_avatar, avatar);
2784				return;
2785			}
2786			publishAvatar(account, avatar, callback);
2787		} else {
2788			callback.error(R.string.error_publish_avatar_converting, null);
2789		}
2790	}
2791
2792	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2793		IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2794		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2795
2796			@Override
2797			public void onIqPacketReceived(Account account, IqPacket result) {
2798				if (result.getType() == IqPacket.TYPE.RESULT) {
2799					final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2800					sendIqPacket(account, packet, new OnIqPacketReceived() {
2801						@Override
2802						public void onIqPacketReceived(Account account, IqPacket result) {
2803							if (result.getType() == IqPacket.TYPE.RESULT) {
2804								if (account.setAvatar(avatar.getFilename())) {
2805									getAvatarService().clear(account);
2806									databaseBackend.updateAccount(account);
2807								}
2808								Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar "+(avatar.size/1024)+"KiB");
2809								if (callback != null) {
2810									callback.success(avatar);
2811								}
2812							} else {
2813								if (callback != null) {
2814									callback.error(R.string.error_publish_avatar_server_reject,avatar);
2815								}
2816							}
2817						}
2818					});
2819				} else {
2820					Element error = result.findChild("error");
2821					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server rejected avatar "+(avatar.size/1024)+"KiB "+(error!=null?error.toString():""));
2822					if (callback != null) {
2823						callback.error(R.string.error_publish_avatar_server_reject, avatar);
2824					}
2825				}
2826			}
2827		});
2828	}
2829
2830	public void republishAvatarIfNeeded(Account account) {
2831		if (account.getAxolotlService().isPepBroken()) {
2832			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2833			return;
2834		}
2835		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2836		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2837
2838			private Avatar parseAvatar(IqPacket packet) {
2839				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2840				if (pubsub != null) {
2841					Element items = pubsub.findChild("items");
2842					if (items != null) {
2843						return Avatar.parseMetadata(items);
2844					}
2845				}
2846				return null;
2847			}
2848
2849			private boolean errorIsItemNotFound(IqPacket packet) {
2850				Element error = packet.findChild("error");
2851				return packet.getType() == IqPacket.TYPE.ERROR
2852						&& error != null
2853						&& error.hasChild("item-not-found");
2854			}
2855
2856			@Override
2857			public void onIqPacketReceived(Account account, IqPacket packet) {
2858				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2859					Avatar serverAvatar = parseAvatar(packet);
2860					if (serverAvatar == null && account.getAvatar() != null) {
2861						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2862						if (avatar != null) {
2863							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2864							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2865						} else {
2866							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2867						}
2868					}
2869				}
2870			}
2871		});
2872	}
2873
2874	public void fetchAvatar(Account account, Avatar avatar) {
2875		fetchAvatar(account, avatar, null);
2876	}
2877
2878	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2879		final String KEY = generateFetchKey(account, avatar);
2880		synchronized (this.mInProgressAvatarFetches) {
2881			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2882				switch (avatar.origin) {
2883					case PEP:
2884						this.mInProgressAvatarFetches.add(KEY);
2885						fetchAvatarPep(account, avatar, callback);
2886						break;
2887					case VCARD:
2888						this.mInProgressAvatarFetches.add(KEY);
2889						fetchAvatarVcard(account, avatar, callback);
2890						break;
2891				}
2892			}
2893		}
2894	}
2895
2896	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2897		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2898		sendIqPacket(account, packet, new OnIqPacketReceived() {
2899
2900			@Override
2901			public void onIqPacketReceived(Account account, IqPacket result) {
2902				synchronized (mInProgressAvatarFetches) {
2903					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2904				}
2905				final String ERROR = account.getJid().toBareJid()
2906						+ ": fetching avatar for " + avatar.owner + " failed ";
2907				if (result.getType() == IqPacket.TYPE.RESULT) {
2908					avatar.image = mIqParser.avatarData(result);
2909					if (avatar.image != null) {
2910						if (getFileBackend().save(avatar)) {
2911							if (account.getJid().toBareJid().equals(avatar.owner)) {
2912								if (account.setAvatar(avatar.getFilename())) {
2913									databaseBackend.updateAccount(account);
2914								}
2915								getAvatarService().clear(account);
2916								updateConversationUi();
2917								updateAccountUi();
2918							} else {
2919								Contact contact = account.getRoster()
2920										.getContact(avatar.owner);
2921								contact.setAvatar(avatar);
2922								getAvatarService().clear(contact);
2923								updateConversationUi();
2924								updateRosterUi();
2925							}
2926							if (callback != null) {
2927								callback.success(avatar);
2928							}
2929							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2930									+ ": successfully fetched pep avatar for " + avatar.owner);
2931							return;
2932						}
2933					} else {
2934
2935						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2936					}
2937				} else {
2938					Element error = result.findChild("error");
2939					if (error == null) {
2940						Log.d(Config.LOGTAG, ERROR + "(server error)");
2941					} else {
2942						Log.d(Config.LOGTAG, ERROR + error.toString());
2943					}
2944				}
2945				if (callback != null) {
2946					callback.error(0, null);
2947				}
2948
2949			}
2950		});
2951	}
2952
2953	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2954		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2955		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2956			@Override
2957			public void onIqPacketReceived(Account account, IqPacket packet) {
2958				synchronized (mInProgressAvatarFetches) {
2959					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2960				}
2961				if (packet.getType() == IqPacket.TYPE.RESULT) {
2962					Element vCard = packet.findChild("vCard", "vcard-temp");
2963					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2964					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2965					if (image != null) {
2966						avatar.image = image;
2967						if (getFileBackend().save(avatar)) {
2968							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2969									+ ": successfully fetched vCard avatar for " + avatar.owner);
2970							if (avatar.owner.isBareJid()) {
2971								if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2972									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": had no avatar. replacing with vcard");
2973									account.setAvatar(avatar.getFilename());
2974									databaseBackend.updateAccount(account);
2975									getAvatarService().clear(account);
2976									updateAccountUi();
2977								} else {
2978									Contact contact = account.getRoster().getContact(avatar.owner);
2979									contact.setAvatar(avatar);
2980									getAvatarService().clear(contact);
2981									updateRosterUi();
2982								}
2983								updateConversationUi();
2984							} else {
2985								Conversation conversation = find(account, avatar.owner.toBareJid());
2986								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2987									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2988									if (user != null) {
2989										if (user.setAvatar(avatar)) {
2990											getAvatarService().clear(user);
2991											updateConversationUi();
2992											updateMucRosterUi();
2993										}
2994									}
2995								}
2996							}
2997						}
2998					}
2999				}
3000			}
3001		});
3002	}
3003
3004	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3005		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3006		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3007
3008			@Override
3009			public void onIqPacketReceived(Account account, IqPacket packet) {
3010				if (packet.getType() == IqPacket.TYPE.RESULT) {
3011					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
3012					if (pubsub != null) {
3013						Element items = pubsub.findChild("items");
3014						if (items != null) {
3015							Avatar avatar = Avatar.parseMetadata(items);
3016							if (avatar != null) {
3017								avatar.owner = account.getJid().toBareJid();
3018								if (fileBackend.isAvatarCached(avatar)) {
3019									if (account.setAvatar(avatar.getFilename())) {
3020										databaseBackend.updateAccount(account);
3021									}
3022									getAvatarService().clear(account);
3023									callback.success(avatar);
3024								} else {
3025									fetchAvatarPep(account, avatar, callback);
3026								}
3027								return;
3028							}
3029						}
3030					}
3031				}
3032				callback.error(0, null);
3033			}
3034		});
3035	}
3036
3037	public void deleteContactOnServer(Contact contact) {
3038		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3039		contact.resetOption(Contact.Options.DIRTY_PUSH);
3040		contact.setOption(Contact.Options.DIRTY_DELETE);
3041		Account account = contact.getAccount();
3042		if (account.getStatus() == Account.State.ONLINE) {
3043			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3044			Element item = iq.query(Xmlns.ROSTER).addChild("item");
3045			item.setAttribute("jid", contact.getJid().toString());
3046			item.setAttribute("subscription", "remove");
3047			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3048		}
3049	}
3050
3051	public void updateConversation(final Conversation conversation) {
3052		mDatabaseExecutor.execute(new Runnable() {
3053			@Override
3054			public void run() {
3055				databaseBackend.updateConversation(conversation);
3056			}
3057		});
3058	}
3059
3060	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3061		synchronized (account) {
3062			XmppConnection connection = account.getXmppConnection();
3063			if (connection == null) {
3064				connection = createConnection(account);
3065				account.setXmppConnection(connection);
3066			}
3067			boolean hasInternet = hasInternetConnection();
3068			if (!account.isOptionSet(Account.OPTION_DISABLED) && hasInternet) {
3069				if (!force) {
3070					disconnect(account, false);
3071				}
3072				Thread thread = new Thread(connection);
3073				connection.setInteractive(interactive);
3074				connection.prepareNewConnection();
3075				connection.interrupt();
3076				thread.start();
3077				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3078			} else {
3079				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3080				account.getRoster().clearPresences();
3081				connection.resetEverything();
3082				account.getAxolotlService().resetBrokenness();
3083				if (!hasInternet) {
3084					account.setStatus(Account.State.NO_INTERNET);
3085				}
3086			}
3087		}
3088	}
3089
3090	public void reconnectAccountInBackground(final Account account) {
3091		new Thread(new Runnable() {
3092			@Override
3093			public void run() {
3094				reconnectAccount(account, false, true);
3095			}
3096		}).start();
3097	}
3098
3099	public void invite(Conversation conversation, Jid contact) {
3100		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
3101		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3102		sendMessagePacket(conversation.getAccount(), packet);
3103	}
3104
3105	public void directInvite(Conversation conversation, Jid jid) {
3106		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3107		sendMessagePacket(conversation.getAccount(), packet);
3108	}
3109
3110	public void resetSendingToWaiting(Account account) {
3111		for (Conversation conversation : getConversations()) {
3112			if (conversation.getAccount() == account) {
3113				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3114
3115					@Override
3116					public void onMessageFound(Message message) {
3117						markMessage(message, Message.STATUS_WAITING);
3118					}
3119				});
3120			}
3121		}
3122	}
3123
3124	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3125		return markMessage(account, recipient, uuid, status, null);
3126	}
3127
3128	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3129		if (uuid == null) {
3130			return null;
3131		}
3132		for (Conversation conversation : getConversations()) {
3133			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
3134				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3135				if (message != null) {
3136					markMessage(message, status, errorMessage);
3137				}
3138				return message;
3139			}
3140		}
3141		return null;
3142	}
3143
3144	public boolean markMessage(Conversation conversation, String uuid, int status) {
3145		if (uuid == null) {
3146			return false;
3147		} else {
3148			Message message = conversation.findSentMessageWithUuid(uuid);
3149			if (message != null) {
3150				markMessage(message, status);
3151				return true;
3152			} else {
3153				return false;
3154			}
3155		}
3156	}
3157
3158	public void markMessage(Message message, int status) {
3159		markMessage(message, status, null);
3160	}
3161
3162
3163	public void markMessage(Message message, int status, String errorMessage) {
3164		if (status == Message.STATUS_SEND_FAILED
3165				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
3166				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
3167			return;
3168		}
3169		message.setErrorMessage(errorMessage);
3170		message.setStatus(status);
3171		databaseBackend.updateMessage(message);
3172		updateConversationUi();
3173	}
3174
3175	public SharedPreferences getPreferences() {
3176		return PreferenceManager
3177				.getDefaultSharedPreferences(getApplicationContext());
3178	}
3179
3180	public long getAutomaticMessageDeletionDate() {
3181		try {
3182			final long timeout = Long.parseLong(getPreferences().getString(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, "0")) * 1000;
3183			return timeout == 0 ? timeout : System.currentTimeMillis() - timeout;
3184		} catch (NumberFormatException e) {
3185			return 0;
3186		}
3187	}
3188
3189	public boolean confirmMessages() {
3190		return getPreferences().getBoolean("confirm_messages", true);
3191	}
3192
3193	public boolean allowMessageCorrection() {
3194		return getPreferences().getBoolean("allow_message_correction", true);
3195	}
3196
3197	public boolean sendChatStates() {
3198		return getPreferences().getBoolean("chat_states", false);
3199	}
3200
3201	private boolean respectAutojoin() {
3202		return getPreferences().getBoolean("autojoin", true);
3203	}
3204
3205	public boolean indicateReceived() {
3206		return getPreferences().getBoolean("indicate_received", false);
3207	}
3208
3209	public boolean useTorToConnect() {
3210		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
3211	}
3212
3213	public boolean showExtendedConnectionOptions() {
3214		return getPreferences().getBoolean("show_connection_options", false);
3215	}
3216
3217	public boolean broadcastLastActivity() {
3218		return getPreferences().getBoolean("last_activity", false);
3219	}
3220
3221	public int unreadCount() {
3222		int count = 0;
3223		for (Conversation conversation : getConversations()) {
3224			count += conversation.unreadCount();
3225		}
3226		return count;
3227	}
3228
3229
3230	public void showErrorToastInUi(int resId) {
3231		if (mOnShowErrorToast != null) {
3232			mOnShowErrorToast.onShowErrorToast(resId);
3233		}
3234	}
3235
3236	public void updateConversationUi() {
3237		if (mOnConversationUpdate != null) {
3238			mOnConversationUpdate.onConversationUpdate();
3239		}
3240	}
3241
3242	public void updateAccountUi() {
3243		if (mOnAccountUpdate != null) {
3244			mOnAccountUpdate.onAccountUpdate();
3245		}
3246	}
3247
3248	public void updateRosterUi() {
3249		if (mOnRosterUpdate != null) {
3250			mOnRosterUpdate.onRosterUpdate();
3251		}
3252	}
3253
3254	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3255		if (mOnCaptchaRequested != null) {
3256			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3257			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3258					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3259
3260			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3261			return true;
3262		}
3263		return false;
3264	}
3265
3266	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3267		if (mOnUpdateBlocklist != null) {
3268			mOnUpdateBlocklist.OnUpdateBlocklist(status);
3269		}
3270	}
3271
3272	public void updateMucRosterUi() {
3273		if (mOnMucRosterUpdate != null) {
3274			mOnMucRosterUpdate.onMucRosterUpdate();
3275		}
3276	}
3277
3278	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3279		if (mOnKeyStatusUpdated != null) {
3280			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3281		}
3282	}
3283
3284	public Account findAccountByJid(final Jid accountJid) {
3285		for (Account account : this.accounts) {
3286			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3287				return account;
3288			}
3289		}
3290		return null;
3291	}
3292
3293	public Conversation findConversationByUuid(String uuid) {
3294		for (Conversation conversation : getConversations()) {
3295			if (conversation.getUuid().equals(uuid)) {
3296				return conversation;
3297			}
3298		}
3299		return null;
3300	}
3301
3302	public boolean markRead(final Conversation conversation) {
3303		return markRead(conversation,true);
3304	}
3305
3306	public boolean markRead(final Conversation conversation, boolean clear) {
3307		if (clear) {
3308			mNotificationService.clear(conversation);
3309		}
3310		final List<Message> readMessages = conversation.markRead();
3311		if (readMessages.size() > 0) {
3312			Runnable runnable = new Runnable() {
3313				@Override
3314				public void run() {
3315					for (Message message : readMessages) {
3316						databaseBackend.updateMessage(message);
3317					}
3318				}
3319			};
3320			mDatabaseExecutor.execute(runnable);
3321			updateUnreadCountBadge();
3322			return true;
3323		} else {
3324			return false;
3325		}
3326	}
3327
3328	public synchronized void updateUnreadCountBadge() {
3329		int count = unreadCount();
3330		if (unreadCount != count) {
3331			Log.d(Config.LOGTAG, "update unread count to " + count);
3332			if (count > 0) {
3333				ShortcutBadger.applyCount(getApplicationContext(), count);
3334			} else {
3335				ShortcutBadger.removeCount(getApplicationContext());
3336			}
3337			unreadCount = count;
3338		}
3339	}
3340
3341	public void sendReadMarker(final Conversation conversation) {
3342		final Message markable = conversation.getLatestMarkableMessage();
3343		if (this.markRead(conversation)) {
3344			updateConversationUi();
3345		}
3346		if (confirmMessages()
3347				&& markable != null
3348				&& markable.trusted()
3349				&& markable.getRemoteMsgId() != null) {
3350			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3351			Account account = conversation.getAccount();
3352			final Jid to = markable.getCounterpart();
3353			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
3354			this.sendMessagePacket(conversation.getAccount(), packet);
3355		}
3356	}
3357
3358	public SecureRandom getRNG() {
3359		return this.mRandom;
3360	}
3361
3362	public MemorizingTrustManager getMemorizingTrustManager() {
3363		return this.mMemorizingTrustManager;
3364	}
3365
3366	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3367		this.mMemorizingTrustManager = trustManager;
3368	}
3369
3370	public void updateMemorizingTrustmanager() {
3371		final MemorizingTrustManager tm;
3372		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
3373		if (dontTrustSystemCAs) {
3374			tm = new MemorizingTrustManager(getApplicationContext(), null);
3375		} else {
3376			tm = new MemorizingTrustManager(getApplicationContext());
3377		}
3378		setMemorizingTrustManager(tm);
3379	}
3380
3381	public PowerManager getPowerManager() {
3382		return this.pm;
3383	}
3384
3385	public LruCache<String, Bitmap> getBitmapCache() {
3386		return this.mBitmapCache;
3387	}
3388
3389	public void syncRosterToDisk(final Account account) {
3390		Runnable runnable = new Runnable() {
3391
3392			@Override
3393			public void run() {
3394				databaseBackend.writeRoster(account.getRoster());
3395			}
3396		};
3397		mDatabaseExecutor.execute(runnable);
3398
3399	}
3400
3401	public List<String> getKnownHosts() {
3402		final List<String> hosts = new ArrayList<>();
3403		for (final Account account : getAccounts()) {
3404			if (!hosts.contains(account.getServer().toString())) {
3405				hosts.add(account.getServer().toString());
3406			}
3407			for (final Contact contact : account.getRoster().getContacts()) {
3408				if (contact.showInRoster()) {
3409					final String server = contact.getServer().toString();
3410					if (server != null && !hosts.contains(server)) {
3411						hosts.add(server);
3412					}
3413				}
3414			}
3415		}
3416		if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3417			hosts.add(Config.DOMAIN_LOCK);
3418		}
3419		if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3420			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3421		}
3422		return hosts;
3423	}
3424
3425	public List<String> getKnownConferenceHosts() {
3426		final ArrayList<String> mucServers = new ArrayList<>();
3427		for (final Account account : accounts) {
3428			if (account.getXmppConnection() != null) {
3429				final String server = account.getXmppConnection().getMucServer();
3430				if (server != null && !mucServers.contains(server)) {
3431					mucServers.add(server);
3432				}
3433			}
3434		}
3435		return mucServers;
3436	}
3437
3438	public void sendMessagePacket(Account account, MessagePacket packet) {
3439		XmppConnection connection = account.getXmppConnection();
3440		if (connection != null) {
3441			connection.sendMessagePacket(packet);
3442		}
3443	}
3444
3445	public void sendPresencePacket(Account account, PresencePacket packet) {
3446		XmppConnection connection = account.getXmppConnection();
3447		if (connection != null) {
3448			connection.sendPresencePacket(packet);
3449		}
3450	}
3451
3452	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3453		final XmppConnection connection = account.getXmppConnection();
3454		if (connection != null) {
3455			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3456			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3457		}
3458	}
3459
3460	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3461		final XmppConnection connection = account.getXmppConnection();
3462		if (connection != null) {
3463			connection.sendIqPacket(packet, callback);
3464		}
3465	}
3466
3467	public void sendPresence(final Account account) {
3468		sendPresence(account, checkListeners() && broadcastLastActivity());
3469	}
3470
3471	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3472		PresencePacket packet;
3473		if (manuallyChangePresence()) {
3474			packet =  mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3475			String message = account.getPresenceStatusMessage();
3476			if (message != null && !message.isEmpty()) {
3477				packet.addChild(new Element("status").setContent(message));
3478			}
3479		} else {
3480			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3481		}
3482		if (mLastActivity > 0 && includeIdleTimestamp) {
3483			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3484			packet.addChild("idle","urn:xmpp:idle:1").setAttribute("since", AbstractGenerator.getTimestamp(since));
3485		}
3486		sendPresencePacket(account, packet);
3487	}
3488
3489	private void deactivateGracePeriod() {
3490		for(Account account : getAccounts()) {
3491			account.deactivateGracePeriod();
3492		}
3493	}
3494
3495	public void refreshAllPresences() {
3496		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3497		for (Account account : getAccounts()) {
3498			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3499				sendPresence(account, includeIdleTimestamp);
3500			}
3501		}
3502	}
3503
3504	private void refreshAllGcmTokens() {
3505		for(Account account : getAccounts()) {
3506			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3507				mPushManagementService.registerPushTokenOnServer(account);
3508			}
3509		}
3510	}
3511
3512	private void sendOfflinePresence(final Account account) {
3513		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending offline presence");
3514		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3515	}
3516
3517	public MessageGenerator getMessageGenerator() {
3518		return this.mMessageGenerator;
3519	}
3520
3521	public PresenceGenerator getPresenceGenerator() {
3522		return this.mPresenceGenerator;
3523	}
3524
3525	public IqGenerator getIqGenerator() {
3526		return this.mIqGenerator;
3527	}
3528
3529	public IqParser getIqParser() {
3530		return this.mIqParser;
3531	}
3532
3533	public JingleConnectionManager getJingleConnectionManager() {
3534		return this.mJingleConnectionManager;
3535	}
3536
3537	public MessageArchiveService getMessageArchiveService() {
3538		return this.mMessageArchiveService;
3539	}
3540
3541	public List<Contact> findContacts(Jid jid) {
3542		ArrayList<Contact> contacts = new ArrayList<>();
3543		for (Account account : getAccounts()) {
3544			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3545				Contact contact = account.getRoster().getContactFromRoster(jid);
3546				if (contact != null) {
3547					contacts.add(contact);
3548				}
3549			}
3550		}
3551		return contacts;
3552	}
3553
3554	public Conversation findFirstMuc(Jid jid) {
3555		for(Conversation conversation : getConversations()) {
3556			if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3557					&& conversation.getMode() == Conversation.MODE_MULTI) {
3558				return conversation;
3559			}
3560		}
3561		return null;
3562	}
3563
3564	public NotificationService getNotificationService() {
3565		return this.mNotificationService;
3566	}
3567
3568	public HttpConnectionManager getHttpConnectionManager() {
3569		return this.mHttpConnectionManager;
3570	}
3571
3572	public void resendFailedMessages(final Message message) {
3573		final Collection<Message> messages = new ArrayList<>();
3574		Message current = message;
3575		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3576			messages.add(current);
3577			if (current.mergeable(current.next())) {
3578				current = current.next();
3579			} else {
3580				break;
3581			}
3582		}
3583		for (final Message msg : messages) {
3584			msg.setTime(System.currentTimeMillis());
3585			markMessage(msg, Message.STATUS_WAITING);
3586			this.resendMessage(msg, false);
3587		}
3588	}
3589
3590	public void clearConversationHistory(final Conversation conversation) {
3591		conversation.clearMessages();
3592		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3593		conversation.setLastClearHistory(System.currentTimeMillis());
3594		Runnable runnable = new Runnable() {
3595			@Override
3596			public void run() {
3597				databaseBackend.deleteMessagesInConversation(conversation);
3598				databaseBackend.updateConversation(conversation);
3599			}
3600		};
3601		mDatabaseExecutor.execute(runnable);
3602	}
3603
3604	public void sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3605		if (blockable != null && blockable.getBlockedJid() != null) {
3606			final Jid jid = blockable.getBlockedJid();
3607			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3608
3609				@Override
3610				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3611					if (packet.getType() == IqPacket.TYPE.RESULT) {
3612						account.getBlocklist().add(jid);
3613						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3614					}
3615				}
3616			});
3617		}
3618	}
3619
3620	public void sendUnblockRequest(final Blockable blockable) {
3621		if (blockable != null && blockable.getJid() != null) {
3622			final Jid jid = blockable.getBlockedJid();
3623			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3624				@Override
3625				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3626					if (packet.getType() == IqPacket.TYPE.RESULT) {
3627						account.getBlocklist().remove(jid);
3628						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3629					}
3630				}
3631			});
3632		}
3633	}
3634
3635	public void publishDisplayName(Account account) {
3636		String displayName = account.getDisplayName();
3637		if (displayName != null && !displayName.isEmpty()) {
3638			IqPacket publish = mIqGenerator.publishNick(displayName);
3639			sendIqPacket(account, publish, new OnIqPacketReceived() {
3640				@Override
3641				public void onIqPacketReceived(Account account, IqPacket packet) {
3642					if (packet.getType() == IqPacket.TYPE.ERROR) {
3643						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3644					}
3645				}
3646			});
3647		}
3648	}
3649
3650	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3651		ServiceDiscoveryResult result = discoCache.get(key);
3652		if (result != null) {
3653			return result;
3654		} else {
3655			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3656			if (result != null) {
3657				discoCache.put(key, result);
3658			}
3659			return result;
3660		}
3661	}
3662
3663	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3664		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3665		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3666		if (disco != null) {
3667			presence.setServiceDiscoveryResult(disco);
3668		} else {
3669			if (!account.inProgressDiscoFetches.contains(key)) {
3670				account.inProgressDiscoFetches.add(key);
3671				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3672				request.setTo(jid);
3673				request.query("http://jabber.org/protocol/disco#info");
3674				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3675				sendIqPacket(account, request, new OnIqPacketReceived() {
3676					@Override
3677					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3678						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3679							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3680							if (presence.getVer().equals(disco.getVer())) {
3681								databaseBackend.insertDiscoveryResult(disco);
3682								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3683							} else {
3684								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3685							}
3686						}
3687						account.inProgressDiscoFetches.remove(key);
3688					}
3689				});
3690			}
3691		}
3692	}
3693
3694	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3695		for(Contact contact : roster.getContacts()) {
3696			for(Presence presence : contact.getPresences().getPresences().values()) {
3697				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3698					presence.setServiceDiscoveryResult(disco);
3699				}
3700			}
3701		}
3702	}
3703
3704	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3705		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3706		request.addChild("prefs","urn:xmpp:mam:0");
3707		sendIqPacket(account, request, new OnIqPacketReceived() {
3708			@Override
3709			public void onIqPacketReceived(Account account, IqPacket packet) {
3710				Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3711				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3712					callback.onPreferencesFetched(prefs);
3713				} else {
3714					callback.onPreferencesFetchFailed();
3715				}
3716			}
3717		});
3718	}
3719
3720	public PushManagementService getPushManagementService() {
3721		return mPushManagementService;
3722	}
3723
3724	public Account getPendingAccount() {
3725		Account pending = null;
3726		for(Account account : getAccounts()) {
3727			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3728				pending = account;
3729			} else {
3730				return null;
3731			}
3732		}
3733		return pending;
3734	}
3735
3736	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3737		if (!statusMessage.isEmpty()) {
3738			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3739		}
3740		changeStatusReal(account, status, statusMessage, send);
3741	}
3742
3743	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3744		account.setPresenceStatus(status);
3745		account.setPresenceStatusMessage(statusMessage);
3746		databaseBackend.updateAccount(account);
3747		if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3748			sendPresence(account);
3749		}
3750	}
3751
3752	public void changeStatus(Presence.Status status, String statusMessage) {
3753		if (!statusMessage.isEmpty()) {
3754			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3755		}
3756		for(Account account : getAccounts()) {
3757			changeStatusReal(account, status, statusMessage, true);
3758		}
3759	}
3760
3761	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3762		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3763		for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3764			if (!templates.contains(template)) {
3765				templates.add(0, template);
3766			}
3767		}
3768		return templates;
3769	}
3770
3771	public void saveConversationAsBookmark(Conversation conversation, String name) {
3772		Account account = conversation.getAccount();
3773		Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3774		if (!conversation.getJid().isBareJid()) {
3775			bookmark.setNick(conversation.getJid().getResourcepart());
3776		}
3777		if (name != null && !name.trim().isEmpty()) {
3778			bookmark.setBookmarkName(name.trim());
3779		}
3780		bookmark.setAutojoin(getPreferences().getBoolean("autojoin",true));
3781		account.getBookmarks().add(bookmark);
3782		pushBookmarks(account);
3783		conversation.setBookmark(bookmark);
3784	}
3785
3786	public void clearStartTimeCounter() {
3787		mDatabaseExecutor.execute(new Runnable() {
3788			@Override
3789			public void run() {
3790				databaseBackend.clearStartTimeCounter(false);
3791			}
3792		});
3793	}
3794
3795	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3796		boolean needsRosterWrite = false;
3797		boolean performedVerification = false;
3798		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3799		for(XmppUri.Fingerprint fp : fingerprints) {
3800			if (fp.type == XmppUri.FingerprintType.OTR) {
3801				performedVerification |= contact.addOtrFingerprint(fp.fingerprint);
3802				needsRosterWrite |= performedVerification;
3803			} else if (fp.type == XmppUri.FingerprintType.OMEMO) {
3804				String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3805				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3806				if (fingerprintStatus != null) {
3807					if (!fingerprintStatus.isVerified()) {
3808						performedVerification = true;
3809						axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3810					}
3811				} else {
3812					axolotlService.preVerifyFingerprint(contact,fingerprint);
3813				}
3814			}
3815		}
3816		if (needsRosterWrite) {
3817			syncRosterToDisk(contact.getAccount());
3818		}
3819		return performedVerification;
3820	}
3821
3822	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3823		final AxolotlService axolotlService = account.getAxolotlService();
3824		boolean verifiedSomething = false;
3825		for(XmppUri.Fingerprint fp : fingerprints) {
3826			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3827				String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3828				Log.d(Config.LOGTAG,"trying to verify own fp="+fingerprint);
3829				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3830				if (fingerprintStatus != null) {
3831					if (!fingerprintStatus.isVerified()) {
3832						axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3833						verifiedSomething = true;
3834					}
3835				} else {
3836					axolotlService.preVerifyFingerprint(account,fingerprint);
3837					verifiedSomething = true;
3838				}
3839			}
3840		}
3841		return verifiedSomething;
3842	}
3843
3844	public boolean blindTrustBeforeVerification() {
3845		return getPreferences().getBoolean(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, true);
3846	}
3847
3848	public interface OnMamPreferencesFetched {
3849		void onPreferencesFetched(Element prefs);
3850		void onPreferencesFetchFailed();
3851	}
3852
3853	public void pushMamPreferences(Account account, Element prefs) {
3854		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3855		set.addChild(prefs);
3856		sendIqPacket(account, set, null);
3857	}
3858
3859	public interface OnAccountCreated {
3860		void onAccountCreated(Account account);
3861
3862		void informUser(int r);
3863	}
3864
3865	public interface OnMoreMessagesLoaded {
3866		void onMoreMessagesLoaded(int count, Conversation conversation);
3867
3868		void informUser(int r);
3869	}
3870
3871	public interface OnAccountPasswordChanged {
3872		void onPasswordChangeSucceeded();
3873
3874		void onPasswordChangeFailed();
3875	}
3876
3877	public interface OnAffiliationChanged {
3878		void onAffiliationChangedSuccessful(Jid jid);
3879
3880		void onAffiliationChangeFailed(Jid jid, int resId);
3881	}
3882
3883	public interface OnRoleChanged {
3884		void onRoleChangedSuccessful(String nick);
3885
3886		void onRoleChangeFailed(String nick, int resid);
3887	}
3888
3889	public interface OnConversationUpdate {
3890		void onConversationUpdate();
3891	}
3892
3893	public interface OnAccountUpdate {
3894		void onAccountUpdate();
3895	}
3896
3897	public interface OnCaptchaRequested {
3898		void onCaptchaRequested(Account account,
3899								String id,
3900								Data data,
3901								Bitmap captcha);
3902	}
3903
3904	public interface OnRosterUpdate {
3905		void onRosterUpdate();
3906	}
3907
3908	public interface OnMucRosterUpdate {
3909		void onMucRosterUpdate();
3910	}
3911
3912	public interface OnConferenceConfigurationFetched {
3913		void onConferenceConfigurationFetched(Conversation conversation);
3914
3915		void onFetchFailed(Conversation conversation, Element error);
3916	}
3917
3918	public interface OnConferenceJoined {
3919		void onConferenceJoined(Conversation conversation);
3920	}
3921
3922	public interface OnConferenceOptionsPushed {
3923		void onPushSucceeded();
3924
3925		void onPushFailed();
3926	}
3927
3928	public interface OnShowErrorToast {
3929		void onShowErrorToast(int resId);
3930	}
3931
3932	public class XmppConnectionBinder extends Binder {
3933		public XmppConnectionService getService() {
3934			return XmppConnectionService.this;
3935		}
3936	}
3937}