XmppConnectionService.java

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