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