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					markRead(c, true);
 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 (Conversation conversation : this.conversations) {
1454				Account account = accountLookupTable.get(conversation.getAccountUuid());
1455				conversation.setAccount(account);
1456			}
1457			Runnable runnable = new Runnable() {
1458				@Override
1459				public void run() {
1460					long deletionDate = getAutomaticMessageDeletionDate();
1461					mLastExpiryRun.set(SystemClock.elapsedRealtime());
1462					if (deletionDate > 0) {
1463						Log.d(Config.LOGTAG, "deleting messages that are older than "+AbstractGenerator.getTimestamp(deletionDate));
1464						databaseBackend.expireOldMessages(deletionDate);
1465					}
1466					Log.d(Config.LOGTAG, "restoring roster");
1467					for (Account account : accounts) {
1468						databaseBackend.readRoster(account.getRoster());
1469						account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1470					}
1471					getBitmapCache().evictAll();
1472					loadPhoneContacts();
1473					Log.d(Config.LOGTAG, "restoring messages");
1474					for (Conversation conversation : conversations) {
1475						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1476						checkDeletedFiles(conversation);
1477						conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
1478
1479							@Override
1480							public void onMessageFound(Message message) {
1481								markMessage(message, Message.STATUS_WAITING);
1482							}
1483						});
1484						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1485							@Override
1486							public void onMessageFound(Message message) {
1487								mNotificationService.pushFromBacklog(message);
1488							}
1489						});
1490					}
1491					mNotificationService.finishBacklog(false);
1492					mRestoredFromDatabase = true;
1493					Log.d(Config.LOGTAG, "restored all messages");
1494					updateConversationUi();
1495				}
1496			};
1497			mDatabaseExecutor.execute(runnable);
1498		}
1499	}
1500
1501	public void loadPhoneContacts() {
1502		mContactMergerExecutor.execute(new Runnable() {
1503			@Override
1504			public void run() {
1505				PhoneHelper.loadPhoneContacts(XmppConnectionService.this, new OnPhoneContactsLoadedListener() {
1506					@Override
1507					public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
1508						Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1509						for (Account account : accounts) {
1510							List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1511							for (Bundle phoneContact : phoneContacts) {
1512								Jid jid;
1513								try {
1514									jid = Jid.fromString(phoneContact.getString("jid"));
1515								} catch (final InvalidJidException e) {
1516									continue;
1517								}
1518								final Contact contact = account.getRoster().getContact(jid);
1519								String systemAccount = phoneContact.getInt("phoneid")
1520										+ "#"
1521										+ phoneContact.getString("lookup");
1522								contact.setSystemAccount(systemAccount);
1523								boolean needsCacheClean = contact.setPhotoUri(phoneContact.getString("photouri"));
1524								needsCacheClean |= contact.setSystemName(phoneContact.getString("displayname"));
1525								if (needsCacheClean) {
1526									getAvatarService().clear(contact);
1527								}
1528								withSystemAccounts.remove(contact);
1529							}
1530							for (Contact contact : withSystemAccounts) {
1531								contact.setSystemAccount(null);
1532								boolean needsCacheClean = contact.setPhotoUri(null);
1533								needsCacheClean |= contact.setSystemName(null);
1534								if (needsCacheClean) {
1535									getAvatarService().clear(contact);
1536								}
1537							}
1538						}
1539						Log.d(Config.LOGTAG, "finished merging phone contacts");
1540						updateAccountUi();
1541					}
1542				});
1543			}
1544		});
1545	}
1546
1547	public List<Conversation> getConversations() {
1548		return this.conversations;
1549	}
1550
1551	private void checkDeletedFiles(Conversation conversation) {
1552		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1553
1554			@Override
1555			public void onMessageFound(Message message) {
1556				if (!getFileBackend().isFileAvailable(message)) {
1557					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1558					final int s = message.getStatus();
1559					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1560						markMessage(message, Message.STATUS_SEND_FAILED);
1561					}
1562				}
1563			}
1564		});
1565	}
1566
1567	private void markFileDeleted(final String path) {
1568		Log.d(Config.LOGTAG,"deleted file "+path);
1569		for (Conversation conversation : getConversations()) {
1570			conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1571				@Override
1572				public void onMessageFound(Message message) {
1573					DownloadableFile file = fileBackend.getFile(message);
1574					if (file.getAbsolutePath().equals(path)) {
1575						if (!file.exists()) {
1576							message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1577							final int s = message.getStatus();
1578							if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1579								markMessage(message, Message.STATUS_SEND_FAILED);
1580							} else {
1581								updateConversationUi();
1582							}
1583						} else {
1584							Log.d(Config.LOGTAG,"found matching message for file "+path+" but file still exists");
1585						}
1586					}
1587				}
1588			});
1589		}
1590	}
1591
1592	public void populateWithOrderedConversations(final List<Conversation> list) {
1593		populateWithOrderedConversations(list, true);
1594	}
1595
1596	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1597		list.clear();
1598		if (includeNoFileUpload) {
1599			list.addAll(getConversations());
1600		} else {
1601			for (Conversation conversation : getConversations()) {
1602				if (conversation.getMode() == Conversation.MODE_SINGLE
1603						|| conversation.getAccount().httpUploadAvailable()) {
1604					list.add(conversation);
1605				}
1606			}
1607		}
1608		try {
1609			Collections.sort(list);
1610		} catch (IllegalArgumentException e) {
1611			//ignore
1612		}
1613	}
1614
1615	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1616		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1617			return;
1618		} else if (timestamp == 0) {
1619			return;
1620		}
1621		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1622		Runnable runnable = new Runnable() {
1623			@Override
1624			public void run() {
1625				final Account account = conversation.getAccount();
1626				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1627				if (messages.size() > 0) {
1628					conversation.addAll(0, messages);
1629					checkDeletedFiles(conversation);
1630					callback.onMoreMessagesLoaded(messages.size(), conversation);
1631				} else if (conversation.hasMessagesLeftOnServer()
1632						&& account.isOnlineAndConnected()
1633						&& conversation.getLastClearHistory() == 0) {
1634					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1635							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1636						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1637						if (query != null) {
1638							query.setCallback(callback);
1639							callback.informUser(R.string.fetching_history_from_server);
1640						} else {
1641							callback.informUser(R.string.not_fetching_history_retention_period);
1642						}
1643
1644					}
1645				}
1646			}
1647		};
1648		mDatabaseExecutor.execute(runnable);
1649	}
1650
1651	public List<Account> getAccounts() {
1652		return this.accounts;
1653	}
1654
1655	public List<Conversation> findAllConferencesWith(Contact contact) {
1656		ArrayList<Conversation> results = new ArrayList<>();
1657		for(Conversation conversation : conversations) {
1658			if (conversation.getMode() == Conversation.MODE_MULTI
1659					&& conversation.getMucOptions().isContactInRoom(contact)) {
1660				results.add(conversation);
1661			}
1662		}
1663		return results;
1664	}
1665
1666	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1667		for (final Conversation conversation : haystack) {
1668			if (conversation.getContact() == contact) {
1669				return conversation;
1670			}
1671		}
1672		return null;
1673	}
1674
1675	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1676		if (jid == null) {
1677			return null;
1678		}
1679		for (final Conversation conversation : haystack) {
1680			if ((account == null || conversation.getAccount() == account)
1681					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1682				return conversation;
1683			}
1684		}
1685		return null;
1686	}
1687
1688	public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1689		return this.findOrCreateConversation(account,jid,muc,false, async);
1690	}
1691
1692	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1693		return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1694	}
1695
1696	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1697		synchronized (this.conversations) {
1698			Conversation conversation = find(account, jid);
1699			if (conversation != null) {
1700				return conversation;
1701			}
1702			conversation = databaseBackend.findConversation(account, jid);
1703			final boolean loadMessagesFromDb;
1704			if (conversation != null) {
1705				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1706				conversation.setAccount(account);
1707				if (muc) {
1708					conversation.setMode(Conversation.MODE_MULTI);
1709					conversation.setContactJid(jid);
1710				} else {
1711					conversation.setMode(Conversation.MODE_SINGLE);
1712					conversation.setContactJid(jid.toBareJid());
1713				}
1714				databaseBackend.updateConversation(conversation);
1715				loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true,false);
1716			} else {
1717				String conversationName;
1718				Contact contact = account.getRoster().getContact(jid);
1719				if (contact != null) {
1720					conversationName = contact.getDisplayName();
1721				} else {
1722					conversationName = jid.getLocalpart();
1723				}
1724				if (muc) {
1725					conversation = new Conversation(conversationName, account, jid,
1726							Conversation.MODE_MULTI);
1727				} else {
1728					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1729							Conversation.MODE_SINGLE);
1730				}
1731				this.databaseBackend.createConversation(conversation);
1732				loadMessagesFromDb = false;
1733			}
1734			final Conversation c = conversation;
1735			final Runnable runnable = new Runnable() {
1736				@Override
1737				public void run() {
1738					if (loadMessagesFromDb) {
1739						c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1740						updateConversationUi();
1741						c.messagesLoaded.set(true);
1742					}
1743					if (account.getXmppConnection() != null
1744							&& account.getXmppConnection().getFeatures().mam()
1745							&& !muc) {
1746						if (query == null) {
1747							mMessageArchiveService.query(c);
1748						} else {
1749							if (query.getConversation() == null) {
1750								mMessageArchiveService.query(c, query.getStart());
1751							}
1752						}
1753					}
1754					checkDeletedFiles(c);
1755					if (joinAfterCreate) {
1756						joinMuc(c);
1757					}
1758				}
1759			};
1760			if (async) {
1761				mDatabaseExecutor.execute(runnable);
1762			} else {
1763				runnable.run();
1764			}
1765			this.conversations.add(conversation);
1766			updateConversationUi();
1767			return conversation;
1768		}
1769	}
1770
1771	public void archiveConversation(Conversation conversation) {
1772		getNotificationService().clear(conversation);
1773		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1774		synchronized (this.conversations) {
1775			if (conversation.getMode() == Conversation.MODE_MULTI) {
1776				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1777					Bookmark bookmark = conversation.getBookmark();
1778					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1779						bookmark.setAutojoin(false);
1780						pushBookmarks(bookmark.getAccount());
1781					}
1782				}
1783				leaveMuc(conversation);
1784			} else {
1785				conversation.endOtrIfNeeded();
1786				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1787					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1788					sendPresencePacket(
1789							conversation.getAccount(),
1790							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1791					);
1792				}
1793			}
1794			updateConversation(conversation);
1795			this.conversations.remove(conversation);
1796			updateConversationUi();
1797		}
1798	}
1799
1800	public void createAccount(final Account account) {
1801		account.initAccountServices(this);
1802		databaseBackend.createAccount(account);
1803		this.accounts.add(account);
1804		this.reconnectAccountInBackground(account);
1805		updateAccountUi();
1806	}
1807
1808	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1809		new Thread(new Runnable() {
1810			@Override
1811			public void run() {
1812				try {
1813					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1814					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1815					if (findAccountByJid(info.first) == null) {
1816						Account account = new Account(info.first, "");
1817						account.setPrivateKeyAlias(alias);
1818						account.setOption(Account.OPTION_DISABLED, true);
1819						account.setDisplayName(info.second);
1820						createAccount(account);
1821						callback.onAccountCreated(account);
1822						if (Config.X509_VERIFICATION) {
1823							try {
1824								getMemorizingTrustManager().getNonInteractive(account.getJid().getDomainpart()).checkClientTrusted(chain, "RSA");
1825							} catch (CertificateException e) {
1826								callback.informUser(R.string.certificate_chain_is_not_trusted);
1827							}
1828						}
1829					} else {
1830						callback.informUser(R.string.account_already_exists);
1831					}
1832				} catch (Exception e) {
1833					e.printStackTrace();
1834					callback.informUser(R.string.unable_to_parse_certificate);
1835				}
1836			}
1837		}).start();
1838
1839	}
1840
1841	public void updateKeyInAccount(final Account account, final String alias) {
1842		Log.d(Config.LOGTAG, account.getJid().toBareJid()+": update key in account " + alias);
1843		try {
1844			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1845			Log.d(Config.LOGTAG,account.getJid().toBareJid()+" loaded certificate chain");
1846			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1847			if (account.getJid().toBareJid().equals(info.first)) {
1848				account.setPrivateKeyAlias(alias);
1849				account.setDisplayName(info.second);
1850				databaseBackend.updateAccount(account);
1851				if (Config.X509_VERIFICATION) {
1852					try {
1853						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1854					} catch (CertificateException e) {
1855						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1856					}
1857					account.getAxolotlService().regenerateKeys(true);
1858				}
1859			} else {
1860				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1861			}
1862		} catch (Exception e) {
1863			e.printStackTrace();
1864		}
1865	}
1866
1867	public boolean updateAccount(final Account account) {
1868		if (databaseBackend.updateAccount(account)) {
1869			account.setShowErrorNotification(true);
1870			this.statusListener.onStatusChanged(account);
1871			databaseBackend.updateAccount(account);
1872			reconnectAccountInBackground(account);
1873			updateAccountUi();
1874			getNotificationService().updateErrorNotification();
1875			return true;
1876		} else {
1877			return false;
1878		}
1879	}
1880
1881	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1882		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1883		sendIqPacket(account, iq, new OnIqPacketReceived() {
1884			@Override
1885			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1886				if (packet.getType() == IqPacket.TYPE.RESULT) {
1887					account.setPassword(newPassword);
1888					account.setOption(Account.OPTION_MAGIC_CREATE, false);
1889					databaseBackend.updateAccount(account);
1890					callback.onPasswordChangeSucceeded();
1891				} else {
1892					callback.onPasswordChangeFailed();
1893				}
1894			}
1895		});
1896	}
1897
1898	public void deleteAccount(final Account account) {
1899		synchronized (this.conversations) {
1900			for (final Conversation conversation : conversations) {
1901				if (conversation.getAccount() == account) {
1902					if (conversation.getMode() == Conversation.MODE_MULTI) {
1903						leaveMuc(conversation);
1904					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1905						conversation.endOtrIfNeeded();
1906					}
1907					conversations.remove(conversation);
1908				}
1909			}
1910			if (account.getXmppConnection() != null) {
1911				new Thread(new Runnable() {
1912					@Override
1913					public void run() {
1914						disconnect(account, true);
1915					}
1916				}).start();
1917			}
1918			Runnable runnable = new Runnable() {
1919				@Override
1920				public void run() {
1921					if (!databaseBackend.deleteAccount(account)) {
1922						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": unable to delete account");
1923					}
1924				}
1925			};
1926			mDatabaseExecutor.execute(runnable);
1927			this.accounts.remove(account);
1928			updateAccountUi();
1929			getNotificationService().updateErrorNotification();
1930		}
1931	}
1932
1933	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1934		synchronized (this) {
1935			this.mLastActivity = System.currentTimeMillis();
1936			if (checkListeners()) {
1937				switchToForeground();
1938			}
1939			this.mOnConversationUpdate = listener;
1940			this.mNotificationService.setIsInForeground(true);
1941			if (this.convChangedListenerCount < 2) {
1942				this.convChangedListenerCount++;
1943			}
1944		}
1945	}
1946
1947	public void removeOnConversationListChangedListener() {
1948		synchronized (this) {
1949			this.convChangedListenerCount--;
1950			if (this.convChangedListenerCount <= 0) {
1951				this.convChangedListenerCount = 0;
1952				this.mOnConversationUpdate = null;
1953				this.mNotificationService.setIsInForeground(false);
1954				if (checkListeners()) {
1955					switchToBackground();
1956				}
1957			}
1958		}
1959	}
1960
1961	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1962		synchronized (this) {
1963			if (checkListeners()) {
1964				switchToForeground();
1965			}
1966			this.mOnShowErrorToast = onShowErrorToast;
1967			if (this.showErrorToastListenerCount < 2) {
1968				this.showErrorToastListenerCount++;
1969			}
1970		}
1971		this.mOnShowErrorToast = onShowErrorToast;
1972	}
1973
1974	public void removeOnShowErrorToastListener() {
1975		synchronized (this) {
1976			this.showErrorToastListenerCount--;
1977			if (this.showErrorToastListenerCount <= 0) {
1978				this.showErrorToastListenerCount = 0;
1979				this.mOnShowErrorToast = null;
1980				if (checkListeners()) {
1981					switchToBackground();
1982				}
1983			}
1984		}
1985	}
1986
1987	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1988		synchronized (this) {
1989			if (checkListeners()) {
1990				switchToForeground();
1991			}
1992			this.mOnAccountUpdate = listener;
1993			if (this.accountChangedListenerCount < 2) {
1994				this.accountChangedListenerCount++;
1995			}
1996		}
1997	}
1998
1999	public void removeOnAccountListChangedListener() {
2000		synchronized (this) {
2001			this.accountChangedListenerCount--;
2002			if (this.accountChangedListenerCount <= 0) {
2003				this.mOnAccountUpdate = null;
2004				this.accountChangedListenerCount = 0;
2005				if (checkListeners()) {
2006					switchToBackground();
2007				}
2008			}
2009		}
2010	}
2011
2012	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2013		synchronized (this) {
2014			if (checkListeners()) {
2015				switchToForeground();
2016			}
2017			this.mOnCaptchaRequested = listener;
2018			if (this.captchaRequestedListenerCount < 2) {
2019				this.captchaRequestedListenerCount++;
2020			}
2021		}
2022	}
2023
2024	public void removeOnCaptchaRequestedListener() {
2025		synchronized (this) {
2026			this.captchaRequestedListenerCount--;
2027			if (this.captchaRequestedListenerCount <= 0) {
2028				this.mOnCaptchaRequested = null;
2029				this.captchaRequestedListenerCount = 0;
2030				if (checkListeners()) {
2031					switchToBackground();
2032				}
2033			}
2034		}
2035	}
2036
2037	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2038		synchronized (this) {
2039			if (checkListeners()) {
2040				switchToForeground();
2041			}
2042			this.mOnRosterUpdate = listener;
2043			if (this.rosterChangedListenerCount < 2) {
2044				this.rosterChangedListenerCount++;
2045			}
2046		}
2047	}
2048
2049	public void removeOnRosterUpdateListener() {
2050		synchronized (this) {
2051			this.rosterChangedListenerCount--;
2052			if (this.rosterChangedListenerCount <= 0) {
2053				this.rosterChangedListenerCount = 0;
2054				this.mOnRosterUpdate = null;
2055				if (checkListeners()) {
2056					switchToBackground();
2057				}
2058			}
2059		}
2060	}
2061
2062	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2063		synchronized (this) {
2064			if (checkListeners()) {
2065				switchToForeground();
2066			}
2067			this.mOnUpdateBlocklist = listener;
2068			if (this.updateBlocklistListenerCount < 2) {
2069				this.updateBlocklistListenerCount++;
2070			}
2071		}
2072	}
2073
2074	public void removeOnUpdateBlocklistListener() {
2075		synchronized (this) {
2076			this.updateBlocklistListenerCount--;
2077			if (this.updateBlocklistListenerCount <= 0) {
2078				this.updateBlocklistListenerCount = 0;
2079				this.mOnUpdateBlocklist = null;
2080				if (checkListeners()) {
2081					switchToBackground();
2082				}
2083			}
2084		}
2085	}
2086
2087	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2088		synchronized (this) {
2089			if (checkListeners()) {
2090				switchToForeground();
2091			}
2092			this.mOnKeyStatusUpdated = listener;
2093			if (this.keyStatusUpdatedListenerCount < 2) {
2094				this.keyStatusUpdatedListenerCount++;
2095			}
2096		}
2097	}
2098
2099	public void removeOnNewKeysAvailableListener() {
2100		synchronized (this) {
2101			this.keyStatusUpdatedListenerCount--;
2102			if (this.keyStatusUpdatedListenerCount <= 0) {
2103				this.keyStatusUpdatedListenerCount = 0;
2104				this.mOnKeyStatusUpdated = null;
2105				if (checkListeners()) {
2106					switchToBackground();
2107				}
2108			}
2109		}
2110	}
2111
2112	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2113		synchronized (this) {
2114			if (checkListeners()) {
2115				switchToForeground();
2116			}
2117			this.mOnMucRosterUpdate = listener;
2118			if (this.mucRosterChangedListenerCount < 2) {
2119				this.mucRosterChangedListenerCount++;
2120			}
2121		}
2122	}
2123
2124	public void removeOnMucRosterUpdateListener() {
2125		synchronized (this) {
2126			this.mucRosterChangedListenerCount--;
2127			if (this.mucRosterChangedListenerCount <= 0) {
2128				this.mucRosterChangedListenerCount = 0;
2129				this.mOnMucRosterUpdate = null;
2130				if (checkListeners()) {
2131					switchToBackground();
2132				}
2133			}
2134		}
2135	}
2136
2137	public boolean checkListeners() {
2138		return (this.mOnAccountUpdate == null
2139				&& this.mOnConversationUpdate == null
2140				&& this.mOnRosterUpdate == null
2141				&& this.mOnCaptchaRequested == null
2142				&& this.mOnUpdateBlocklist == null
2143				&& this.mOnShowErrorToast == null
2144				&& this.mOnKeyStatusUpdated == null);
2145	}
2146
2147	private void switchToForeground() {
2148		final boolean broadcastLastActivity = broadcastLastActivity();
2149		for (Conversation conversation : getConversations()) {
2150			if (conversation.getMode() == Conversation.MODE_MULTI) {
2151				conversation.getMucOptions().resetChatState();
2152			} else {
2153				conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2154			}
2155		}
2156		for (Account account : getAccounts()) {
2157			if (account.getStatus() == Account.State.ONLINE) {
2158				account.deactivateGracePeriod();
2159				final XmppConnection connection = account.getXmppConnection();
2160				if (connection != null ) {
2161					if (connection.getFeatures().csi()) {
2162						connection.sendActive();
2163					}
2164					if (broadcastLastActivity) {
2165						sendPresence(account, false); //send new presence but don't include idle because we are not
2166					}
2167				}
2168			}
2169		}
2170		Log.d(Config.LOGTAG, "app switched into foreground");
2171	}
2172
2173	private void switchToBackground() {
2174		final boolean broadcastLastActivity = broadcastLastActivity();
2175		for (Account account : getAccounts()) {
2176			if (account.getStatus() == Account.State.ONLINE) {
2177				XmppConnection connection = account.getXmppConnection();
2178				if (connection != null) {
2179					if (broadcastLastActivity) {
2180						sendPresence(account, broadcastLastActivity);
2181					}
2182					if (connection.getFeatures().csi()) {
2183						connection.sendInactive();
2184					}
2185				}
2186			}
2187		}
2188		this.mNotificationService.setIsInForeground(false);
2189		Log.d(Config.LOGTAG, "app switched into background");
2190	}
2191
2192	private void connectMultiModeConversations(Account account) {
2193		List<Conversation> conversations = getConversations();
2194		for (Conversation conversation : conversations) {
2195			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2196				joinMuc(conversation);
2197			}
2198		}
2199	}
2200
2201	public void joinMuc(Conversation conversation) {
2202		joinMuc(conversation,null, false);
2203	}
2204
2205	public void joinMuc(Conversation conversation, boolean followedInvite) {
2206		joinMuc(conversation, null, followedInvite);
2207	}
2208
2209	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2210		joinMuc(conversation,onConferenceJoined,false);
2211	}
2212
2213	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2214		Account account = conversation.getAccount();
2215		account.pendingConferenceJoins.remove(conversation);
2216		account.pendingConferenceLeaves.remove(conversation);
2217		if (account.getStatus() == Account.State.ONLINE) {
2218			conversation.resetMucOptions();
2219			if (onConferenceJoined != null) {
2220				conversation.getMucOptions().flagNoAutoPushConfiguration();
2221			}
2222			conversation.setHasMessagesLeftOnServer(false);
2223			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2224
2225				private void join(Conversation conversation) {
2226					Account account = conversation.getAccount();
2227					final MucOptions mucOptions = conversation.getMucOptions();
2228					final Jid joinJid = mucOptions.getSelf().getFullJid();
2229					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
2230					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
2231					packet.setTo(joinJid);
2232					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2233					if (conversation.getMucOptions().getPassword() != null) {
2234						x.addChild("password").setContent(mucOptions.getPassword());
2235					}
2236
2237					if (mucOptions.mamSupport()) {
2238						// Use MAM instead of the limited muc history to get history
2239						x.addChild("history").setAttribute("maxchars", "0");
2240					} else {
2241						// Fallback to muc history
2242						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
2243					}
2244					sendPresencePacket(account, packet);
2245					if (onConferenceJoined != null) {
2246						onConferenceJoined.onConferenceJoined(conversation);
2247					}
2248					if (!joinJid.equals(conversation.getJid())) {
2249						conversation.setContactJid(joinJid);
2250						databaseBackend.updateConversation(conversation);
2251					}
2252
2253					if (mucOptions.mamSupport()) {
2254						getMessageArchiveService().catchupMUC(conversation);
2255					}
2256					if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
2257						fetchConferenceMembers(conversation);
2258						if (followedInvite && conversation.getBookmark() == null) {
2259							saveConversationAsBookmark(conversation,null);
2260						}
2261					}
2262					sendUnsentMessages(conversation);
2263				}
2264
2265				@Override
2266				public void onConferenceConfigurationFetched(Conversation conversation) {
2267					join(conversation);
2268				}
2269
2270				@Override
2271				public void onFetchFailed(final Conversation conversation, Element error) {
2272					if (error != null && "remote-server-not-found".equals(error.getName())) {
2273						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2274					} else {
2275						join(conversation);
2276						fetchConferenceConfiguration(conversation);
2277					}
2278				}
2279			});
2280			updateConversationUi();
2281		} else {
2282			account.pendingConferenceJoins.add(conversation);
2283			conversation.resetMucOptions();
2284			conversation.setHasMessagesLeftOnServer(false);
2285			updateConversationUi();
2286		}
2287	}
2288
2289	private void fetchConferenceMembers(final Conversation conversation) {
2290		final Account account = conversation.getAccount();
2291		final String[] affiliations = {"member","admin","owner"};
2292		OnIqPacketReceived callback = new OnIqPacketReceived() {
2293
2294			private int i = 0;
2295			private boolean success = true;
2296
2297			@Override
2298			public void onIqPacketReceived(Account account, IqPacket packet) {
2299
2300				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2301				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2302					for(Element child : query.getChildren()) {
2303						if ("item".equals(child.getName())) {
2304							MucOptions.User user = AbstractParser.parseItem(conversation,child);
2305							if (!user.realJidMatchesAccount()) {
2306								conversation.getMucOptions().updateUser(user);
2307							}
2308						}
2309					}
2310				} else {
2311					success = false;
2312					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
2313				}
2314				++i;
2315				if (i >= affiliations.length) {
2316					List<Jid> members = conversation.getMucOptions().getMembers();
2317					if (success) {
2318						List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2319						boolean changed = false;
2320						for(ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext();) {
2321							Jid jid = iterator.next();
2322							if (!members.contains(jid)) {
2323								iterator.remove();
2324								Log.d(Config.LOGTAG,account.getJid().toBareJid()+": removed "+jid+" from crypto targets of "+conversation.getName());
2325								changed = true;
2326							}
2327						}
2328						if (changed) {
2329							conversation.setAcceptedCryptoTargets(cryptoTargets);
2330							updateConversation(conversation);
2331						}
2332					}
2333					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
2334					getAvatarService().clear(conversation);
2335					updateMucRosterUi();
2336					updateConversationUi();
2337				}
2338			}
2339		};
2340		for(String affiliation : affiliations) {
2341			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2342		}
2343		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
2344	}
2345
2346	public void providePasswordForMuc(Conversation conversation, String password) {
2347		if (conversation.getMode() == Conversation.MODE_MULTI) {
2348			conversation.getMucOptions().setPassword(password);
2349			if (conversation.getBookmark() != null) {
2350				if (respectAutojoin()) {
2351					conversation.getBookmark().setAutojoin(true);
2352				}
2353				pushBookmarks(conversation.getAccount());
2354			}
2355			updateConversation(conversation);
2356			joinMuc(conversation);
2357		}
2358	}
2359
2360	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2361		final MucOptions options = conversation.getMucOptions();
2362		final Jid joinJid = options.createJoinJid(nick);
2363		if (options.online()) {
2364			Account account = conversation.getAccount();
2365			options.setOnRenameListener(new OnRenameListener() {
2366
2367				@Override
2368				public void onSuccess() {
2369					conversation.setContactJid(joinJid);
2370					databaseBackend.updateConversation(conversation);
2371					Bookmark bookmark = conversation.getBookmark();
2372					if (bookmark != null) {
2373						bookmark.setNick(nick);
2374						pushBookmarks(bookmark.getAccount());
2375					}
2376					callback.success(conversation);
2377				}
2378
2379				@Override
2380				public void onFailure() {
2381					callback.error(R.string.nick_in_use, conversation);
2382				}
2383			});
2384
2385			PresencePacket packet = new PresencePacket();
2386			packet.setTo(joinJid);
2387			packet.setFrom(conversation.getAccount().getJid());
2388
2389			String sig = account.getPgpSignature();
2390			if (sig != null) {
2391				packet.addChild("status").setContent("online");
2392				packet.addChild("x", "jabber:x:signed").setContent(sig);
2393			}
2394			sendPresencePacket(account, packet);
2395		} else {
2396			conversation.setContactJid(joinJid);
2397			databaseBackend.updateConversation(conversation);
2398			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2399				Bookmark bookmark = conversation.getBookmark();
2400				if (bookmark != null) {
2401					bookmark.setNick(nick);
2402					pushBookmarks(bookmark.getAccount());
2403				}
2404				joinMuc(conversation);
2405			}
2406		}
2407	}
2408
2409	public void leaveMuc(Conversation conversation) {
2410		leaveMuc(conversation, false);
2411	}
2412
2413	private void leaveMuc(Conversation conversation, boolean now) {
2414		Account account = conversation.getAccount();
2415		account.pendingConferenceJoins.remove(conversation);
2416		account.pendingConferenceLeaves.remove(conversation);
2417		if (account.getStatus() == Account.State.ONLINE || now) {
2418			PresencePacket packet = new PresencePacket();
2419			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2420			packet.setFrom(conversation.getAccount().getJid());
2421			packet.setAttribute("type", "unavailable");
2422			sendPresencePacket(conversation.getAccount(), packet);
2423			conversation.getMucOptions().setOffline();
2424			conversation.deregisterWithBookmark();
2425			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2426					+ ": leaving muc " + conversation.getJid());
2427		} else {
2428			account.pendingConferenceLeaves.add(conversation);
2429		}
2430	}
2431
2432	public String findConferenceServer(final Account account) {
2433		String server;
2434		if (account.getXmppConnection() != null) {
2435			server = account.getXmppConnection().getMucServer();
2436			if (server != null) {
2437				return server;
2438			}
2439		}
2440		for (Account other : getAccounts()) {
2441			if (other != account && other.getXmppConnection() != null) {
2442				server = other.getXmppConnection().getMucServer();
2443				if (server != null) {
2444					return server;
2445				}
2446			}
2447		}
2448		return null;
2449	}
2450
2451	public boolean createAdhocConference(final Account account,
2452									  final String subject,
2453									  final Iterable<Jid> jids,
2454									  final UiCallback<Conversation> callback) {
2455		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2456		if (account.getStatus() == Account.State.ONLINE) {
2457			try {
2458				String server = findConferenceServer(account);
2459				if (server == null) {
2460					if (callback != null) {
2461						callback.error(R.string.no_conference_server_found, null);
2462					}
2463					return false;
2464				}
2465				final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2466				final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2467				joinMuc(conversation, new OnConferenceJoined() {
2468					@Override
2469					public void onConferenceJoined(final Conversation conversation) {
2470						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConfigurationPushed() {
2471							@Override
2472							public void onPushSucceeded() {
2473								if (subject != null && !subject.trim().isEmpty()) {
2474									pushSubjectToConference(conversation, subject.trim());
2475								}
2476								for (Jid invite : jids) {
2477									invite(conversation, invite);
2478								}
2479								if (account.countPresences() > 1) {
2480									directInvite(conversation, account.getJid().toBareJid());
2481								}
2482								saveConversationAsBookmark(conversation, subject);
2483								if (callback != null) {
2484									callback.success(conversation);
2485								}
2486							}
2487
2488							@Override
2489							public void onPushFailed() {
2490								archiveConversation(conversation);
2491								if (callback != null) {
2492									callback.error(R.string.conference_creation_failed, conversation);
2493								}
2494							}
2495						});
2496					}
2497				});
2498				return true;
2499			} catch (InvalidJidException e) {
2500				if (callback != null) {
2501					callback.error(R.string.conference_creation_failed, null);
2502				}
2503				return false;
2504			}
2505		} else {
2506			if (callback != null) {
2507				callback.error(R.string.not_connected_try_again, null);
2508			}
2509			return false;
2510		}
2511	}
2512
2513	public void fetchConferenceConfiguration(final Conversation conversation) {
2514		fetchConferenceConfiguration(conversation, null);
2515	}
2516
2517	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2518		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2519		request.setTo(conversation.getJid().toBareJid());
2520		request.query("http://jabber.org/protocol/disco#info");
2521		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2522			@Override
2523			public void onIqPacketReceived(Account account, IqPacket packet) {
2524				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2525				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2526					ArrayList<String> features = new ArrayList<>();
2527					for (Element child : query.getChildren()) {
2528						if (child != null && child.getName().equals("feature")) {
2529							String var = child.getAttribute("var");
2530							if (var != null) {
2531								features.add(var);
2532							}
2533						}
2534					}
2535					Element form = query.findChild("x", "jabber:x:data");
2536					if (form != null) {
2537						conversation.getMucOptions().updateFormData(Data.parse(form));
2538					}
2539					conversation.getMucOptions().updateFeatures(features);
2540					if (callback != null) {
2541						callback.onConferenceConfigurationFetched(conversation);
2542					}
2543					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2544					updateConversationUi();
2545				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2546					if (callback != null) {
2547						callback.onFetchFailed(conversation, packet.getError());
2548					}
2549				}
2550			}
2551		});
2552	}
2553
2554	public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2555		sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid,node), new OnIqPacketReceived() {
2556			@Override
2557			public void onIqPacketReceived(Account account, IqPacket packet) {
2558				if (packet.getType() == IqPacket.TYPE.RESULT) {
2559					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub#owner");
2560					Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2561					Element x = configuration == null ? null : configuration.findChild("x","jabber:x:data");
2562					if (x != null) {
2563						Data data = Data.parse(x);
2564						data.submit(options);
2565						sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2566							@Override
2567							public void onIqPacketReceived(Account account, IqPacket packet) {
2568								if (packet.getType() == IqPacket.TYPE.RESULT) {
2569									callback.onPushSucceeded();
2570								} else {
2571									Log.d(Config.LOGTAG,packet.toString());
2572								}
2573							}
2574						});
2575					} else {
2576						callback.onPushFailed();
2577					}
2578				} else {
2579					callback.onPushFailed();
2580				}
2581			}
2582		});
2583	}
2584
2585	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2586		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2587		request.setTo(conversation.getJid().toBareJid());
2588		request.query("http://jabber.org/protocol/muc#owner");
2589		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2590			@Override
2591			public void onIqPacketReceived(Account account, IqPacket packet) {
2592				if (packet.getType() == IqPacket.TYPE.RESULT) {
2593					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2594					data.submit(options);
2595					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2596					set.setTo(conversation.getJid().toBareJid());
2597					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2598					sendIqPacket(account, set, new OnIqPacketReceived() {
2599						@Override
2600						public void onIqPacketReceived(Account account, IqPacket packet) {
2601							if (callback != null) {
2602								if (packet.getType() == IqPacket.TYPE.RESULT) {
2603									callback.onPushSucceeded();
2604								} else {
2605									callback.onPushFailed();
2606								}
2607							}
2608						}
2609					});
2610				} else {
2611					if (callback != null) {
2612						callback.onPushFailed();
2613					}
2614				}
2615			}
2616		});
2617	}
2618
2619	public void pushSubjectToConference(final Conversation conference, final String subject) {
2620		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2621		this.sendMessagePacket(conference.getAccount(), packet);
2622		final MucOptions mucOptions = conference.getMucOptions();
2623		final MucOptions.User self = mucOptions.getSelf();
2624		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2625			Bundle options = new Bundle();
2626			options.putString("muc#roomconfig_persistentroom", "1");
2627			this.pushConferenceConfiguration(conference, options, null);
2628		}
2629	}
2630
2631	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2632		final Jid jid = user.toBareJid();
2633		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2634		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2635			@Override
2636			public void onIqPacketReceived(Account account, IqPacket packet) {
2637				if (packet.getType() == IqPacket.TYPE.RESULT) {
2638					conference.getMucOptions().changeAffiliation(jid, affiliation);
2639					getAvatarService().clear(conference);
2640					callback.onAffiliationChangedSuccessful(jid);
2641				} else {
2642					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2643				}
2644			}
2645		});
2646	}
2647
2648	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2649		List<Jid> jids = new ArrayList<>();
2650		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2651			if (user.getAffiliation() == before && user.getRealJid() != null) {
2652				jids.add(user.getRealJid());
2653			}
2654		}
2655		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2656		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2657	}
2658
2659	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2660		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2661		Log.d(Config.LOGTAG, request.toString());
2662		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2663			@Override
2664			public void onIqPacketReceived(Account account, IqPacket packet) {
2665				Log.d(Config.LOGTAG, packet.toString());
2666				if (packet.getType() == IqPacket.TYPE.RESULT) {
2667					callback.onRoleChangedSuccessful(nick);
2668				} else {
2669					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2670				}
2671			}
2672		});
2673	}
2674
2675	private void disconnect(Account account, boolean force) {
2676		if ((account.getStatus() == Account.State.ONLINE)
2677				|| (account.getStatus() == Account.State.DISABLED)) {
2678			final XmppConnection connection = account.getXmppConnection();
2679			if (!force) {
2680				List<Conversation> conversations = getConversations();
2681				for (Conversation conversation : conversations) {
2682					if (conversation.getAccount() == account) {
2683						if (conversation.getMode() == Conversation.MODE_MULTI) {
2684							leaveMuc(conversation, true);
2685						} else {
2686							if (conversation.endOtrIfNeeded()) {
2687								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2688										+ ": ended otr session with "
2689										+ conversation.getJid());
2690							}
2691						}
2692					}
2693				}
2694				sendOfflinePresence(account);
2695			}
2696			connection.disconnect(force);
2697		}
2698	}
2699
2700	@Override
2701	public IBinder onBind(Intent intent) {
2702		return mBinder;
2703	}
2704
2705	public void updateMessage(Message message) {
2706		databaseBackend.updateMessage(message);
2707		updateConversationUi();
2708	}
2709
2710	public void updateMessage(Message message, String uuid) {
2711		databaseBackend.updateMessage(message, uuid);
2712		updateConversationUi();
2713	}
2714
2715	protected void syncDirtyContacts(Account account) {
2716		for (Contact contact : account.getRoster().getContacts()) {
2717			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2718				pushContactToServer(contact);
2719			}
2720			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2721				deleteContactOnServer(contact);
2722			}
2723		}
2724	}
2725
2726	public void createContact(Contact contact) {
2727		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2728		if (autoGrant) {
2729			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2730			contact.setOption(Contact.Options.ASKING);
2731		}
2732		pushContactToServer(contact);
2733	}
2734
2735	public void onOtrSessionEstablished(Conversation conversation) {
2736		final Account account = conversation.getAccount();
2737		final Session otrSession = conversation.getOtrSession();
2738		Log.d(Config.LOGTAG,
2739				account.getJid().toBareJid() + " otr session established with "
2740						+ conversation.getJid() + "/"
2741						+ otrSession.getSessionID().getUserID());
2742		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2743
2744			@Override
2745			public void onMessageFound(Message message) {
2746				SessionID id = otrSession.getSessionID();
2747				try {
2748					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2749				} catch (InvalidJidException e) {
2750					return;
2751				}
2752				if (message.needsUploading()) {
2753					mJingleConnectionManager.createNewConnection(message);
2754				} else {
2755					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2756					if (outPacket != null) {
2757						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2758						message.setStatus(Message.STATUS_SEND);
2759						databaseBackend.updateMessage(message);
2760						sendMessagePacket(account, outPacket);
2761					}
2762				}
2763				updateConversationUi();
2764			}
2765		});
2766	}
2767
2768	public boolean renewSymmetricKey(Conversation conversation) {
2769		Account account = conversation.getAccount();
2770		byte[] symmetricKey = new byte[32];
2771		this.mRandom.nextBytes(symmetricKey);
2772		Session otrSession = conversation.getOtrSession();
2773		if (otrSession != null) {
2774			MessagePacket packet = new MessagePacket();
2775			packet.setType(MessagePacket.TYPE_CHAT);
2776			packet.setFrom(account.getJid());
2777			MessageGenerator.addMessageHints(packet);
2778			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2779					+ otrSession.getSessionID().getUserID());
2780			try {
2781				packet.setBody(otrSession
2782						.transformSending(CryptoHelper.FILETRANSFER
2783								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2784				sendMessagePacket(account, packet);
2785				conversation.setSymmetricKey(symmetricKey);
2786				return true;
2787			} catch (OtrException e) {
2788				return false;
2789			}
2790		}
2791		return false;
2792	}
2793
2794	public void pushContactToServer(final Contact contact) {
2795		contact.resetOption(Contact.Options.DIRTY_DELETE);
2796		contact.setOption(Contact.Options.DIRTY_PUSH);
2797		final Account account = contact.getAccount();
2798		if (account.getStatus() == Account.State.ONLINE) {
2799			final boolean ask = contact.getOption(Contact.Options.ASKING);
2800			final boolean sendUpdates = contact
2801					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2802					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2803			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2804			iq.query(Namespace.ROSTER).addChild(contact.asElement());
2805			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2806			if (sendUpdates) {
2807				sendPresencePacket(account,
2808						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2809			}
2810			if (ask) {
2811				sendPresencePacket(account,
2812						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2813			}
2814		}
2815	}
2816
2817	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2818		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2819		final int size = Config.AVATAR_SIZE;
2820		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2821		if (avatar != null) {
2822			avatar.height = size;
2823			avatar.width = size;
2824			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2825				avatar.type = "image/webp";
2826			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2827				avatar.type = "image/jpeg";
2828			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2829				avatar.type = "image/png";
2830			}
2831			if (!getFileBackend().save(avatar)) {
2832				callback.error(R.string.error_saving_avatar, avatar);
2833				return;
2834			}
2835			publishAvatar(account, avatar, callback);
2836		} else {
2837			callback.error(R.string.error_publish_avatar_converting, null);
2838		}
2839	}
2840
2841	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2842		IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2843		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2844
2845			@Override
2846			public void onIqPacketReceived(Account account, IqPacket result) {
2847				if (result.getType() == IqPacket.TYPE.RESULT) {
2848					final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2849					sendIqPacket(account, packet, new OnIqPacketReceived() {
2850						@Override
2851						public void onIqPacketReceived(Account account, IqPacket result) {
2852							if (result.getType() == IqPacket.TYPE.RESULT) {
2853								if (account.setAvatar(avatar.getFilename())) {
2854									getAvatarService().clear(account);
2855									databaseBackend.updateAccount(account);
2856								}
2857								Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar "+(avatar.size/1024)+"KiB");
2858								if (callback != null) {
2859									callback.success(avatar);
2860								}
2861							} else {
2862								if (callback != null) {
2863									callback.error(R.string.error_publish_avatar_server_reject,avatar);
2864								}
2865							}
2866						}
2867					});
2868				} else {
2869					Element error = result.findChild("error");
2870					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server rejected avatar "+(avatar.size/1024)+"KiB "+(error!=null?error.toString():""));
2871					if (callback != null) {
2872						callback.error(R.string.error_publish_avatar_server_reject, avatar);
2873					}
2874				}
2875			}
2876		});
2877	}
2878
2879	public void republishAvatarIfNeeded(Account account) {
2880		if (account.getAxolotlService().isPepBroken()) {
2881			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2882			return;
2883		}
2884		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2885		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2886
2887			private Avatar parseAvatar(IqPacket packet) {
2888				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2889				if (pubsub != null) {
2890					Element items = pubsub.findChild("items");
2891					if (items != null) {
2892						return Avatar.parseMetadata(items);
2893					}
2894				}
2895				return null;
2896			}
2897
2898			private boolean errorIsItemNotFound(IqPacket packet) {
2899				Element error = packet.findChild("error");
2900				return packet.getType() == IqPacket.TYPE.ERROR
2901						&& error != null
2902						&& error.hasChild("item-not-found");
2903			}
2904
2905			@Override
2906			public void onIqPacketReceived(Account account, IqPacket packet) {
2907				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2908					Avatar serverAvatar = parseAvatar(packet);
2909					if (serverAvatar == null && account.getAvatar() != null) {
2910						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2911						if (avatar != null) {
2912							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2913							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2914						} else {
2915							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2916						}
2917					}
2918				}
2919			}
2920		});
2921	}
2922
2923	public void fetchAvatar(Account account, Avatar avatar) {
2924		fetchAvatar(account, avatar, null);
2925	}
2926
2927	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2928		final String KEY = generateFetchKey(account, avatar);
2929		synchronized (this.mInProgressAvatarFetches) {
2930			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2931				switch (avatar.origin) {
2932					case PEP:
2933						this.mInProgressAvatarFetches.add(KEY);
2934						fetchAvatarPep(account, avatar, callback);
2935						break;
2936					case VCARD:
2937						this.mInProgressAvatarFetches.add(KEY);
2938						fetchAvatarVcard(account, avatar, callback);
2939						break;
2940				}
2941			}
2942		}
2943	}
2944
2945	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2946		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2947		sendIqPacket(account, packet, new OnIqPacketReceived() {
2948
2949			@Override
2950			public void onIqPacketReceived(Account account, IqPacket result) {
2951				synchronized (mInProgressAvatarFetches) {
2952					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2953				}
2954				final String ERROR = account.getJid().toBareJid()
2955						+ ": fetching avatar for " + avatar.owner + " failed ";
2956				if (result.getType() == IqPacket.TYPE.RESULT) {
2957					avatar.image = mIqParser.avatarData(result);
2958					if (avatar.image != null) {
2959						if (getFileBackend().save(avatar)) {
2960							if (account.getJid().toBareJid().equals(avatar.owner)) {
2961								if (account.setAvatar(avatar.getFilename())) {
2962									databaseBackend.updateAccount(account);
2963								}
2964								getAvatarService().clear(account);
2965								updateConversationUi();
2966								updateAccountUi();
2967							} else {
2968								Contact contact = account.getRoster()
2969										.getContact(avatar.owner);
2970								contact.setAvatar(avatar);
2971								getAvatarService().clear(contact);
2972								updateConversationUi();
2973								updateRosterUi();
2974							}
2975							if (callback != null) {
2976								callback.success(avatar);
2977							}
2978							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2979									+ ": successfully fetched pep avatar for " + avatar.owner);
2980							return;
2981						}
2982					} else {
2983
2984						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2985					}
2986				} else {
2987					Element error = result.findChild("error");
2988					if (error == null) {
2989						Log.d(Config.LOGTAG, ERROR + "(server error)");
2990					} else {
2991						Log.d(Config.LOGTAG, ERROR + error.toString());
2992					}
2993				}
2994				if (callback != null) {
2995					callback.error(0, null);
2996				}
2997
2998			}
2999		});
3000	}
3001
3002	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3003		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3004		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3005			@Override
3006			public void onIqPacketReceived(Account account, IqPacket packet) {
3007				synchronized (mInProgressAvatarFetches) {
3008					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
3009				}
3010				if (packet.getType() == IqPacket.TYPE.RESULT) {
3011					Element vCard = packet.findChild("vCard", "vcard-temp");
3012					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3013					String image = photo != null ? photo.findChildContent("BINVAL") : null;
3014					if (image != null) {
3015						avatar.image = image;
3016						if (getFileBackend().save(avatar)) {
3017							Log.d(Config.LOGTAG, account.getJid().toBareJid()
3018									+ ": successfully fetched vCard avatar for " + avatar.owner);
3019							if (avatar.owner.isBareJid()) {
3020								if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3021									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": had no avatar. replacing with vcard");
3022									account.setAvatar(avatar.getFilename());
3023									databaseBackend.updateAccount(account);
3024									getAvatarService().clear(account);
3025									updateAccountUi();
3026								} else {
3027									Contact contact = account.getRoster().getContact(avatar.owner);
3028									contact.setAvatar(avatar);
3029									getAvatarService().clear(contact);
3030									updateRosterUi();
3031								}
3032								updateConversationUi();
3033							} else {
3034								Conversation conversation = find(account, avatar.owner.toBareJid());
3035								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3036									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3037									if (user != null) {
3038										if (user.setAvatar(avatar)) {
3039											getAvatarService().clear(user);
3040											updateConversationUi();
3041											updateMucRosterUi();
3042										}
3043									}
3044								}
3045							}
3046						}
3047					}
3048				}
3049			}
3050		});
3051	}
3052
3053	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3054		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3055		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3056
3057			@Override
3058			public void onIqPacketReceived(Account account, IqPacket packet) {
3059				if (packet.getType() == IqPacket.TYPE.RESULT) {
3060					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
3061					if (pubsub != null) {
3062						Element items = pubsub.findChild("items");
3063						if (items != null) {
3064							Avatar avatar = Avatar.parseMetadata(items);
3065							if (avatar != null) {
3066								avatar.owner = account.getJid().toBareJid();
3067								if (fileBackend.isAvatarCached(avatar)) {
3068									if (account.setAvatar(avatar.getFilename())) {
3069										databaseBackend.updateAccount(account);
3070									}
3071									getAvatarService().clear(account);
3072									callback.success(avatar);
3073								} else {
3074									fetchAvatarPep(account, avatar, callback);
3075								}
3076								return;
3077							}
3078						}
3079					}
3080				}
3081				callback.error(0, null);
3082			}
3083		});
3084	}
3085
3086	public void deleteContactOnServer(Contact contact) {
3087		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3088		contact.resetOption(Contact.Options.DIRTY_PUSH);
3089		contact.setOption(Contact.Options.DIRTY_DELETE);
3090		Account account = contact.getAccount();
3091		if (account.getStatus() == Account.State.ONLINE) {
3092			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3093			Element item = iq.query(Namespace.ROSTER).addChild("item");
3094			item.setAttribute("jid", contact.getJid().toString());
3095			item.setAttribute("subscription", "remove");
3096			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3097		}
3098	}
3099
3100	public void updateConversation(final Conversation conversation) {
3101		mDatabaseExecutor.execute(new Runnable() {
3102			@Override
3103			public void run() {
3104				databaseBackend.updateConversation(conversation);
3105			}
3106		});
3107	}
3108
3109	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3110		synchronized (account) {
3111			XmppConnection connection = account.getXmppConnection();
3112			if (connection == null) {
3113				connection = createConnection(account);
3114				account.setXmppConnection(connection);
3115			}
3116			boolean hasInternet = hasInternetConnection();
3117			if (!account.isOptionSet(Account.OPTION_DISABLED) && hasInternet) {
3118				if (!force) {
3119					disconnect(account, false);
3120				}
3121				Thread thread = new Thread(connection);
3122				connection.setInteractive(interactive);
3123				connection.prepareNewConnection();
3124				connection.interrupt();
3125				thread.start();
3126				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3127			} else {
3128				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3129				account.getRoster().clearPresences();
3130				connection.resetEverything();
3131				final AxolotlService axolotlService = account.getAxolotlService();
3132				if (axolotlService != null) {
3133					axolotlService.resetBrokenness();
3134				}
3135				if (!hasInternet) {
3136					account.setStatus(Account.State.NO_INTERNET);
3137				}
3138			}
3139		}
3140	}
3141
3142	public void reconnectAccountInBackground(final Account account) {
3143		new Thread(new Runnable() {
3144			@Override
3145			public void run() {
3146				reconnectAccount(account, false, true);
3147			}
3148		}).start();
3149	}
3150
3151	public void invite(Conversation conversation, Jid contact) {
3152		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
3153		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3154		sendMessagePacket(conversation.getAccount(), packet);
3155	}
3156
3157	public void directInvite(Conversation conversation, Jid jid) {
3158		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3159		sendMessagePacket(conversation.getAccount(), packet);
3160	}
3161
3162	public void resetSendingToWaiting(Account account) {
3163		for (Conversation conversation : getConversations()) {
3164			if (conversation.getAccount() == account) {
3165				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3166
3167					@Override
3168					public void onMessageFound(Message message) {
3169						markMessage(message, Message.STATUS_WAITING);
3170					}
3171				});
3172			}
3173		}
3174	}
3175
3176	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3177		return markMessage(account, recipient, uuid, status, null);
3178	}
3179
3180	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3181		if (uuid == null) {
3182			return null;
3183		}
3184		for (Conversation conversation : getConversations()) {
3185			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
3186				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3187				if (message != null) {
3188					markMessage(message, status, errorMessage);
3189				}
3190				return message;
3191			}
3192		}
3193		return null;
3194	}
3195
3196	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3197		if (uuid == null) {
3198			return false;
3199		} else {
3200			Message message = conversation.findSentMessageWithUuid(uuid);
3201			if (message != null) {
3202				if (message.getServerMsgId() == null) {
3203					message.setServerMsgId(serverMessageId);
3204				}
3205				markMessage(message, status);
3206				return true;
3207			} else {
3208				return false;
3209			}
3210		}
3211	}
3212
3213	public void markMessage(Message message, int status) {
3214		markMessage(message, status, null);
3215	}
3216
3217
3218	public void markMessage(Message message, int status, String errorMessage) {
3219		if (status == Message.STATUS_SEND_FAILED
3220				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
3221				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
3222			return;
3223		}
3224		message.setErrorMessage(errorMessage);
3225		message.setStatus(status);
3226		databaseBackend.updateMessage(message);
3227		updateConversationUi();
3228	}
3229
3230	public SharedPreferences getPreferences() {
3231		return PreferenceManager
3232				.getDefaultSharedPreferences(getApplicationContext());
3233	}
3234
3235	public long getAutomaticMessageDeletionDate() {
3236		try {
3237			final long timeout = Long.parseLong(getPreferences().getString(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, "0")) * 1000;
3238			return timeout == 0 ? timeout : System.currentTimeMillis() - timeout;
3239		} catch (NumberFormatException e) {
3240			return 0;
3241		}
3242	}
3243
3244	public boolean confirmMessages() {
3245		return getPreferences().getBoolean("confirm_messages", true);
3246	}
3247
3248	public boolean allowMessageCorrection() {
3249		return getPreferences().getBoolean("allow_message_correction", true);
3250	}
3251
3252	public boolean sendChatStates() {
3253		return getPreferences().getBoolean("chat_states", false);
3254	}
3255
3256	private boolean respectAutojoin() {
3257		return getPreferences().getBoolean("autojoin", true);
3258	}
3259
3260	public boolean indicateReceived() {
3261		return getPreferences().getBoolean("indicate_received", false);
3262	}
3263
3264	public boolean useTorToConnect() {
3265		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
3266	}
3267
3268	public boolean showExtendedConnectionOptions() {
3269		return getPreferences().getBoolean("show_connection_options", false);
3270	}
3271
3272	public boolean broadcastLastActivity() {
3273		return getPreferences().getBoolean(SettingsActivity.BROADCAST_LAST_ACTIVITY, false);
3274	}
3275
3276	public int unreadCount() {
3277		int count = 0;
3278		for (Conversation conversation : getConversations()) {
3279			count += conversation.unreadCount();
3280		}
3281		return count;
3282	}
3283
3284
3285	public void showErrorToastInUi(int resId) {
3286		if (mOnShowErrorToast != null) {
3287			mOnShowErrorToast.onShowErrorToast(resId);
3288		}
3289	}
3290
3291	public void updateConversationUi() {
3292		if (mOnConversationUpdate != null) {
3293			mOnConversationUpdate.onConversationUpdate();
3294		}
3295	}
3296
3297	public void updateAccountUi() {
3298		if (mOnAccountUpdate != null) {
3299			mOnAccountUpdate.onAccountUpdate();
3300		}
3301	}
3302
3303	public void updateRosterUi() {
3304		if (mOnRosterUpdate != null) {
3305			mOnRosterUpdate.onRosterUpdate();
3306		}
3307	}
3308
3309	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3310		if (mOnCaptchaRequested != null) {
3311			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3312			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3313					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3314
3315			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3316			return true;
3317		}
3318		return false;
3319	}
3320
3321	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3322		if (mOnUpdateBlocklist != null) {
3323			mOnUpdateBlocklist.OnUpdateBlocklist(status);
3324		}
3325	}
3326
3327	public void updateMucRosterUi() {
3328		if (mOnMucRosterUpdate != null) {
3329			mOnMucRosterUpdate.onMucRosterUpdate();
3330		}
3331	}
3332
3333	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3334		if (mOnKeyStatusUpdated != null) {
3335			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3336		}
3337	}
3338
3339	public Account findAccountByJid(final Jid accountJid) {
3340		for (Account account : this.accounts) {
3341			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3342				return account;
3343			}
3344		}
3345		return null;
3346	}
3347
3348	public Conversation findConversationByUuid(String uuid) {
3349		for (Conversation conversation : getConversations()) {
3350			if (conversation.getUuid().equals(uuid)) {
3351				return conversation;
3352			}
3353		}
3354		return null;
3355	}
3356
3357	public boolean markRead(final Conversation conversation) {
3358		return markRead(conversation,true);
3359	}
3360
3361	public boolean markRead(final Conversation conversation, boolean clear) {
3362		if (clear) {
3363			mNotificationService.clear(conversation);
3364		}
3365		final List<Message> readMessages = conversation.markRead();
3366		if (readMessages.size() > 0) {
3367			Runnable runnable = new Runnable() {
3368				@Override
3369				public void run() {
3370					for (Message message : readMessages) {
3371						databaseBackend.updateMessage(message);
3372					}
3373				}
3374			};
3375			mDatabaseExecutor.execute(runnable);
3376			updateUnreadCountBadge();
3377			return true;
3378		} else {
3379			return false;
3380		}
3381	}
3382
3383	public synchronized void updateUnreadCountBadge() {
3384		int count = unreadCount();
3385		if (unreadCount != count) {
3386			Log.d(Config.LOGTAG, "update unread count to " + count);
3387			if (count > 0) {
3388				ShortcutBadger.applyCount(getApplicationContext(), count);
3389			} else {
3390				ShortcutBadger.removeCount(getApplicationContext());
3391			}
3392			unreadCount = count;
3393		}
3394	}
3395
3396	public void sendReadMarker(final Conversation conversation) {
3397		final Message markable = conversation.getLatestMarkableMessage();
3398		if (this.markRead(conversation)) {
3399			updateConversationUi();
3400		}
3401		if (confirmMessages()
3402				&& markable != null
3403				&& markable.trusted()
3404				&& markable.getRemoteMsgId() != null) {
3405			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3406			Account account = conversation.getAccount();
3407			final Jid to = markable.getCounterpart();
3408			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
3409			this.sendMessagePacket(conversation.getAccount(), packet);
3410		}
3411	}
3412
3413	public SecureRandom getRNG() {
3414		return this.mRandom;
3415	}
3416
3417	public MemorizingTrustManager getMemorizingTrustManager() {
3418		return this.mMemorizingTrustManager;
3419	}
3420
3421	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3422		this.mMemorizingTrustManager = trustManager;
3423	}
3424
3425	public void updateMemorizingTrustmanager() {
3426		final MemorizingTrustManager tm;
3427		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
3428		if (dontTrustSystemCAs) {
3429			tm = new MemorizingTrustManager(getApplicationContext(), null);
3430		} else {
3431			tm = new MemorizingTrustManager(getApplicationContext());
3432		}
3433		setMemorizingTrustManager(tm);
3434	}
3435
3436	public PowerManager getPowerManager() {
3437		return this.pm;
3438	}
3439
3440	public LruCache<String, Bitmap> getBitmapCache() {
3441		return this.mBitmapCache;
3442	}
3443
3444	public void syncRosterToDisk(final Account account) {
3445		Runnable runnable = new Runnable() {
3446
3447			@Override
3448			public void run() {
3449				databaseBackend.writeRoster(account.getRoster());
3450			}
3451		};
3452		mDatabaseExecutor.execute(runnable);
3453
3454	}
3455
3456	public List<String> getKnownHosts() {
3457		final List<String> hosts = new ArrayList<>();
3458		for (final Account account : getAccounts()) {
3459			if (!hosts.contains(account.getServer().toString())) {
3460				hosts.add(account.getServer().toString());
3461			}
3462			for (final Contact contact : account.getRoster().getContacts()) {
3463				if (contact.showInRoster()) {
3464					final String server = contact.getServer().toString();
3465					if (server != null && !hosts.contains(server)) {
3466						hosts.add(server);
3467					}
3468				}
3469			}
3470		}
3471		if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3472			hosts.add(Config.DOMAIN_LOCK);
3473		}
3474		if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3475			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3476		}
3477		return hosts;
3478	}
3479
3480	public List<String> getKnownConferenceHosts() {
3481		final ArrayList<String> mucServers = new ArrayList<>();
3482		for (final Account account : accounts) {
3483			if (account.getXmppConnection() != null) {
3484				final String server = account.getXmppConnection().getMucServer();
3485				if (server != null && !mucServers.contains(server)) {
3486					mucServers.add(server);
3487				}
3488			}
3489		}
3490		return mucServers;
3491	}
3492
3493	public void sendMessagePacket(Account account, MessagePacket packet) {
3494		XmppConnection connection = account.getXmppConnection();
3495		if (connection != null) {
3496			connection.sendMessagePacket(packet);
3497		}
3498	}
3499
3500	public void sendPresencePacket(Account account, PresencePacket packet) {
3501		XmppConnection connection = account.getXmppConnection();
3502		if (connection != null) {
3503			connection.sendPresencePacket(packet);
3504		}
3505	}
3506
3507	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3508		final XmppConnection connection = account.getXmppConnection();
3509		if (connection != null) {
3510			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3511			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3512		}
3513	}
3514
3515	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3516		final XmppConnection connection = account.getXmppConnection();
3517		if (connection != null) {
3518			connection.sendIqPacket(packet, callback);
3519		}
3520	}
3521
3522	public void sendPresence(final Account account) {
3523		sendPresence(account, checkListeners() && broadcastLastActivity());
3524	}
3525
3526	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3527		PresencePacket packet;
3528		if (manuallyChangePresence()) {
3529			packet =  mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3530			String message = account.getPresenceStatusMessage();
3531			if (message != null && !message.isEmpty()) {
3532				packet.addChild(new Element("status").setContent(message));
3533			}
3534		} else {
3535			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3536		}
3537		if (mLastActivity > 0 && includeIdleTimestamp) {
3538			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3539			packet.addChild("idle",Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3540		}
3541		sendPresencePacket(account, packet);
3542	}
3543
3544	private void deactivateGracePeriod() {
3545		for(Account account : getAccounts()) {
3546			account.deactivateGracePeriod();
3547		}
3548	}
3549
3550	public void refreshAllPresences() {
3551		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3552		for (Account account : getAccounts()) {
3553			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3554				sendPresence(account, includeIdleTimestamp);
3555			}
3556		}
3557	}
3558
3559	private void refreshAllGcmTokens() {
3560		for(Account account : getAccounts()) {
3561			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3562				mPushManagementService.registerPushTokenOnServer(account);
3563			}
3564		}
3565	}
3566
3567	private void sendOfflinePresence(final Account account) {
3568		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending offline presence");
3569		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3570	}
3571
3572	public MessageGenerator getMessageGenerator() {
3573		return this.mMessageGenerator;
3574	}
3575
3576	public PresenceGenerator getPresenceGenerator() {
3577		return this.mPresenceGenerator;
3578	}
3579
3580	public IqGenerator getIqGenerator() {
3581		return this.mIqGenerator;
3582	}
3583
3584	public IqParser getIqParser() {
3585		return this.mIqParser;
3586	}
3587
3588	public JingleConnectionManager getJingleConnectionManager() {
3589		return this.mJingleConnectionManager;
3590	}
3591
3592	public MessageArchiveService getMessageArchiveService() {
3593		return this.mMessageArchiveService;
3594	}
3595
3596	public List<Contact> findContacts(Jid jid) {
3597		ArrayList<Contact> contacts = new ArrayList<>();
3598		for (Account account : getAccounts()) {
3599			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3600				Contact contact = account.getRoster().getContactFromRoster(jid);
3601				if (contact != null) {
3602					contacts.add(contact);
3603				}
3604			}
3605		}
3606		return contacts;
3607	}
3608
3609	public Conversation findFirstMuc(Jid jid) {
3610		for(Conversation conversation : getConversations()) {
3611			if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3612					&& conversation.getMode() == Conversation.MODE_MULTI) {
3613				return conversation;
3614			}
3615		}
3616		return null;
3617	}
3618
3619	public NotificationService getNotificationService() {
3620		return this.mNotificationService;
3621	}
3622
3623	public HttpConnectionManager getHttpConnectionManager() {
3624		return this.mHttpConnectionManager;
3625	}
3626
3627	public void resendFailedMessages(final Message message) {
3628		final Collection<Message> messages = new ArrayList<>();
3629		Message current = message;
3630		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3631			messages.add(current);
3632			if (current.mergeable(current.next())) {
3633				current = current.next();
3634			} else {
3635				break;
3636			}
3637		}
3638		for (final Message msg : messages) {
3639			msg.setTime(System.currentTimeMillis());
3640			markMessage(msg, Message.STATUS_WAITING);
3641			this.resendMessage(msg, false);
3642		}
3643	}
3644
3645	public void clearConversationHistory(final Conversation conversation) {
3646		long clearDate;
3647		if (conversation.countMessages() > 0) {
3648			clearDate = conversation.getLatestMessage().getTimeSent() + 1000;
3649		} else {
3650			clearDate = System.currentTimeMillis();
3651		}
3652		conversation.clearMessages();
3653		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3654		conversation.setLastClearHistory(clearDate);
3655		Runnable runnable = new Runnable() {
3656			@Override
3657			public void run() {
3658				databaseBackend.deleteMessagesInConversation(conversation);
3659				databaseBackend.updateConversation(conversation);
3660			}
3661		};
3662		mDatabaseExecutor.execute(runnable);
3663	}
3664
3665	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3666		if (blockable != null && blockable.getBlockedJid() != null) {
3667			final Jid jid = blockable.getBlockedJid();
3668			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3669
3670				@Override
3671				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3672					if (packet.getType() == IqPacket.TYPE.RESULT) {
3673						account.getBlocklist().add(jid);
3674						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3675					}
3676				}
3677			});
3678			if (removeBlockedConversations(blockable.getAccount(),jid)) {
3679				updateConversationUi();
3680				return true;
3681			} else {
3682				return false;
3683			}
3684		} else {
3685			return false;
3686		}
3687	}
3688
3689	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3690		boolean removed = false;
3691		synchronized (this.conversations) {
3692			boolean domainJid = blockedJid.isDomainJid();
3693			for(Conversation conversation : this.conversations) {
3694				boolean jidMatches = (domainJid && blockedJid.getDomainpart().equals(conversation.getJid().getDomainpart()))
3695						|| blockedJid.equals(conversation.getJid().toBareJid());
3696				if (conversation.getAccount() == account
3697						&& conversation.getMode() == Conversation.MODE_SINGLE
3698						&& jidMatches) {
3699					this.conversations.remove(conversation);
3700					markRead(conversation);
3701					conversation.setStatus(Conversation.STATUS_ARCHIVED);
3702					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": archiving conversation "+conversation.getJid().toBareJid()+" because jid was blocked");
3703					updateConversation(conversation);
3704					removed = true;
3705				}
3706			}
3707		}
3708		return removed;
3709	}
3710
3711	public void sendUnblockRequest(final Blockable blockable) {
3712		if (blockable != null && blockable.getJid() != null) {
3713			final Jid jid = blockable.getBlockedJid();
3714			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3715				@Override
3716				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3717					if (packet.getType() == IqPacket.TYPE.RESULT) {
3718						account.getBlocklist().remove(jid);
3719						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3720					}
3721				}
3722			});
3723		}
3724	}
3725
3726	public void publishDisplayName(Account account) {
3727		String displayName = account.getDisplayName();
3728		if (displayName != null && !displayName.isEmpty()) {
3729			IqPacket publish = mIqGenerator.publishNick(displayName);
3730			sendIqPacket(account, publish, new OnIqPacketReceived() {
3731				@Override
3732				public void onIqPacketReceived(Account account, IqPacket packet) {
3733					if (packet.getType() == IqPacket.TYPE.ERROR) {
3734						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3735					}
3736				}
3737			});
3738		}
3739	}
3740
3741	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3742		ServiceDiscoveryResult result = discoCache.get(key);
3743		if (result != null) {
3744			return result;
3745		} else {
3746			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3747			if (result != null) {
3748				discoCache.put(key, result);
3749			}
3750			return result;
3751		}
3752	}
3753
3754	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3755		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3756		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3757		if (disco != null) {
3758			presence.setServiceDiscoveryResult(disco);
3759		} else {
3760			if (!account.inProgressDiscoFetches.contains(key)) {
3761				account.inProgressDiscoFetches.add(key);
3762				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3763				request.setTo(jid);
3764				request.query("http://jabber.org/protocol/disco#info");
3765				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3766				sendIqPacket(account, request, new OnIqPacketReceived() {
3767					@Override
3768					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3769						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3770							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3771							if (presence.getVer().equals(disco.getVer())) {
3772								databaseBackend.insertDiscoveryResult(disco);
3773								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3774							} else {
3775								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3776							}
3777						}
3778						account.inProgressDiscoFetches.remove(key);
3779					}
3780				});
3781			}
3782		}
3783	}
3784
3785	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3786		for(Contact contact : roster.getContacts()) {
3787			for(Presence presence : contact.getPresences().getPresences().values()) {
3788				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3789					presence.setServiceDiscoveryResult(disco);
3790				}
3791			}
3792		}
3793	}
3794
3795	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3796		final boolean legacy = account.getXmppConnection().getFeatures().mamLegacy();
3797		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3798		request.addChild("prefs",legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3799		sendIqPacket(account, request, new OnIqPacketReceived() {
3800			@Override
3801			public void onIqPacketReceived(Account account, IqPacket packet) {
3802				Element prefs = packet.findChild("prefs",legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3803				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3804					callback.onPreferencesFetched(prefs);
3805				} else {
3806					callback.onPreferencesFetchFailed();
3807				}
3808			}
3809		});
3810	}
3811
3812	public PushManagementService getPushManagementService() {
3813		return mPushManagementService;
3814	}
3815
3816	public Account getPendingAccount() {
3817		Account pending = null;
3818		for(Account account : getAccounts()) {
3819			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3820				pending = account;
3821			} else {
3822				return null;
3823			}
3824		}
3825		return pending;
3826	}
3827
3828	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3829		if (!statusMessage.isEmpty()) {
3830			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3831		}
3832		changeStatusReal(account, status, statusMessage, send);
3833	}
3834
3835	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3836		account.setPresenceStatus(status);
3837		account.setPresenceStatusMessage(statusMessage);
3838		databaseBackend.updateAccount(account);
3839		if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3840			sendPresence(account);
3841		}
3842	}
3843
3844	public void changeStatus(Presence.Status status, String statusMessage) {
3845		if (!statusMessage.isEmpty()) {
3846			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3847		}
3848		for(Account account : getAccounts()) {
3849			changeStatusReal(account, status, statusMessage, true);
3850		}
3851	}
3852
3853	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3854		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3855		for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3856			if (!templates.contains(template)) {
3857				templates.add(0, template);
3858			}
3859		}
3860		return templates;
3861	}
3862
3863	public void saveConversationAsBookmark(Conversation conversation, String name) {
3864		Account account = conversation.getAccount();
3865		Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3866		if (!conversation.getJid().isBareJid()) {
3867			bookmark.setNick(conversation.getJid().getResourcepart());
3868		}
3869		if (name != null && !name.trim().isEmpty()) {
3870			bookmark.setBookmarkName(name.trim());
3871		}
3872		bookmark.setAutojoin(getPreferences().getBoolean("autojoin",true));
3873		account.getBookmarks().add(bookmark);
3874		pushBookmarks(account);
3875		conversation.setBookmark(bookmark);
3876	}
3877
3878	public void clearStartTimeCounter() {
3879		mDatabaseExecutor.execute(new Runnable() {
3880			@Override
3881			public void run() {
3882				databaseBackend.clearStartTimeCounter(false);
3883			}
3884		});
3885	}
3886
3887	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3888		boolean needsRosterWrite = false;
3889		boolean performedVerification = false;
3890		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3891		for(XmppUri.Fingerprint fp : fingerprints) {
3892			if (fp.type == XmppUri.FingerprintType.OTR) {
3893				performedVerification |= contact.addOtrFingerprint(fp.fingerprint);
3894				needsRosterWrite |= performedVerification;
3895			} else if (fp.type == XmppUri.FingerprintType.OMEMO) {
3896				String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3897				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3898				if (fingerprintStatus != null) {
3899					if (!fingerprintStatus.isVerified()) {
3900						performedVerification = true;
3901						axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3902					}
3903				} else {
3904					axolotlService.preVerifyFingerprint(contact,fingerprint);
3905				}
3906			}
3907		}
3908		if (needsRosterWrite) {
3909			syncRosterToDisk(contact.getAccount());
3910		}
3911		return performedVerification;
3912	}
3913
3914	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3915		final AxolotlService axolotlService = account.getAxolotlService();
3916		boolean verifiedSomething = false;
3917		for(XmppUri.Fingerprint fp : fingerprints) {
3918			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3919				String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3920				Log.d(Config.LOGTAG,"trying to verify own fp="+fingerprint);
3921				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3922				if (fingerprintStatus != null) {
3923					if (!fingerprintStatus.isVerified()) {
3924						axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3925						verifiedSomething = true;
3926					}
3927				} else {
3928					axolotlService.preVerifyFingerprint(account,fingerprint);
3929					verifiedSomething = true;
3930				}
3931			}
3932		}
3933		return verifiedSomething;
3934	}
3935
3936	public boolean blindTrustBeforeVerification() {
3937		return getPreferences().getBoolean(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, true);
3938	}
3939
3940	public interface OnMamPreferencesFetched {
3941		void onPreferencesFetched(Element prefs);
3942		void onPreferencesFetchFailed();
3943	}
3944
3945	public void pushMamPreferences(Account account, Element prefs) {
3946		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3947		set.addChild(prefs);
3948		sendIqPacket(account, set, null);
3949	}
3950
3951	public interface OnAccountCreated {
3952		void onAccountCreated(Account account);
3953
3954		void informUser(int r);
3955	}
3956
3957	public interface OnMoreMessagesLoaded {
3958		void onMoreMessagesLoaded(int count, Conversation conversation);
3959
3960		void informUser(int r);
3961	}
3962
3963	public interface OnAccountPasswordChanged {
3964		void onPasswordChangeSucceeded();
3965
3966		void onPasswordChangeFailed();
3967	}
3968
3969	public interface OnAffiliationChanged {
3970		void onAffiliationChangedSuccessful(Jid jid);
3971
3972		void onAffiliationChangeFailed(Jid jid, int resId);
3973	}
3974
3975	public interface OnRoleChanged {
3976		void onRoleChangedSuccessful(String nick);
3977
3978		void onRoleChangeFailed(String nick, int resid);
3979	}
3980
3981	public interface OnConversationUpdate {
3982		void onConversationUpdate();
3983	}
3984
3985	public interface OnAccountUpdate {
3986		void onAccountUpdate();
3987	}
3988
3989	public interface OnCaptchaRequested {
3990		void onCaptchaRequested(Account account,
3991								String id,
3992								Data data,
3993								Bitmap captcha);
3994	}
3995
3996	public interface OnRosterUpdate {
3997		void onRosterUpdate();
3998	}
3999
4000	public interface OnMucRosterUpdate {
4001		void onMucRosterUpdate();
4002	}
4003
4004	public interface OnConferenceConfigurationFetched {
4005		void onConferenceConfigurationFetched(Conversation conversation);
4006
4007		void onFetchFailed(Conversation conversation, Element error);
4008	}
4009
4010	public interface OnConferenceJoined {
4011		void onConferenceJoined(Conversation conversation);
4012	}
4013
4014	public interface OnConfigurationPushed {
4015		void onPushSucceeded();
4016
4017		void onPushFailed();
4018	}
4019
4020	public interface OnShowErrorToast {
4021		void onShowErrorToast(int resId);
4022	}
4023
4024	public class XmppConnectionBinder extends Binder {
4025		public XmppConnectionService getService() {
4026			return XmppConnectionService.this;
4027		}
4028	}
4029}