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