1package eu.siacs.conversations.services;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.annotation.TargetApi;
6import android.app.AlarmManager;
7import android.app.Notification;
8import android.app.NotificationManager;
9import android.app.PendingIntent;
10import android.app.Service;
11import android.content.BroadcastReceiver;
12import android.content.ComponentName;
13import android.content.Context;
14import android.content.Intent;
15import android.content.IntentFilter;
16import android.content.SharedPreferences;
17import android.content.pm.PackageManager;
18import android.database.ContentObserver;
19import android.graphics.Bitmap;
20import android.media.AudioManager;
21import android.net.ConnectivityManager;
22import android.net.NetworkInfo;
23import android.net.Uri;
24import android.os.Binder;
25import android.os.Build;
26import android.os.Bundle;
27import android.os.Environment;
28import android.os.IBinder;
29import android.os.PowerManager;
30import android.os.PowerManager.WakeLock;
31import android.os.SystemClock;
32import android.preference.PreferenceManager;
33import android.provider.ContactsContract;
34import android.security.KeyChain;
35import android.support.annotation.BoolRes;
36import android.support.annotation.IntegerRes;
37import android.support.annotation.NonNull;
38import android.support.v4.app.RemoteInput;
39import android.support.v4.content.ContextCompat;
40import android.text.TextUtils;
41import android.util.DisplayMetrics;
42import android.util.Log;
43import android.util.LruCache;
44import android.util.Pair;
45
46import com.google.common.base.Strings;
47
48import org.conscrypt.Conscrypt;
49import org.openintents.openpgp.IOpenPgpService2;
50import org.openintents.openpgp.util.OpenPgpApi;
51import org.openintents.openpgp.util.OpenPgpServiceConnection;
52
53import java.io.File;
54import java.net.URL;
55import java.security.SecureRandom;
56import java.security.Security;
57import java.security.cert.CertificateException;
58import java.security.cert.X509Certificate;
59import java.util.ArrayList;
60import java.util.Arrays;
61import java.util.Collection;
62import java.util.Collections;
63import java.util.HashSet;
64import java.util.Hashtable;
65import java.util.Iterator;
66import java.util.List;
67import java.util.ListIterator;
68import java.util.Map;
69import java.util.Set;
70import java.util.WeakHashMap;
71import java.util.concurrent.CopyOnWriteArrayList;
72import java.util.concurrent.CountDownLatch;
73import java.util.concurrent.atomic.AtomicBoolean;
74import java.util.concurrent.atomic.AtomicLong;
75
76import eu.siacs.conversations.Config;
77import eu.siacs.conversations.R;
78import eu.siacs.conversations.android.JabberIdContact;
79import eu.siacs.conversations.crypto.OmemoSetting;
80import eu.siacs.conversations.crypto.PgpDecryptionService;
81import eu.siacs.conversations.crypto.PgpEngine;
82import eu.siacs.conversations.crypto.axolotl.AxolotlService;
83import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
84import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
85import eu.siacs.conversations.entities.Account;
86import eu.siacs.conversations.entities.Blockable;
87import eu.siacs.conversations.entities.Bookmark;
88import eu.siacs.conversations.entities.Contact;
89import eu.siacs.conversations.entities.Conversation;
90import eu.siacs.conversations.entities.Conversational;
91import eu.siacs.conversations.entities.Message;
92import eu.siacs.conversations.entities.MucOptions;
93import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
94import eu.siacs.conversations.entities.Presence;
95import eu.siacs.conversations.entities.PresenceTemplate;
96import eu.siacs.conversations.entities.Roster;
97import eu.siacs.conversations.entities.ServiceDiscoveryResult;
98import eu.siacs.conversations.generator.AbstractGenerator;
99import eu.siacs.conversations.generator.IqGenerator;
100import eu.siacs.conversations.generator.MessageGenerator;
101import eu.siacs.conversations.generator.PresenceGenerator;
102import eu.siacs.conversations.http.CustomURLStreamHandlerFactory;
103import eu.siacs.conversations.http.HttpConnectionManager;
104import eu.siacs.conversations.parser.AbstractParser;
105import eu.siacs.conversations.parser.IqParser;
106import eu.siacs.conversations.parser.MessageParser;
107import eu.siacs.conversations.parser.PresenceParser;
108import eu.siacs.conversations.persistance.DatabaseBackend;
109import eu.siacs.conversations.persistance.FileBackend;
110import eu.siacs.conversations.ui.ChooseAccountForProfilePictureActivity;
111import eu.siacs.conversations.ui.SettingsActivity;
112import eu.siacs.conversations.ui.UiCallback;
113import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
114import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
115import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
116import eu.siacs.conversations.utils.Compatibility;
117import eu.siacs.conversations.utils.ConversationsFileObserver;
118import eu.siacs.conversations.utils.CryptoHelper;
119import eu.siacs.conversations.utils.ExceptionHelper;
120import eu.siacs.conversations.utils.MimeUtils;
121import eu.siacs.conversations.utils.PhoneHelper;
122import eu.siacs.conversations.utils.QuickLoader;
123import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
124import eu.siacs.conversations.utils.ReplacingTaskManager;
125import eu.siacs.conversations.utils.Resolver;
126import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
127import eu.siacs.conversations.utils.StringUtils;
128import eu.siacs.conversations.utils.WakeLockHelper;
129import eu.siacs.conversations.utils.XmppUri;
130import eu.siacs.conversations.xml.Element;
131import eu.siacs.conversations.xml.Namespace;
132import eu.siacs.conversations.xmpp.OnBindListener;
133import eu.siacs.conversations.xmpp.OnContactStatusChanged;
134import eu.siacs.conversations.xmpp.OnIqPacketReceived;
135import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
136import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
137import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
138import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
139import eu.siacs.conversations.xmpp.OnStatusChanged;
140import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
141import eu.siacs.conversations.xmpp.Patches;
142import eu.siacs.conversations.xmpp.XmppConnection;
143import eu.siacs.conversations.xmpp.chatstate.ChatState;
144import eu.siacs.conversations.xmpp.forms.Data;
145import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
146import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
147import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
148import eu.siacs.conversations.xmpp.mam.MamReference;
149import eu.siacs.conversations.xmpp.pep.Avatar;
150import eu.siacs.conversations.xmpp.pep.PublishOptions;
151import eu.siacs.conversations.xmpp.stanzas.IqPacket;
152import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
153import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
154import me.leolin.shortcutbadger.ShortcutBadger;
155import rocks.xmpp.addr.Jid;
156
157public class XmppConnectionService extends Service {
158
159 public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
160 public static final String ACTION_MARK_AS_READ = "mark_as_read";
161 public static final String ACTION_SNOOZE = "snooze";
162 public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
163 public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
164 public static final String ACTION_TRY_AGAIN = "try_again";
165 public static final String ACTION_IDLE_PING = "idle_ping";
166 public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
167 public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
168 private static final String ACTION_POST_CONNECTIVITY_CHANGE = "eu.siacs.conversations.POST_CONNECTIVITY_CHANGE";
169
170 private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
171
172 static {
173 URL.setURLStreamHandlerFactory(new CustomURLStreamHandlerFactory());
174 }
175
176 public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
177 private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor("FileAdding");
178 private final SerialSingleThreadExecutor mVideoCompressionExecutor = new SerialSingleThreadExecutor("VideoCompression");
179 private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter");
180 private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader");
181 private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor");
182 private final ReplacingTaskManager mRosterSyncTaskManager = new ReplacingTaskManager();
183 private final IBinder mBinder = new XmppConnectionBinder();
184 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
185 private final IqGenerator mIqGenerator = new IqGenerator(this);
186 private final Set<String> mInProgressAvatarFetches = new HashSet<>();
187 private final Set<String> mOmittedPepAvatarFetches = new HashSet<>();
188 private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
189 private final OnIqPacketReceived mDefaultIqHandler = (account, packet) -> {
190 if (packet.getType() != IqPacket.TYPE.RESULT) {
191 Element error = packet.findChild("error");
192 String text = error != null ? error.findChildContent("text") : null;
193 if (text != null) {
194 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received iq error - " + text);
195 }
196 }
197 };
198 public DatabaseBackend databaseBackend;
199 private ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor("ContactMerger");
200 private long mLastActivity = 0;
201 private FileBackend fileBackend = new FileBackend(this);
202 private MemorizingTrustManager mMemorizingTrustManager;
203 private NotificationService mNotificationService = new NotificationService(this);
204 private ChannelDiscoveryService mChannelDiscoveryService = new ChannelDiscoveryService(this);
205 private ShortcutService mShortcutService = new ShortcutService(this);
206 private AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
207 private AtomicBoolean mForceForegroundService = new AtomicBoolean(false);
208 private AtomicBoolean mForceDuringOnCreate = new AtomicBoolean(false);
209 private OnMessagePacketReceived mMessageParser = new MessageParser(this);
210 private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
211 private IqParser mIqParser = new IqParser(this);
212 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
213 public OnContactStatusChanged onContactStatusChanged = (contact, online) -> {
214 Conversation conversation = find(getConversations(), contact);
215 if (conversation != null) {
216 if (online) {
217 if (contact.getPresences().size() == 1) {
218 sendUnsentMessages(conversation);
219 }
220 }
221 }
222 };
223 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
224 private List<Account> accounts;
225 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
226 this);
227 private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
228
229 @Override
230 public void onJinglePacketReceived(Account account, JinglePacket packet) {
231 mJingleConnectionManager.deliverPacket(account, packet);
232 }
233 };
234 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
235 private AvatarService mAvatarService = new AvatarService(this);
236 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
237 private PushManagementService mPushManagementService = new PushManagementService(this);
238 private QuickConversationsService mQuickConversationsService = new QuickConversationsService(this);
239 private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
240 Environment.getExternalStorageDirectory().getAbsolutePath()
241 ) {
242 @Override
243 public void onEvent(int event, String path) {
244 markFileDeleted(path);
245 }
246 };
247 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
248
249 @Override
250 public boolean onMessageAcknowledged(Account account, String uuid) {
251 for (final Conversation conversation : getConversations()) {
252 if (conversation.getAccount() == account) {
253 Message message = conversation.findUnsentMessageWithUuid(uuid);
254 if (message != null) {
255 message.setStatus(Message.STATUS_SEND);
256 message.setErrorMessage(null);
257 databaseBackend.updateMessage(message, false);
258 return true;
259 }
260 }
261 }
262 return false;
263 }
264 };
265
266 private boolean destroyed = false;
267
268 private int unreadCount = -1;
269
270 //Ui callback listeners
271 private final Set<OnConversationUpdate> mOnConversationUpdates = Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
272 private final Set<OnShowErrorToast> mOnShowErrorToasts = Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
273 private final Set<OnAccountUpdate> mOnAccountUpdates = Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
274 private final Set<OnCaptchaRequested> mOnCaptchaRequested = Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
275 private final Set<OnRosterUpdate> mOnRosterUpdates = Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
276 private final Set<OnUpdateBlocklist> mOnUpdateBlocklist = Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
277 private final Set<OnMucRosterUpdate> mOnMucRosterUpdate = Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
278 private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated = Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
279
280 private final Object LISTENER_LOCK = new Object();
281
282
283 public final Set<String> FILENAMES_TO_IGNORE_DELETION = new HashSet<>();
284
285
286 private final OnBindListener mOnBindListener = new OnBindListener() {
287
288 @Override
289 public void onBind(final Account account) {
290 synchronized (mInProgressAvatarFetches) {
291 for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
292 final String KEY = iterator.next();
293 if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
294 iterator.remove();
295 }
296 }
297 }
298 boolean loggedInSuccessfully = account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, true);
299 boolean gainedFeature = account.setOption(Account.OPTION_HTTP_UPLOAD_AVAILABLE, account.getXmppConnection().getFeatures().httpUpload(0));
300 if (loggedInSuccessfully || gainedFeature) {
301 databaseBackend.updateAccount(account);
302 }
303
304 if (loggedInSuccessfully) {
305 if (!TextUtils.isEmpty(account.getDisplayName())) {
306 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": display name wasn't empty on first log in. publishing");
307 publishDisplayName(account);
308 }
309 }
310
311 account.getRoster().clearPresences();
312 synchronized (account.inProgressConferenceJoins) {
313 account.inProgressConferenceJoins.clear();
314 }
315 synchronized (account.inProgressConferencePings) {
316 account.inProgressConferencePings.clear();
317 }
318 mJingleConnectionManager.cancelInTransmission();
319 mQuickConversationsService.considerSyncBackground(false);
320 fetchRosterFromServer(account);
321
322 final XmppConnection connection = account.getXmppConnection();
323
324 if (connection.getFeatures().bookmarks2()) {
325 fetchBookmarks2(account);
326 } else if (!account.getXmppConnection().getFeatures().bookmarksConversion()) {
327 fetchBookmarks(account);
328 }
329 final boolean flexible = account.getXmppConnection().getFeatures().flexibleOfflineMessageRetrieval();
330 final boolean catchup = getMessageArchiveService().inCatchup(account);
331 if (flexible && catchup && account.getXmppConnection().isMamPreferenceAlways()) {
332 sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> {
333 if (packet.getType() == IqPacket.TYPE.RESULT) {
334 Log.d(Config.LOGTAG, acc.getJid().asBareJid() + ": successfully purged offline messages");
335 }
336 });
337 }
338 sendPresence(account);
339 if (mPushManagementService.available(account)) {
340 mPushManagementService.registerPushTokenOnServer(account);
341 }
342 connectMultiModeConversations(account);
343 syncDirtyContacts(account);
344 }
345 };
346 private AtomicLong mLastExpiryRun = new AtomicLong(0);
347 private SecureRandom mRandom;
348 private LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache = new LruCache<>(20);
349 private OnStatusChanged statusListener = new OnStatusChanged() {
350
351 @Override
352 public void onStatusChanged(final Account account) {
353 XmppConnection connection = account.getXmppConnection();
354 updateAccountUi();
355
356 if (account.getStatus() == Account.State.ONLINE || account.getStatus().isError()) {
357 mQuickConversationsService.signalAccountStateChange();
358 }
359
360 if (account.getStatus() == Account.State.ONLINE) {
361 synchronized (mLowPingTimeoutMode) {
362 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
363 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
364 }
365 }
366 if (account.setShowErrorNotification(true)) {
367 databaseBackend.updateAccount(account);
368 }
369 mMessageArchiveService.executePendingQueries(account);
370 if (connection != null && connection.getFeatures().csi()) {
371 if (checkListeners()) {
372 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//inactive");
373 connection.sendInactive();
374 } else {
375 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//active");
376 connection.sendActive();
377 }
378 }
379 List<Conversation> conversations = getConversations();
380 for (Conversation conversation : conversations) {
381 final boolean inProgressJoin;
382 synchronized (account.inProgressConferenceJoins) {
383 inProgressJoin = account.inProgressConferenceJoins.contains(conversation);
384 }
385 final boolean pendingJoin;
386 synchronized (account.pendingConferenceJoins) {
387 pendingJoin = account.pendingConferenceJoins.contains(conversation);
388 }
389 if (conversation.getAccount() == account
390 && !pendingJoin
391 && !inProgressJoin) {
392 sendUnsentMessages(conversation);
393 }
394 }
395 final List<Conversation> pendingLeaves;
396 synchronized (account.pendingConferenceLeaves) {
397 pendingLeaves = new ArrayList<>(account.pendingConferenceLeaves);
398 account.pendingConferenceLeaves.clear();
399
400 }
401 for (Conversation conversation : pendingLeaves) {
402 leaveMuc(conversation);
403 }
404 final List<Conversation> pendingJoins;
405 synchronized (account.pendingConferenceJoins) {
406 pendingJoins = new ArrayList<>(account.pendingConferenceJoins);
407 account.pendingConferenceJoins.clear();
408 }
409 for (Conversation conversation : pendingJoins) {
410 joinMuc(conversation);
411 }
412 scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
413 } else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
414 resetSendingToWaiting(account);
415 if (account.isEnabled() && isInLowPingTimeoutMode(account)) {
416 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": went into offline state during low ping mode. reconnecting now");
417 reconnectAccount(account, true, false);
418 } else {
419 int timeToReconnect = mRandom.nextInt(10) + 2;
420 scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
421 }
422 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
423 databaseBackend.updateAccount(account);
424 reconnectAccount(account, true, false);
425 } else if (account.getStatus() != Account.State.CONNECTING && account.getStatus() != Account.State.NO_INTERNET) {
426 resetSendingToWaiting(account);
427 if (connection != null && account.getStatus().isAttemptReconnect()) {
428 final int next = connection.getTimeToNextAttempt();
429 final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
430 if (next <= 0) {
431 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + lowPingTimeoutMode);
432 reconnectAccount(account, true, false);
433 } else {
434 final int attempt = connection.getAttempt() + 1;
435 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + lowPingTimeoutMode);
436 scheduleWakeUpCall(next, account.getUuid().hashCode());
437 }
438 }
439 }
440 getNotificationService().updateErrorNotification();
441 }
442 };
443 private OpenPgpServiceConnection pgpServiceConnection;
444 private PgpEngine mPgpEngine = null;
445 private WakeLock wakeLock;
446 private PowerManager pm;
447 private LruCache<String, Bitmap> mBitmapCache;
448 private BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
449 private BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
450
451 private static String generateFetchKey(Account account, final Avatar avatar) {
452 return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
453 }
454
455 private boolean isInLowPingTimeoutMode(Account account) {
456 synchronized (mLowPingTimeoutMode) {
457 return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
458 }
459 }
460
461 public void startForcingForegroundNotification() {
462 mForceForegroundService.set(true);
463 toggleForegroundService();
464 }
465
466 public void stopForcingForegroundNotification() {
467 mForceForegroundService.set(false);
468 toggleForegroundService();
469 }
470
471 public boolean areMessagesInitialized() {
472 return this.restoredFromDatabaseLatch.getCount() == 0;
473 }
474
475 public PgpEngine getPgpEngine() {
476 if (!Config.supportOpenPgp()) {
477 return null;
478 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
479 if (this.mPgpEngine == null) {
480 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
481 getApplicationContext(),
482 pgpServiceConnection.getService()), this);
483 }
484 return mPgpEngine;
485 } else {
486 return null;
487 }
488
489 }
490
491 public OpenPgpApi getOpenPgpApi() {
492 if (!Config.supportOpenPgp()) {
493 return null;
494 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
495 return new OpenPgpApi(this, pgpServiceConnection.getService());
496 } else {
497 return null;
498 }
499 }
500
501 public FileBackend getFileBackend() {
502 return this.fileBackend;
503 }
504
505 public AvatarService getAvatarService() {
506 return this.mAvatarService;
507 }
508
509 public void attachLocationToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
510 int encryption = conversation.getNextEncryption();
511 if (encryption == Message.ENCRYPTION_PGP) {
512 encryption = Message.ENCRYPTION_DECRYPTED;
513 }
514 Message message = new Message(conversation, uri.toString(), encryption);
515 Message.configurePrivateMessage(message);
516 if (encryption == Message.ENCRYPTION_DECRYPTED) {
517 getPgpEngine().encrypt(message, callback);
518 } else {
519 sendMessage(message);
520 callback.success(message);
521 }
522 }
523
524 public void attachFileToConversation(final Conversation conversation, final Uri uri, final String type, final UiCallback<Message> callback) {
525 final Message message;
526 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
527 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
528 } else {
529 message = new Message(conversation, "", conversation.getNextEncryption());
530 }
531 if (!Message.configurePrivateFileMessage(message)) {
532 message.setCounterpart(conversation.getNextCounterpart());
533 message.setType(Message.TYPE_FILE);
534 }
535 Log.d(Config.LOGTAG, "attachFile: type=" + message.getType());
536 Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart());
537 final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback);
538 if (runnable.isVideoMessage()) {
539 mVideoCompressionExecutor.execute(runnable);
540 } else {
541 mFileAddingExecutor.execute(runnable);
542 }
543 }
544
545 public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
546 final String mimeType = MimeUtils.guessMimeTypeFromUri(this, uri);
547 final String compressPictures = getCompressPicturesPreference();
548
549 if ("never".equals(compressPictures)
550 || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
551 || (mimeType != null && mimeType.endsWith("/gif"))
552 || getFileBackend().unusualBounds(uri)) {
553 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": not compressing picture. sending as file");
554 attachFileToConversation(conversation, uri, mimeType, callback);
555 return;
556 }
557 final Message message;
558 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
559 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
560 } else {
561 message = new Message(conversation, "", conversation.getNextEncryption());
562 }
563 if (!Message.configurePrivateFileMessage(message)) {
564 message.setCounterpart(conversation.getNextCounterpart());
565 message.setType(Message.TYPE_IMAGE);
566 }
567 Log.d(Config.LOGTAG, "attachImage: type=" + message.getType());
568 mFileAddingExecutor.execute(() -> {
569 try {
570 getFileBackend().copyImageToPrivateStorage(message, uri);
571 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
572 final PgpEngine pgpEngine = getPgpEngine();
573 if (pgpEngine != null) {
574 pgpEngine.encrypt(message, callback);
575 } else if (callback != null) {
576 callback.error(R.string.unable_to_connect_to_keychain, null);
577 }
578 } else {
579 sendMessage(message);
580 callback.success(message);
581 }
582 } catch (final FileBackend.FileCopyException e) {
583 callback.error(e.getResId(), message);
584 }
585 });
586 }
587
588 public Conversation find(Bookmark bookmark) {
589 return find(bookmark.getAccount(), bookmark.getJid());
590 }
591
592 public Conversation find(final Account account, final Jid jid) {
593 return find(getConversations(), account, jid);
594 }
595
596 public boolean isMuc(final Account account, final Jid jid) {
597 final Conversation c = find(account, jid);
598 return c != null && c.getMode() == Conversational.MODE_MULTI;
599 }
600
601 public void search(List<String> term, OnSearchResultsAvailable onSearchResultsAvailable) {
602 MessageSearchTask.search(this, term, onSearchResultsAvailable);
603 }
604
605 @Override
606 public int onStartCommand(Intent intent, int flags, int startId) {
607 final String action = intent == null ? null : intent.getAction();
608 final boolean needsForegroundService = intent != null && intent.getBooleanExtra(EventReceiver.EXTRA_NEEDS_FOREGROUND_SERVICE, false);
609 if (needsForegroundService) {
610 Log.d(Config.LOGTAG, "toggle forced foreground service after receiving event (action=" + action + ")");
611 toggleForegroundService(true);
612 }
613 String pushedAccountHash = null;
614 String pushedChannelHash = null;
615 boolean interactive = false;
616 if (action != null) {
617 final String uuid = intent.getStringExtra("uuid");
618 switch (action) {
619 case ConnectivityManager.CONNECTIVITY_ACTION:
620 if (hasInternetConnection()) {
621 if (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0) {
622 schedulePostConnectivityChange();
623 }
624 if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
625 resetAllAttemptCounts(true, false);
626 }
627 }
628 break;
629 case Intent.ACTION_SHUTDOWN:
630 logoutAndSave(true);
631 return START_NOT_STICKY;
632 case ACTION_CLEAR_NOTIFICATION:
633 mNotificationExecutor.execute(() -> {
634 try {
635 final Conversation c = findConversationByUuid(uuid);
636 if (c != null) {
637 mNotificationService.clear(c);
638 } else {
639 mNotificationService.clear();
640 }
641 restoredFromDatabaseLatch.await();
642
643 } catch (InterruptedException e) {
644 Log.d(Config.LOGTAG, "unable to process clear notification");
645 }
646 });
647 break;
648 case ACTION_DISMISS_ERROR_NOTIFICATIONS:
649 dismissErrorNotifications();
650 break;
651 case ACTION_TRY_AGAIN:
652 resetAllAttemptCounts(false, true);
653 interactive = true;
654 break;
655 case ACTION_REPLY_TO_CONVERSATION:
656 Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
657 if (remoteInput == null) {
658 break;
659 }
660 final CharSequence body = remoteInput.getCharSequence("text_reply");
661 final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
662 if (body == null || body.length() <= 0) {
663 break;
664 }
665 mNotificationExecutor.execute(() -> {
666 try {
667 restoredFromDatabaseLatch.await();
668 final Conversation c = findConversationByUuid(uuid);
669 if (c != null) {
670 directReply(c, body.toString(), dismissNotification);
671 }
672 } catch (InterruptedException e) {
673 Log.d(Config.LOGTAG, "unable to process direct reply");
674 }
675 });
676 break;
677 case ACTION_MARK_AS_READ:
678 mNotificationExecutor.execute(() -> {
679 final Conversation c = findConversationByUuid(uuid);
680 if (c == null) {
681 Log.d(Config.LOGTAG, "received mark read intent for unknown conversation (" + uuid + ")");
682 return;
683 }
684 try {
685 restoredFromDatabaseLatch.await();
686 sendReadMarker(c, null);
687 } catch (InterruptedException e) {
688 Log.d(Config.LOGTAG, "unable to process notification read marker for conversation " + c.getName());
689 }
690
691 });
692 break;
693 case ACTION_SNOOZE:
694 mNotificationExecutor.execute(() -> {
695 final Conversation c = findConversationByUuid(uuid);
696 if (c == null) {
697 Log.d(Config.LOGTAG, "received snooze intent for unknown conversation (" + uuid + ")");
698 return;
699 }
700 c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
701 mNotificationService.clear(c);
702 updateConversation(c);
703 });
704 case AudioManager.RINGER_MODE_CHANGED_ACTION:
705 case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
706 if (dndOnSilentMode()) {
707 refreshAllPresences();
708 }
709 break;
710 case Intent.ACTION_SCREEN_ON:
711 deactivateGracePeriod();
712 case Intent.ACTION_SCREEN_OFF:
713 if (awayWhenScreenOff()) {
714 refreshAllPresences();
715 }
716 break;
717 case ACTION_FCM_TOKEN_REFRESH:
718 refreshAllFcmTokens();
719 break;
720 case ACTION_IDLE_PING:
721 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
722 scheduleNextIdlePing();
723 }
724 break;
725 case ACTION_FCM_MESSAGE_RECEIVED:
726 pushedAccountHash = intent.getStringExtra("account");
727 pushedChannelHash = intent.getStringExtra("channel");
728 Log.d(Config.LOGTAG, "push message arrived in service. account=" + pushedAccountHash);
729 break;
730 case Intent.ACTION_SEND:
731 Uri uri = intent.getData();
732 if (uri != null) {
733 Log.d(Config.LOGTAG, "received uri permission for " + uri.toString());
734 }
735 return START_STICKY;
736 }
737 }
738 synchronized (this) {
739 WakeLockHelper.acquire(wakeLock);
740 boolean pingNow = ConnectivityManager.CONNECTIVITY_ACTION.equals(action) || (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0 && ACTION_POST_CONNECTIVITY_CHANGE.equals(action));
741 final HashSet<Account> pingCandidates = new HashSet<>();
742 final String androidId = PhoneHelper.getAndroidId(this);
743 for (Account account : accounts) {
744 final boolean pushWasMeantForThisAccount = CryptoHelper.getAccountFingerprint(account, androidId).equals(pushedAccountHash);
745 pingNow |= processAccountState(account,
746 interactive,
747 "ui".equals(action),
748 pushWasMeantForThisAccount,
749 pingCandidates);
750 if (pushWasMeantForThisAccount && pushedChannelHash != null) {
751 checkMucStillJoined(account, pushedAccountHash, androidId);
752 }
753 }
754 if (pingNow) {
755 for (Account account : pingCandidates) {
756 final boolean lowTimeout = isInLowPingTimeoutMode(account);
757 account.getXmppConnection().sendPing();
758 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")");
759 scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
760 }
761 }
762 WakeLockHelper.release(wakeLock);
763 }
764 if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
765 expireOldMessages();
766 }
767 return START_STICKY;
768 }
769
770 private boolean processAccountState(Account account, boolean interactive, boolean isUiAction, boolean isAccountPushed, HashSet<Account> pingCandidates) {
771 boolean pingNow = false;
772 if (account.getStatus().isAttemptReconnect()) {
773 if (!hasInternetConnection()) {
774 account.setStatus(Account.State.NO_INTERNET);
775 if (statusListener != null) {
776 statusListener.onStatusChanged(account);
777 }
778 } else {
779 if (account.getStatus() == Account.State.NO_INTERNET) {
780 account.setStatus(Account.State.OFFLINE);
781 if (statusListener != null) {
782 statusListener.onStatusChanged(account);
783 }
784 }
785 if (account.getStatus() == Account.State.ONLINE) {
786 synchronized (mLowPingTimeoutMode) {
787 long lastReceived = account.getXmppConnection().getLastPacketReceived();
788 long lastSent = account.getXmppConnection().getLastPingSent();
789 long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
790 long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
791 int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().asBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
792 long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
793 if (lastSent > lastReceived) {
794 if (pingTimeoutIn < 0) {
795 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
796 this.reconnectAccount(account, true, interactive);
797 } else {
798 int secs = (int) (pingTimeoutIn / 1000);
799 this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
800 }
801 } else {
802 pingCandidates.add(account);
803 if (isAccountPushed) {
804 pingNow = true;
805 if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
806 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": entering low ping timeout mode");
807 }
808 } else if (msToNextPing <= 0) {
809 pingNow = true;
810 } else {
811 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
812 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
813 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
814 }
815 }
816 }
817 }
818 } else if (account.getStatus() == Account.State.OFFLINE) {
819 reconnectAccount(account, true, interactive);
820 } else if (account.getStatus() == Account.State.CONNECTING) {
821 long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
822 long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
823 long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
824 long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
825 if (timeout < 0) {
826 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast=" + secondsSinceLastConnect + ")");
827 account.getXmppConnection().resetAttemptCount(false);
828 reconnectAccount(account, true, interactive);
829 } else if (discoTimeout < 0) {
830 account.getXmppConnection().sendDiscoTimeout();
831 scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
832 } else {
833 scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
834 }
835 } else {
836 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
837 reconnectAccount(account, true, interactive);
838 }
839 }
840 }
841 }
842 return pingNow;
843 }
844
845 private void checkMucStillJoined(final Account account, final String hash, final String androidId) {
846 for (final Conversation conversation : this.conversations) {
847 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
848 Jid jid = conversation.getJid().asBareJid();
849 final String currentHash = CryptoHelper.getFingerprint(jid, androidId);
850 if (currentHash.equals(hash)) {
851 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received cloud push notification for MUC " + jid);
852 return;
853 }
854 }
855 }
856 mPushManagementService.unregisterChannel(account, hash);
857 }
858
859 public void reinitializeMuclumbusService() {
860 mChannelDiscoveryService.initializeMuclumbusService();
861 }
862
863 public void discoverChannels(String query, ChannelDiscoveryService.Method method, ChannelDiscoveryService.OnChannelSearchResultsFound onChannelSearchResultsFound) {
864 mChannelDiscoveryService.discover(Strings.nullToEmpty(query).trim(), method, onChannelSearchResultsFound);
865 }
866
867 public boolean isDataSaverDisabled() {
868 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
869 ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
870 return !connectivityManager.isActiveNetworkMetered()
871 || connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
872 } else {
873 return true;
874 }
875 }
876
877 private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) {
878 Message message = new Message(conversation, body, conversation.getNextEncryption());
879 message.markUnread();
880 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
881 getPgpEngine().encrypt(message, new UiCallback<Message>() {
882 @Override
883 public void success(Message message) {
884 if (dismissAfterReply) {
885 markRead((Conversation) message.getConversation(), true);
886 } else {
887 mNotificationService.pushFromDirectReply(message);
888 }
889 }
890
891 @Override
892 public void error(int errorCode, Message object) {
893
894 }
895
896 @Override
897 public void userInputRequired(PendingIntent pi, Message object) {
898
899 }
900 });
901 } else {
902 sendMessage(message);
903 if (dismissAfterReply) {
904 markRead(conversation, true);
905 } else {
906 mNotificationService.pushFromDirectReply(message);
907 }
908 }
909 }
910
911 private boolean dndOnSilentMode() {
912 return getBooleanPreference(SettingsActivity.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
913 }
914
915 private boolean manuallyChangePresence() {
916 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
917 }
918
919 private boolean treatVibrateAsSilent() {
920 return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
921 }
922
923 private boolean awayWhenScreenOff() {
924 return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
925 }
926
927 private String getCompressPicturesPreference() {
928 return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
929 }
930
931 private Presence.Status getTargetPresence() {
932 if (dndOnSilentMode() && isPhoneSilenced()) {
933 return Presence.Status.DND;
934 } else if (awayWhenScreenOff() && !isInteractive()) {
935 return Presence.Status.AWAY;
936 } else {
937 return Presence.Status.ONLINE;
938 }
939 }
940
941 @SuppressLint("NewApi")
942 @SuppressWarnings("deprecation")
943 public boolean isInteractive() {
944 try {
945 final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
946
947 final boolean isScreenOn;
948 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
949 isScreenOn = pm.isScreenOn();
950 } else {
951 isScreenOn = pm.isInteractive();
952 }
953 return isScreenOn;
954 } catch (RuntimeException e) {
955 return false;
956 }
957 }
958
959 private boolean isPhoneSilenced() {
960 final boolean notificationDnd;
961 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
962 final NotificationManager notificationManager = getSystemService(NotificationManager.class);
963 final int filter = notificationManager == null ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN : notificationManager.getCurrentInterruptionFilter();
964 notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
965 } else {
966 notificationDnd = false;
967 }
968 final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
969 final int ringerMode = audioManager == null ? AudioManager.RINGER_MODE_NORMAL : audioManager.getRingerMode();
970 try {
971 if (treatVibrateAsSilent()) {
972 return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
973 } else {
974 return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
975 }
976 } catch (Throwable throwable) {
977 Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
978 return notificationDnd;
979 }
980 }
981
982 private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
983 Log.d(Config.LOGTAG, "resetting all attempt counts");
984 for (Account account : accounts) {
985 if (account.hasErrorStatus() || reallyAll) {
986 final XmppConnection connection = account.getXmppConnection();
987 if (connection != null) {
988 connection.resetAttemptCount(retryImmediately);
989 }
990 }
991 if (account.setShowErrorNotification(true)) {
992 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
993 }
994 }
995 mNotificationService.updateErrorNotification();
996 }
997
998 private void dismissErrorNotifications() {
999 for (final Account account : this.accounts) {
1000 if (account.hasErrorStatus()) {
1001 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
1002 if (account.setShowErrorNotification(false)) {
1003 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1004 }
1005 }
1006 }
1007 }
1008
1009 private void expireOldMessages() {
1010 expireOldMessages(false);
1011 }
1012
1013 public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
1014 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1015 mDatabaseWriterExecutor.execute(() -> {
1016 long timestamp = getAutomaticMessageDeletionDate();
1017 if (timestamp > 0) {
1018 databaseBackend.expireOldMessages(timestamp);
1019 synchronized (XmppConnectionService.this.conversations) {
1020 for (Conversation conversation : XmppConnectionService.this.conversations) {
1021 conversation.expireOldMessages(timestamp);
1022 if (resetHasMessagesLeftOnServer) {
1023 conversation.messagesLoaded.set(true);
1024 conversation.setHasMessagesLeftOnServer(true);
1025 }
1026 }
1027 }
1028 updateConversationUi();
1029 }
1030 });
1031 }
1032
1033 public boolean hasInternetConnection() {
1034 final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
1035 try {
1036 final NetworkInfo activeNetwork = cm == null ? null : cm.getActiveNetworkInfo();
1037 return activeNetwork != null && (activeNetwork.isConnected() || activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET);
1038 } catch (RuntimeException e) {
1039 Log.d(Config.LOGTAG, "unable to check for internet connection", e);
1040 return true; //if internet connection can not be checked it is probably best to just try
1041 }
1042 }
1043
1044 @SuppressLint("TrulyRandom")
1045 @Override
1046 public void onCreate() {
1047 if (Compatibility.runsTwentySix()) {
1048 mNotificationService.initializeChannels();
1049 }
1050 mChannelDiscoveryService.initializeMuclumbusService();
1051 mForceDuringOnCreate.set(Compatibility.runsAndTargetsTwentySix(this));
1052 toggleForegroundService();
1053 this.destroyed = false;
1054 OmemoSetting.load(this);
1055 ExceptionHelper.init(getApplicationContext());
1056 try {
1057 Security.insertProviderAt(Conscrypt.newProvider(), 1);
1058 } catch (Throwable throwable) {
1059 Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
1060 }
1061 Resolver.init(this);
1062 this.mRandom = new SecureRandom();
1063 updateMemorizingTrustmanager();
1064 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
1065 final int cacheSize = maxMemory / 8;
1066 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
1067 @Override
1068 protected int sizeOf(final String key, final Bitmap bitmap) {
1069 return bitmap.getByteCount() / 1024;
1070 }
1071 };
1072 if (mLastActivity == 0) {
1073 mLastActivity = getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
1074 }
1075
1076 Log.d(Config.LOGTAG, "initializing database...");
1077 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
1078 Log.d(Config.LOGTAG, "restoring accounts...");
1079 this.accounts = databaseBackend.getAccounts();
1080 final SharedPreferences.Editor editor = getPreferences().edit();
1081 if (this.accounts.size() == 0 && Arrays.asList("Sony", "Sony Ericsson").contains(Build.MANUFACTURER)) {
1082 editor.putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, true);
1083 Log.d(Config.LOGTAG, Build.MANUFACTURER + " is on blacklist. enabling foreground service");
1084 }
1085 final boolean hasEnabledAccounts = hasEnabledAccounts();
1086 editor.putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
1087 editor.apply();
1088 toggleSetProfilePictureActivity(hasEnabledAccounts);
1089
1090 restoreFromDatabase();
1091
1092 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
1093 startContactObserver();
1094 }
1095 if (Compatibility.hasStoragePermission(this)) {
1096 Log.d(Config.LOGTAG, "starting file observer");
1097 mFileAddingExecutor.execute(this.fileObserver::startWatching);
1098 mFileAddingExecutor.execute(this::checkForDeletedFiles);
1099 }
1100 if (Config.supportOpenPgp()) {
1101 this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
1102 @Override
1103 public void onBound(IOpenPgpService2 service) {
1104 for (Account account : accounts) {
1105 final PgpDecryptionService pgp = account.getPgpDecryptionService();
1106 if (pgp != null) {
1107 pgp.continueDecryption(true);
1108 }
1109 }
1110 }
1111
1112 @Override
1113 public void onError(Exception e) {
1114 }
1115 });
1116 this.pgpServiceConnection.bindToService();
1117 }
1118
1119 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
1120 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1121
1122 toggleForegroundService();
1123 updateUnreadCountBadge();
1124 toggleScreenEventReceiver();
1125 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1126 scheduleNextIdlePing();
1127 IntentFilter intentFilter = new IntentFilter();
1128 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1129 intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1130 }
1131 intentFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1132 registerReceiver(this.mInternalEventReceiver, intentFilter);
1133 }
1134 mForceDuringOnCreate.set(false);
1135 toggleForegroundService();
1136 }
1137
1138 private void checkForDeletedFiles() {
1139 if (destroyed) {
1140 Log.d(Config.LOGTAG, "Do not check for deleted files because service has been destroyed");
1141 return;
1142 }
1143 final long start = SystemClock.elapsedRealtime();
1144 final List<DatabaseBackend.FilePathInfo> relativeFilePaths = databaseBackend.getFilePathInfo();
1145 final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1146 for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1147 if (destroyed) {
1148 Log.d(Config.LOGTAG, "Stop checking for deleted files because service has been destroyed");
1149 return;
1150 }
1151 final File file = fileBackend.getFileForPath(filePath.path);
1152 if (filePath.setDeleted(!file.exists())) {
1153 changed.add(filePath);
1154 }
1155 }
1156 final long duration = SystemClock.elapsedRealtime() - start;
1157 Log.d(Config.LOGTAG, "found " + changed.size() + " changed files on start up. total=" + relativeFilePaths.size() + ". (" + duration + "ms)");
1158 if (changed.size() > 0) {
1159 databaseBackend.markFilesAsChanged(changed);
1160 markChangedFiles(changed);
1161 }
1162 }
1163
1164 public void startContactObserver() {
1165 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) {
1166 @Override
1167 public void onChange(boolean selfChange) {
1168 super.onChange(selfChange);
1169 if (restoredFromDatabaseLatch.getCount() == 0) {
1170 loadPhoneContacts();
1171 }
1172 }
1173 });
1174 }
1175
1176 @Override
1177 public void onTrimMemory(int level) {
1178 super.onTrimMemory(level);
1179 if (level >= TRIM_MEMORY_COMPLETE) {
1180 Log.d(Config.LOGTAG, "clear cache due to low memory");
1181 getBitmapCache().evictAll();
1182 }
1183 }
1184
1185 @Override
1186 public void onDestroy() {
1187 try {
1188 unregisterReceiver(this.mInternalEventReceiver);
1189 } catch (IllegalArgumentException e) {
1190 //ignored
1191 }
1192 destroyed = false;
1193 fileObserver.stopWatching();
1194 super.onDestroy();
1195 }
1196
1197 public void restartFileObserver() {
1198 Log.d(Config.LOGTAG, "restarting file observer");
1199 mFileAddingExecutor.execute(this.fileObserver::restartWatching);
1200 mFileAddingExecutor.execute(this::checkForDeletedFiles);
1201 }
1202
1203 public void toggleScreenEventReceiver() {
1204 if (awayWhenScreenOff() && !manuallyChangePresence()) {
1205 final IntentFilter filter = new IntentFilter();
1206 filter.addAction(Intent.ACTION_SCREEN_ON);
1207 filter.addAction(Intent.ACTION_SCREEN_OFF);
1208 registerReceiver(this.mInternalScreenEventReceiver, filter);
1209 } else {
1210 try {
1211 unregisterReceiver(this.mInternalScreenEventReceiver);
1212 } catch (IllegalArgumentException e) {
1213 //ignored
1214 }
1215 }
1216 }
1217
1218 public void toggleForegroundService() {
1219 toggleForegroundService(false);
1220 }
1221
1222 private void toggleForegroundService(boolean force) {
1223 final boolean status;
1224 if (force || mForceDuringOnCreate.get() || mForceForegroundService.get() || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1225 final Notification notification = this.mNotificationService.createForegroundNotification();
1226 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, notification);
1227 if (!mForceForegroundService.get()) {
1228 mNotificationService.notify(NotificationService.FOREGROUND_NOTIFICATION_ID, notification);
1229 }
1230 status = true;
1231 } else {
1232 stopForeground(true);
1233 status = false;
1234 }
1235 if (!mForceForegroundService.get()) {
1236 mNotificationService.dismissForcedForegroundNotification(); //if the channel was changed the previous call might fail
1237 }
1238 Log.d(Config.LOGTAG, "ForegroundService: " + (status ? "on" : "off"));
1239 }
1240
1241 public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1242 return !mForceForegroundService.get() && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1243 }
1244
1245 @Override
1246 public void onTaskRemoved(final Intent rootIntent) {
1247 super.onTaskRemoved(rootIntent);
1248 if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get()) {
1249 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1250 } else {
1251 this.logoutAndSave(false);
1252 }
1253 }
1254
1255 private void logoutAndSave(boolean stop) {
1256 int activeAccounts = 0;
1257 for (final Account account : accounts) {
1258 if (account.getStatus() != Account.State.DISABLED) {
1259 databaseBackend.writeRoster(account.getRoster());
1260 activeAccounts++;
1261 }
1262 if (account.getXmppConnection() != null) {
1263 new Thread(() -> disconnect(account, false)).start();
1264 }
1265 }
1266 if (stop || activeAccounts == 0) {
1267 Log.d(Config.LOGTAG, "good bye");
1268 stopSelf();
1269 }
1270 }
1271
1272 private void schedulePostConnectivityChange() {
1273 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1274 if (alarmManager == null) {
1275 return;
1276 }
1277 final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1278 final Intent intent = new Intent(this, EventReceiver.class);
1279 intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1280 try {
1281 final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
1282 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1283 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1284 } else {
1285 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1286 }
1287 } catch (RuntimeException e) {
1288 Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1289 }
1290 }
1291
1292 public void scheduleWakeUpCall(int seconds, int requestCode) {
1293 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1294 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1295 if (alarmManager == null) {
1296 return;
1297 }
1298 final Intent intent = new Intent(this, EventReceiver.class);
1299 intent.setAction("ping");
1300 try {
1301 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1302 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1303 } catch (RuntimeException e) {
1304 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1305 }
1306 }
1307
1308 @TargetApi(Build.VERSION_CODES.M)
1309 private void scheduleNextIdlePing() {
1310 final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1311 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1312 if (alarmManager == null) {
1313 return;
1314 }
1315 final Intent intent = new Intent(this, EventReceiver.class);
1316 intent.setAction(ACTION_IDLE_PING);
1317 try {
1318 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
1319 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1320 } catch (RuntimeException e) {
1321 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1322 }
1323 }
1324
1325 public XmppConnection createConnection(final Account account) {
1326 final XmppConnection connection = new XmppConnection(account, this);
1327 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1328 connection.setOnStatusChangedListener(this.statusListener);
1329 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1330 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1331 connection.setOnJinglePacketReceivedListener(this.jingleListener);
1332 connection.setOnBindListener(this.mOnBindListener);
1333 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1334 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1335 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1336 AxolotlService axolotlService = account.getAxolotlService();
1337 if (axolotlService != null) {
1338 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1339 }
1340 return connection;
1341 }
1342
1343 public void sendChatState(Conversation conversation) {
1344 if (sendChatStates()) {
1345 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1346 sendMessagePacket(conversation.getAccount(), packet);
1347 }
1348 }
1349
1350 private void sendFileMessage(final Message message, final boolean delay) {
1351 Log.d(Config.LOGTAG, "send file message");
1352 final Account account = message.getConversation().getAccount();
1353 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1354 || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1355 mHttpConnectionManager.createNewUploadConnection(message, delay);
1356 } else {
1357 mJingleConnectionManager.createNewConnection(message);
1358 }
1359 }
1360
1361 public void sendMessage(final Message message) {
1362 sendMessage(message, false, false);
1363 }
1364
1365 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1366 final Account account = message.getConversation().getAccount();
1367 if (account.setShowErrorNotification(true)) {
1368 databaseBackend.updateAccount(account);
1369 mNotificationService.updateErrorNotification();
1370 }
1371 final Conversation conversation = (Conversation) message.getConversation();
1372 account.deactivateGracePeriod();
1373
1374
1375 if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1376 final Contact contact = conversation.getContact();
1377 if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1378 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1379 createContact(contact, true);
1380 }
1381 }
1382
1383 MessagePacket packet = null;
1384 final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1385 || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1386 && !message.edited();
1387 boolean saveInDb = addToConversation;
1388 message.setStatus(Message.STATUS_WAITING);
1389
1390 if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1391 if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1392 databaseBackend.updateConversation(conversation);
1393 }
1394 }
1395
1396 final boolean inProgressJoin = isJoinInProgress(conversation);
1397
1398
1399 if (account.isOnlineAndConnected() && !inProgressJoin) {
1400 switch (message.getEncryption()) {
1401 case Message.ENCRYPTION_NONE:
1402 if (message.needsUploading()) {
1403 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1404 || conversation.getMode() == Conversation.MODE_MULTI
1405 || message.fixCounterpart()) {
1406 this.sendFileMessage(message, delay);
1407 } else {
1408 break;
1409 }
1410 } else {
1411 packet = mMessageGenerator.generateChat(message);
1412 }
1413 break;
1414 case Message.ENCRYPTION_PGP:
1415 case Message.ENCRYPTION_DECRYPTED:
1416 if (message.needsUploading()) {
1417 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1418 || conversation.getMode() == Conversation.MODE_MULTI
1419 || message.fixCounterpart()) {
1420 this.sendFileMessage(message, delay);
1421 } else {
1422 break;
1423 }
1424 } else {
1425 packet = mMessageGenerator.generatePgpChat(message);
1426 }
1427 break;
1428 case Message.ENCRYPTION_AXOLOTL:
1429 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1430 if (message.needsUploading()) {
1431 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1432 || conversation.getMode() == Conversation.MODE_MULTI
1433 || message.fixCounterpart()) {
1434 this.sendFileMessage(message, delay);
1435 } else {
1436 break;
1437 }
1438 } else {
1439 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1440 if (axolotlMessage == null) {
1441 account.getAxolotlService().preparePayloadMessage(message, delay);
1442 } else {
1443 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1444 }
1445 }
1446 break;
1447
1448 }
1449 if (packet != null) {
1450 if (account.getXmppConnection().getFeatures().sm()
1451 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1452 message.setStatus(Message.STATUS_UNSEND);
1453 } else {
1454 message.setStatus(Message.STATUS_SEND);
1455 }
1456 }
1457 } else {
1458 switch (message.getEncryption()) {
1459 case Message.ENCRYPTION_DECRYPTED:
1460 if (!message.needsUploading()) {
1461 String pgpBody = message.getEncryptedBody();
1462 String decryptedBody = message.getBody();
1463 message.setBody(pgpBody); //TODO might throw NPE
1464 message.setEncryption(Message.ENCRYPTION_PGP);
1465 if (message.edited()) {
1466 message.setBody(decryptedBody);
1467 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1468 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1469 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1470 }
1471 updateConversationUi();
1472 return;
1473 } else {
1474 databaseBackend.createMessage(message);
1475 saveInDb = false;
1476 message.setBody(decryptedBody);
1477 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1478 }
1479 }
1480 break;
1481 case Message.ENCRYPTION_AXOLOTL:
1482 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1483 break;
1484 }
1485 }
1486
1487
1488 boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1489 if (mucMessage) {
1490 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1491 }
1492
1493 if (resend) {
1494 if (packet != null && addToConversation) {
1495 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1496 markMessage(message, Message.STATUS_UNSEND);
1497 } else {
1498 markMessage(message, Message.STATUS_SEND);
1499 }
1500 }
1501 } else {
1502 if (addToConversation) {
1503 conversation.add(message);
1504 }
1505 if (saveInDb) {
1506 databaseBackend.createMessage(message);
1507 } else if (message.edited()) {
1508 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1509 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1510 }
1511 }
1512 updateConversationUi();
1513 }
1514 if (packet != null) {
1515 if (delay) {
1516 mMessageGenerator.addDelay(packet, message.getTimeSent());
1517 }
1518 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1519 if (this.sendChatStates()) {
1520 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1521 }
1522 }
1523 sendMessagePacket(account, packet);
1524 }
1525 }
1526
1527 private boolean isJoinInProgress(final Conversation conversation) {
1528 final Account account = conversation.getAccount();
1529 synchronized (account.inProgressConferenceJoins) {
1530 if (conversation.getMode() == Conversational.MODE_MULTI) {
1531 final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1532 final boolean pending = account.pendingConferenceJoins.contains(conversation);
1533 final boolean inProgressJoin = inProgress || pending;
1534 if (inProgressJoin) {
1535 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
1536 }
1537 return inProgressJoin;
1538 } else {
1539 return false;
1540 }
1541 }
1542 }
1543
1544 private void sendUnsentMessages(final Conversation conversation) {
1545 conversation.findWaitingMessages(message -> resendMessage(message, true));
1546 }
1547
1548 public void resendMessage(final Message message, final boolean delay) {
1549 sendMessage(message, true, delay);
1550 }
1551
1552 public void fetchRosterFromServer(final Account account) {
1553 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1554 if (!"".equals(account.getRosterVersion())) {
1555 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1556 + ": fetching roster version " + account.getRosterVersion());
1557 } else {
1558 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1559 }
1560 iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1561 sendIqPacket(account, iqPacket, mIqParser);
1562 }
1563
1564 public void fetchBookmarks(final Account account) {
1565 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1566 final Element query = iqPacket.query("jabber:iq:private");
1567 query.addChild("storage", Namespace.BOOKMARKS);
1568 final OnIqPacketReceived callback = (a, response) -> {
1569 if (response.getType() == IqPacket.TYPE.RESULT) {
1570 final Element query1 = response.query();
1571 final Element storage = query1.findChild("storage", "storage:bookmarks");
1572 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
1573 processBookmarksInitial(a, bookmarks, false);
1574 } else {
1575 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1576 }
1577 };
1578 sendIqPacket(account, iqPacket, callback);
1579 }
1580
1581 public void fetchBookmarks2(final Account account) {
1582 final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
1583 sendIqPacket(account, retrieve, new OnIqPacketReceived() {
1584 @Override
1585 public void onIqPacketReceived(final Account account, final IqPacket response) {
1586 if (response.getType() == IqPacket.TYPE.RESULT) {
1587 final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
1588 final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, account);
1589 processBookmarksInitial(account, bookmarks, true);
1590 }
1591 }
1592 });
1593 }
1594
1595 public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
1596 final Set<Jid> previousBookmarks = account.getBookmarkedJids();
1597 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1598 for (Bookmark bookmark : bookmarks.values()) {
1599 previousBookmarks.remove(bookmark.getJid().asBareJid());
1600 processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
1601 }
1602 if (pep && synchronizeWithBookmarks) {
1603 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
1604 for (Jid jid : previousBookmarks) {
1605 processDeletedBookmark(account, jid);
1606 }
1607 }
1608 account.setBookmarks(bookmarks);
1609 }
1610
1611 public void processDeletedBookmark(Account account, Jid jid) {
1612 final Conversation conversation = find(account, jid);
1613 if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
1614 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
1615 archiveConversation(conversation, false);
1616 }
1617 }
1618
1619 private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
1620 final Account account = bookmark.getAccount();
1621 Conversation conversation = find(bookmark);
1622 if (conversation != null) {
1623 if (conversation.getMode() != Conversation.MODE_MULTI) {
1624 return;
1625 }
1626 bookmark.setConversation(conversation);
1627 if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
1628 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
1629 archiveConversation(conversation, false);
1630 } else {
1631 final MucOptions mucOptions = conversation.getMucOptions();
1632 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
1633 final String current = mucOptions.getActualNick();
1634 final String proposed = mucOptions.getProposedNick();
1635 if (current != null && !current.equals(proposed)) {
1636 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
1637 joinMuc(conversation);
1638 }
1639 }
1640 }
1641 } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
1642 conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
1643 bookmark.setConversation(conversation);
1644 }
1645 }
1646
1647 public void processModifiedBookmark(Bookmark bookmark) {
1648 final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1649 processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
1650 }
1651
1652 public void createBookmark(final Account account, final Bookmark bookmark) {
1653 account.putBookmark(bookmark);
1654 final XmppConnection connection = account.getXmppConnection();
1655 if (connection.getFeatures().bookmarks2()) {
1656 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
1657 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
1658 } else if (connection.getFeatures().bookmarksConversion()) {
1659 pushBookmarksPep(account);
1660 } else {
1661 pushBookmarksPrivateXml(account);
1662 }
1663 }
1664
1665 public void deleteBookmark(final Account account, final Bookmark bookmark) {
1666 account.removeBookmark(bookmark);
1667 final XmppConnection connection = account.getXmppConnection();
1668 if (connection.getFeatures().bookmarks2()) {
1669 IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
1670 sendIqPacket(account, request, (a, response) -> {
1671 if (response.getType() == IqPacket.TYPE.ERROR) {
1672 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getError());
1673 }
1674 });
1675 } else if (connection.getFeatures().bookmarksConversion()) {
1676 pushBookmarksPep(account);
1677 } else {
1678 pushBookmarksPrivateXml(account);
1679 }
1680 }
1681
1682 private void pushBookmarksPrivateXml(Account account) {
1683 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1684 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1685 Element query = iqPacket.query("jabber:iq:private");
1686 Element storage = query.addChild("storage", "storage:bookmarks");
1687 for (Bookmark bookmark : account.getBookmarks()) {
1688 storage.addChild(bookmark);
1689 }
1690 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1691 }
1692
1693 private void pushBookmarksPep(Account account) {
1694 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1695 Element storage = new Element("storage", "storage:bookmarks");
1696 for (Bookmark bookmark : account.getBookmarks()) {
1697 storage.addChild(bookmark);
1698 }
1699 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, PublishOptions.persistentWhitelistAccess());
1700
1701 }
1702
1703 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options) {
1704 pushNodeAndEnforcePublishOptions(account, node, element, null, options, true);
1705
1706 }
1707
1708 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1709 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1710
1711 }
1712
1713 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1714 final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1715 sendIqPacket(account, packet, (a, response) -> {
1716 if (response.getType() == IqPacket.TYPE.RESULT) {
1717 return;
1718 }
1719 if (retry && PublishOptions.preconditionNotMet(response)) {
1720 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1721 @Override
1722 public void onPushSucceeded() {
1723 pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
1724 }
1725
1726 @Override
1727 public void onPushFailed() {
1728 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
1729 }
1730 });
1731 } else {
1732 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + Boolean.toString(retry) + ") " + response);
1733 }
1734 });
1735 }
1736
1737 private void restoreFromDatabase() {
1738 synchronized (this.conversations) {
1739 final Map<String, Account> accountLookupTable = new Hashtable<>();
1740 for (Account account : this.accounts) {
1741 accountLookupTable.put(account.getUuid(), account);
1742 }
1743 Log.d(Config.LOGTAG, "restoring conversations...");
1744 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1745 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1746 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1747 Conversation conversation = iterator.next();
1748 Account account = accountLookupTable.get(conversation.getAccountUuid());
1749 if (account != null) {
1750 conversation.setAccount(account);
1751 } else {
1752 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1753 iterator.remove();
1754 }
1755 }
1756 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1757 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1758 Runnable runnable = () -> {
1759 long deletionDate = getAutomaticMessageDeletionDate();
1760 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1761 if (deletionDate > 0) {
1762 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1763 databaseBackend.expireOldMessages(deletionDate);
1764 }
1765 Log.d(Config.LOGTAG, "restoring roster...");
1766 for (Account account : accounts) {
1767 databaseBackend.readRoster(account.getRoster());
1768 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1769 }
1770 getBitmapCache().evictAll();
1771 loadPhoneContacts();
1772 Log.d(Config.LOGTAG, "restoring messages...");
1773 final long startMessageRestore = SystemClock.elapsedRealtime();
1774 final Conversation quickLoad = QuickLoader.get(this.conversations);
1775 if (quickLoad != null) {
1776 restoreMessages(quickLoad);
1777 updateConversationUi();
1778 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1779 Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
1780 }
1781 for (Conversation conversation : this.conversations) {
1782 if (quickLoad != conversation) {
1783 restoreMessages(conversation);
1784 }
1785 }
1786 mNotificationService.finishBacklog(false);
1787 restoredFromDatabaseLatch.countDown();
1788 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1789 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1790 updateConversationUi();
1791 };
1792 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1793 }
1794 }
1795
1796 private void restoreMessages(Conversation conversation) {
1797 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1798 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1799 conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message));
1800 }
1801
1802 public void loadPhoneContacts() {
1803 mContactMergerExecutor.execute(() -> {
1804 Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
1805 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1806 for (Account account : accounts) {
1807 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
1808 for (JabberIdContact jidContact : contacts.values()) {
1809 final Contact contact = account.getRoster().getContact(jidContact.getJid());
1810 boolean needsCacheClean = contact.setPhoneContact(jidContact);
1811 if (needsCacheClean) {
1812 getAvatarService().clear(contact);
1813 }
1814 withSystemAccounts.remove(contact);
1815 }
1816 for (Contact contact : withSystemAccounts) {
1817 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
1818 if (needsCacheClean) {
1819 getAvatarService().clear(contact);
1820 }
1821 }
1822 }
1823 Log.d(Config.LOGTAG, "finished merging phone contacts");
1824 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1825 updateRosterUi();
1826 mQuickConversationsService.considerSync();
1827 });
1828 }
1829
1830
1831 public void syncRoster(final Account account) {
1832 mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1833 }
1834
1835 public List<Conversation> getConversations() {
1836 return this.conversations;
1837 }
1838
1839 private void markFileDeleted(final String path) {
1840 synchronized (FILENAMES_TO_IGNORE_DELETION) {
1841 if (FILENAMES_TO_IGNORE_DELETION.remove(path)) {
1842 Log.d(Config.LOGTAG,"ignored deletion of "+path);
1843 return;
1844 }
1845 }
1846 final File file = new File(path);
1847 final boolean isInternalFile = fileBackend.isInternalFile(file);
1848 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
1849 Log.d(Config.LOGTAG, "deleted file " + path + " internal=" + isInternalFile + ", database hits=" + uuids.size());
1850 markUuidsAsDeletedFiles(uuids);
1851 }
1852
1853 private void markUuidsAsDeletedFiles(List<String> uuids) {
1854 boolean deleted = false;
1855 for (Conversation conversation : getConversations()) {
1856 deleted |= conversation.markAsDeleted(uuids);
1857 }
1858 if (deleted) {
1859 updateConversationUi();
1860 }
1861 }
1862
1863 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
1864 boolean changed = false;
1865 for (Conversation conversation : getConversations()) {
1866 changed |= conversation.markAsChanged(infos);
1867 }
1868 if (changed) {
1869 updateConversationUi();
1870 }
1871 }
1872
1873 public void populateWithOrderedConversations(final List<Conversation> list) {
1874 populateWithOrderedConversations(list, true, true);
1875 }
1876
1877 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
1878 populateWithOrderedConversations(list, includeNoFileUpload, true);
1879 }
1880
1881 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
1882 final List<String> orderedUuids;
1883 if (sort) {
1884 orderedUuids = null;
1885 } else {
1886 orderedUuids = new ArrayList<>();
1887 for (Conversation conversation : list) {
1888 orderedUuids.add(conversation.getUuid());
1889 }
1890 }
1891 list.clear();
1892 if (includeNoFileUpload) {
1893 list.addAll(getConversations());
1894 } else {
1895 for (Conversation conversation : getConversations()) {
1896 if (conversation.getMode() == Conversation.MODE_SINGLE
1897 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
1898 list.add(conversation);
1899 }
1900 }
1901 }
1902 try {
1903 if (orderedUuids != null) {
1904 Collections.sort(list, (a, b) -> {
1905 final int indexA = orderedUuids.indexOf(a.getUuid());
1906 final int indexB = orderedUuids.indexOf(b.getUuid());
1907 if (indexA == -1 || indexB == -1 || indexA == indexB) {
1908 return a.compareTo(b);
1909 }
1910 return indexA - indexB;
1911 });
1912 } else {
1913 Collections.sort(list);
1914 }
1915 } catch (IllegalArgumentException e) {
1916 //ignore
1917 }
1918 }
1919
1920 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1921 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1922 return;
1923 } else if (timestamp == 0) {
1924 return;
1925 }
1926 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1927 final Runnable runnable = () -> {
1928 final Account account = conversation.getAccount();
1929 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1930 if (messages.size() > 0) {
1931 conversation.addAll(0, messages);
1932 callback.onMoreMessagesLoaded(messages.size(), conversation);
1933 } else if (conversation.hasMessagesLeftOnServer()
1934 && account.isOnlineAndConnected()
1935 && conversation.getLastClearHistory().getTimestamp() == 0) {
1936 final boolean mamAvailable;
1937 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1938 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
1939 } else {
1940 mamAvailable = conversation.getMucOptions().mamSupport();
1941 }
1942 if (mamAvailable) {
1943 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
1944 if (query != null) {
1945 query.setCallback(callback);
1946 callback.informUser(R.string.fetching_history_from_server);
1947 } else {
1948 callback.informUser(R.string.not_fetching_history_retention_period);
1949 }
1950
1951 }
1952 }
1953 };
1954 mDatabaseReaderExecutor.execute(runnable);
1955 }
1956
1957 public List<Account> getAccounts() {
1958 return this.accounts;
1959 }
1960
1961
1962 /**
1963 * This will find all conferences with the contact as member and also the conference that is the contact (that 'fake' contact is used to store the avatar)
1964 */
1965 public List<Conversation> findAllConferencesWith(Contact contact) {
1966 final ArrayList<Conversation> results = new ArrayList<>();
1967 for (final Conversation c : conversations) {
1968 if (c.getMode() != Conversation.MODE_MULTI) {
1969 continue;
1970 }
1971 final MucOptions mucOptions = c.getMucOptions();
1972 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
1973 results.add(c);
1974 }
1975 }
1976 return results;
1977 }
1978
1979 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1980 for (final Conversation conversation : haystack) {
1981 if (conversation.getContact() == contact) {
1982 return conversation;
1983 }
1984 }
1985 return null;
1986 }
1987
1988 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1989 if (jid == null) {
1990 return null;
1991 }
1992 for (final Conversation conversation : haystack) {
1993 if ((account == null || conversation.getAccount() == account)
1994 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
1995 return conversation;
1996 }
1997 }
1998 return null;
1999 }
2000
2001 public boolean isConversationsListEmpty(final Conversation ignore) {
2002 synchronized (this.conversations) {
2003 final int size = this.conversations.size();
2004 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2005 }
2006 }
2007
2008 public boolean isConversationStillOpen(final Conversation conversation) {
2009 synchronized (this.conversations) {
2010 for (Conversation current : this.conversations) {
2011 if (current == conversation) {
2012 return true;
2013 }
2014 }
2015 }
2016 return false;
2017 }
2018
2019 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2020 return this.findOrCreateConversation(account, jid, muc, false, async);
2021 }
2022
2023 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2024 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2025 }
2026
2027 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2028 synchronized (this.conversations) {
2029 Conversation conversation = find(account, jid);
2030 if (conversation != null) {
2031 return conversation;
2032 }
2033 conversation = databaseBackend.findConversation(account, jid);
2034 final boolean loadMessagesFromDb;
2035 if (conversation != null) {
2036 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2037 conversation.setAccount(account);
2038 if (muc) {
2039 conversation.setMode(Conversation.MODE_MULTI);
2040 conversation.setContactJid(jid);
2041 } else {
2042 conversation.setMode(Conversation.MODE_SINGLE);
2043 conversation.setContactJid(jid.asBareJid());
2044 }
2045 databaseBackend.updateConversation(conversation);
2046 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2047 } else {
2048 String conversationName;
2049 Contact contact = account.getRoster().getContact(jid);
2050 if (contact != null) {
2051 conversationName = contact.getDisplayName();
2052 } else {
2053 conversationName = jid.getLocal();
2054 }
2055 if (muc) {
2056 conversation = new Conversation(conversationName, account, jid,
2057 Conversation.MODE_MULTI);
2058 } else {
2059 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2060 Conversation.MODE_SINGLE);
2061 }
2062 this.databaseBackend.createConversation(conversation);
2063 loadMessagesFromDb = false;
2064 }
2065 final Conversation c = conversation;
2066 final Runnable runnable = () -> {
2067 if (loadMessagesFromDb) {
2068 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2069 updateConversationUi();
2070 c.messagesLoaded.set(true);
2071 }
2072 if (account.getXmppConnection() != null
2073 && !c.getContact().isBlocked()
2074 && account.getXmppConnection().getFeatures().mam()
2075 && !muc) {
2076 if (query == null) {
2077 mMessageArchiveService.query(c);
2078 } else {
2079 if (query.getConversation() == null) {
2080 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2081 }
2082 }
2083 }
2084 if (joinAfterCreate) {
2085 joinMuc(c);
2086 }
2087 };
2088 if (async) {
2089 mDatabaseReaderExecutor.execute(runnable);
2090 } else {
2091 runnable.run();
2092 }
2093 this.conversations.add(conversation);
2094 updateConversationUi();
2095 return conversation;
2096 }
2097 }
2098
2099 public void archiveConversation(Conversation conversation) {
2100 archiveConversation(conversation, true);
2101 }
2102
2103 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2104 getNotificationService().clear(conversation);
2105 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2106 conversation.setNextMessage(null);
2107 synchronized (this.conversations) {
2108 getMessageArchiveService().kill(conversation);
2109 if (conversation.getMode() == Conversation.MODE_MULTI) {
2110 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2111 final Bookmark bookmark = conversation.getBookmark();
2112 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2113 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2114 Account account = bookmark.getAccount();
2115 bookmark.setConversation(null);
2116 deleteBookmark(account, bookmark);
2117 } else if (bookmark.autojoin()) {
2118 bookmark.setAutojoin(false);
2119 createBookmark(bookmark.getAccount(), bookmark);
2120 }
2121 }
2122 }
2123 if (conversation.getMucOptions().push()) {
2124 disableDirectMucPush(conversation);
2125 mPushManagementService.disablePushOnServer(conversation);
2126 }
2127 leaveMuc(conversation);
2128 } else {
2129 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2130 stopPresenceUpdatesTo(conversation.getContact());
2131 }
2132 }
2133 updateConversation(conversation);
2134 this.conversations.remove(conversation);
2135 updateConversationUi();
2136 }
2137 }
2138
2139 public void stopPresenceUpdatesTo(Contact contact) {
2140 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2141 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2142 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2143 }
2144
2145 public void createAccount(final Account account) {
2146 account.initAccountServices(this);
2147 databaseBackend.createAccount(account);
2148 this.accounts.add(account);
2149 this.reconnectAccountInBackground(account);
2150 updateAccountUi();
2151 syncEnabledAccountSetting();
2152 toggleForegroundService();
2153 }
2154
2155 private void syncEnabledAccountSetting() {
2156 final boolean hasEnabledAccounts = hasEnabledAccounts();
2157 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2158 toggleSetProfilePictureActivity(hasEnabledAccounts);
2159 }
2160
2161 private void toggleSetProfilePictureActivity(final boolean enabled) {
2162 try {
2163 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2164 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2165 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2166 } catch (IllegalStateException e) {
2167 Log.d(Config.LOGTAG, "unable to toggle profile picture actvitiy");
2168 }
2169 }
2170
2171 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2172 new Thread(() -> {
2173 try {
2174 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2175 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2176 if (cert == null) {
2177 callback.informUser(R.string.unable_to_parse_certificate);
2178 return;
2179 }
2180 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2181 if (info == null) {
2182 callback.informUser(R.string.certificate_does_not_contain_jid);
2183 return;
2184 }
2185 if (findAccountByJid(info.first) == null) {
2186 Account account = new Account(info.first, "");
2187 account.setPrivateKeyAlias(alias);
2188 account.setOption(Account.OPTION_DISABLED, true);
2189 account.setDisplayName(info.second);
2190 createAccount(account);
2191 callback.onAccountCreated(account);
2192 if (Config.X509_VERIFICATION) {
2193 try {
2194 getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
2195 } catch (CertificateException e) {
2196 callback.informUser(R.string.certificate_chain_is_not_trusted);
2197 }
2198 }
2199 } else {
2200 callback.informUser(R.string.account_already_exists);
2201 }
2202 } catch (Exception e) {
2203 e.printStackTrace();
2204 callback.informUser(R.string.unable_to_parse_certificate);
2205 }
2206 }).start();
2207
2208 }
2209
2210 public void updateKeyInAccount(final Account account, final String alias) {
2211 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2212 try {
2213 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2214 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2215 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2216 if (info == null) {
2217 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2218 return;
2219 }
2220 if (account.getJid().asBareJid().equals(info.first)) {
2221 account.setPrivateKeyAlias(alias);
2222 account.setDisplayName(info.second);
2223 databaseBackend.updateAccount(account);
2224 if (Config.X509_VERIFICATION) {
2225 try {
2226 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2227 } catch (CertificateException e) {
2228 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2229 }
2230 account.getAxolotlService().regenerateKeys(true);
2231 }
2232 } else {
2233 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2234 }
2235 } catch (Exception e) {
2236 e.printStackTrace();
2237 }
2238 }
2239
2240 public boolean updateAccount(final Account account) {
2241 if (databaseBackend.updateAccount(account)) {
2242 account.setShowErrorNotification(true);
2243 this.statusListener.onStatusChanged(account);
2244 databaseBackend.updateAccount(account);
2245 reconnectAccountInBackground(account);
2246 updateAccountUi();
2247 getNotificationService().updateErrorNotification();
2248 toggleForegroundService();
2249 syncEnabledAccountSetting();
2250 mChannelDiscoveryService.cleanCache();
2251 return true;
2252 } else {
2253 return false;
2254 }
2255 }
2256
2257 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2258 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2259 sendIqPacket(account, iq, (a, packet) -> {
2260 if (packet.getType() == IqPacket.TYPE.RESULT) {
2261 a.setPassword(newPassword);
2262 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2263 databaseBackend.updateAccount(a);
2264 callback.onPasswordChangeSucceeded();
2265 } else {
2266 callback.onPasswordChangeFailed();
2267 }
2268 });
2269 }
2270
2271 public void deleteAccount(final Account account) {
2272 final boolean connected = account.getStatus() == Account.State.ONLINE;
2273 synchronized (this.conversations) {
2274 if (connected) {
2275 account.getAxolotlService().deleteOmemoIdentity();
2276 }
2277 for (final Conversation conversation : conversations) {
2278 if (conversation.getAccount() == account) {
2279 if (conversation.getMode() == Conversation.MODE_MULTI) {
2280 if (connected) {
2281 leaveMuc(conversation);
2282 }
2283 }
2284 conversations.remove(conversation);
2285 mNotificationService.clear(conversation);
2286 }
2287 }
2288 if (account.getXmppConnection() != null) {
2289 new Thread(() -> disconnect(account, !connected)).start();
2290 }
2291 final Runnable runnable = () -> {
2292 if (!databaseBackend.deleteAccount(account)) {
2293 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2294 }
2295 };
2296 mDatabaseWriterExecutor.execute(runnable);
2297 this.accounts.remove(account);
2298 this.mRosterSyncTaskManager.clear(account);
2299 updateAccountUi();
2300 mNotificationService.updateErrorNotification();
2301 syncEnabledAccountSetting();
2302 toggleForegroundService();
2303 }
2304 }
2305
2306 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2307 final boolean remainingListeners;
2308 synchronized (LISTENER_LOCK) {
2309 remainingListeners = checkListeners();
2310 if (!this.mOnConversationUpdates.add(listener)) {
2311 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2312 }
2313 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2314 }
2315 if (remainingListeners) {
2316 switchToForeground();
2317 }
2318 }
2319
2320 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2321 final boolean remainingListeners;
2322 synchronized (LISTENER_LOCK) {
2323 this.mOnConversationUpdates.remove(listener);
2324 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2325 remainingListeners = checkListeners();
2326 }
2327 if (remainingListeners) {
2328 switchToBackground();
2329 }
2330 }
2331
2332 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2333 final boolean remainingListeners;
2334 synchronized (LISTENER_LOCK) {
2335 remainingListeners = checkListeners();
2336 if (!this.mOnShowErrorToasts.add(listener)) {
2337 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2338 }
2339 }
2340 if (remainingListeners) {
2341 switchToForeground();
2342 }
2343 }
2344
2345 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2346 final boolean remainingListeners;
2347 synchronized (LISTENER_LOCK) {
2348 this.mOnShowErrorToasts.remove(onShowErrorToast);
2349 remainingListeners = checkListeners();
2350 }
2351 if (remainingListeners) {
2352 switchToBackground();
2353 }
2354 }
2355
2356 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2357 final boolean remainingListeners;
2358 synchronized (LISTENER_LOCK) {
2359 remainingListeners = checkListeners();
2360 if (!this.mOnAccountUpdates.add(listener)) {
2361 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2362 }
2363 }
2364 if (remainingListeners) {
2365 switchToForeground();
2366 }
2367 }
2368
2369 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2370 final boolean remainingListeners;
2371 synchronized (LISTENER_LOCK) {
2372 this.mOnAccountUpdates.remove(listener);
2373 remainingListeners = checkListeners();
2374 }
2375 if (remainingListeners) {
2376 switchToBackground();
2377 }
2378 }
2379
2380 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2381 final boolean remainingListeners;
2382 synchronized (LISTENER_LOCK) {
2383 remainingListeners = checkListeners();
2384 if (!this.mOnCaptchaRequested.add(listener)) {
2385 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2386 }
2387 }
2388 if (remainingListeners) {
2389 switchToForeground();
2390 }
2391 }
2392
2393 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2394 final boolean remainingListeners;
2395 synchronized (LISTENER_LOCK) {
2396 this.mOnCaptchaRequested.remove(listener);
2397 remainingListeners = checkListeners();
2398 }
2399 if (remainingListeners) {
2400 switchToBackground();
2401 }
2402 }
2403
2404 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2405 final boolean remainingListeners;
2406 synchronized (LISTENER_LOCK) {
2407 remainingListeners = checkListeners();
2408 if (!this.mOnRosterUpdates.add(listener)) {
2409 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2410 }
2411 }
2412 if (remainingListeners) {
2413 switchToForeground();
2414 }
2415 }
2416
2417 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2418 final boolean remainingListeners;
2419 synchronized (LISTENER_LOCK) {
2420 this.mOnRosterUpdates.remove(listener);
2421 remainingListeners = checkListeners();
2422 }
2423 if (remainingListeners) {
2424 switchToBackground();
2425 }
2426 }
2427
2428 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2429 final boolean remainingListeners;
2430 synchronized (LISTENER_LOCK) {
2431 remainingListeners = checkListeners();
2432 if (!this.mOnUpdateBlocklist.add(listener)) {
2433 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2434 }
2435 }
2436 if (remainingListeners) {
2437 switchToForeground();
2438 }
2439 }
2440
2441 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2442 final boolean remainingListeners;
2443 synchronized (LISTENER_LOCK) {
2444 this.mOnUpdateBlocklist.remove(listener);
2445 remainingListeners = checkListeners();
2446 }
2447 if (remainingListeners) {
2448 switchToBackground();
2449 }
2450 }
2451
2452 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2453 final boolean remainingListeners;
2454 synchronized (LISTENER_LOCK) {
2455 remainingListeners = checkListeners();
2456 if (!this.mOnKeyStatusUpdated.add(listener)) {
2457 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2458 }
2459 }
2460 if (remainingListeners) {
2461 switchToForeground();
2462 }
2463 }
2464
2465 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2466 final boolean remainingListeners;
2467 synchronized (LISTENER_LOCK) {
2468 this.mOnKeyStatusUpdated.remove(listener);
2469 remainingListeners = checkListeners();
2470 }
2471 if (remainingListeners) {
2472 switchToBackground();
2473 }
2474 }
2475
2476 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2477 final boolean remainingListeners;
2478 synchronized (LISTENER_LOCK) {
2479 remainingListeners = checkListeners();
2480 if (!this.mOnMucRosterUpdate.add(listener)) {
2481 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2482 }
2483 }
2484 if (remainingListeners) {
2485 switchToForeground();
2486 }
2487 }
2488
2489 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2490 final boolean remainingListeners;
2491 synchronized (LISTENER_LOCK) {
2492 this.mOnMucRosterUpdate.remove(listener);
2493 remainingListeners = checkListeners();
2494 }
2495 if (remainingListeners) {
2496 switchToBackground();
2497 }
2498 }
2499
2500 public boolean checkListeners() {
2501 return (this.mOnAccountUpdates.size() == 0
2502 && this.mOnConversationUpdates.size() == 0
2503 && this.mOnRosterUpdates.size() == 0
2504 && this.mOnCaptchaRequested.size() == 0
2505 && this.mOnMucRosterUpdate.size() == 0
2506 && this.mOnUpdateBlocklist.size() == 0
2507 && this.mOnShowErrorToasts.size() == 0
2508 && this.mOnKeyStatusUpdated.size() == 0);
2509 }
2510
2511 private void switchToForeground() {
2512 final boolean broadcastLastActivity = broadcastLastActivity();
2513 for (Conversation conversation : getConversations()) {
2514 if (conversation.getMode() == Conversation.MODE_MULTI) {
2515 conversation.getMucOptions().resetChatState();
2516 } else {
2517 conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2518 }
2519 }
2520 for (Account account : getAccounts()) {
2521 if (account.getStatus() == Account.State.ONLINE) {
2522 account.deactivateGracePeriod();
2523 final XmppConnection connection = account.getXmppConnection();
2524 if (connection != null) {
2525 if (connection.getFeatures().csi()) {
2526 connection.sendActive();
2527 }
2528 if (broadcastLastActivity) {
2529 sendPresence(account, false); //send new presence but don't include idle because we are not
2530 }
2531 }
2532 }
2533 }
2534 Log.d(Config.LOGTAG, "app switched into foreground");
2535 }
2536
2537 private void switchToBackground() {
2538 final boolean broadcastLastActivity = broadcastLastActivity();
2539 if (broadcastLastActivity) {
2540 mLastActivity = System.currentTimeMillis();
2541 final SharedPreferences.Editor editor = getPreferences().edit();
2542 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2543 editor.apply();
2544 }
2545 for (Account account : getAccounts()) {
2546 if (account.getStatus() == Account.State.ONLINE) {
2547 XmppConnection connection = account.getXmppConnection();
2548 if (connection != null) {
2549 if (broadcastLastActivity) {
2550 sendPresence(account, true);
2551 }
2552 if (connection.getFeatures().csi()) {
2553 connection.sendInactive();
2554 }
2555 }
2556 }
2557 }
2558 this.mNotificationService.setIsInForeground(false);
2559 Log.d(Config.LOGTAG, "app switched into background");
2560 }
2561
2562 private void connectMultiModeConversations(Account account) {
2563 List<Conversation> conversations = getConversations();
2564 for (Conversation conversation : conversations) {
2565 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2566 joinMuc(conversation);
2567 }
2568 }
2569 }
2570
2571 public void mucSelfPingAndRejoin(final Conversation conversation) {
2572 final Account account = conversation.getAccount();
2573 synchronized (account.inProgressConferenceJoins) {
2574 if (account.inProgressConferenceJoins.contains(conversation)) {
2575 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2576 return;
2577 }
2578 }
2579 synchronized (account.inProgressConferencePings) {
2580 if (!account.inProgressConferencePings.add(conversation)) {
2581 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
2582 return;
2583 }
2584 }
2585 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2586 final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2587 ping.setTo(self);
2588 ping.addChild("ping", Namespace.PING);
2589 sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2590 if (response.getType() == IqPacket.TYPE.ERROR) {
2591 Element error = response.findChild("error");
2592 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2593 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
2594 } else {
2595 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
2596 joinMuc(conversation);
2597 }
2598 } else if (response.getType() == IqPacket.TYPE.RESULT) {
2599 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
2600 }
2601 synchronized (account.inProgressConferencePings) {
2602 account.inProgressConferencePings.remove(conversation);
2603 }
2604 });
2605 }
2606
2607 public void joinMuc(Conversation conversation) {
2608 joinMuc(conversation, null, false);
2609 }
2610
2611 public void joinMuc(Conversation conversation, boolean followedInvite) {
2612 joinMuc(conversation, null, followedInvite);
2613 }
2614
2615 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2616 joinMuc(conversation, onConferenceJoined, false);
2617 }
2618
2619 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2620 final Account account = conversation.getAccount();
2621 synchronized (account.pendingConferenceJoins) {
2622 account.pendingConferenceJoins.remove(conversation);
2623 }
2624 synchronized (account.pendingConferenceLeaves) {
2625 account.pendingConferenceLeaves.remove(conversation);
2626 }
2627 if (account.getStatus() == Account.State.ONLINE) {
2628 synchronized (account.inProgressConferenceJoins) {
2629 account.inProgressConferenceJoins.add(conversation);
2630 }
2631 if (Config.MUC_LEAVE_BEFORE_JOIN) {
2632 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2633 }
2634 conversation.resetMucOptions();
2635 if (onConferenceJoined != null) {
2636 conversation.getMucOptions().flagNoAutoPushConfiguration();
2637 }
2638 conversation.setHasMessagesLeftOnServer(false);
2639 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2640
2641 private void join(Conversation conversation) {
2642 Account account = conversation.getAccount();
2643 final MucOptions mucOptions = conversation.getMucOptions();
2644
2645 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2646 synchronized (account.inProgressConferenceJoins) {
2647 account.inProgressConferenceJoins.remove(conversation);
2648 }
2649 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2650 updateConversationUi();
2651 if (onConferenceJoined != null) {
2652 onConferenceJoined.onConferenceJoined(conversation);
2653 }
2654 return;
2655 }
2656
2657 final Jid joinJid = mucOptions.getSelf().getFullJid();
2658 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2659 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2660 packet.setTo(joinJid);
2661 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2662 if (conversation.getMucOptions().getPassword() != null) {
2663 x.addChild("password").setContent(mucOptions.getPassword());
2664 }
2665
2666 if (mucOptions.mamSupport()) {
2667 // Use MAM instead of the limited muc history to get history
2668 x.addChild("history").setAttribute("maxchars", "0");
2669 } else {
2670 // Fallback to muc history
2671 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2672 }
2673 sendPresencePacket(account, packet);
2674 if (onConferenceJoined != null) {
2675 onConferenceJoined.onConferenceJoined(conversation);
2676 }
2677 if (!joinJid.equals(conversation.getJid())) {
2678 conversation.setContactJid(joinJid);
2679 databaseBackend.updateConversation(conversation);
2680 }
2681
2682 if (mucOptions.mamSupport()) {
2683 getMessageArchiveService().catchupMUC(conversation);
2684 }
2685 if (mucOptions.isPrivateAndNonAnonymous()) {
2686 fetchConferenceMembers(conversation);
2687
2688 if (followedInvite) {
2689 final Bookmark bookmark = conversation.getBookmark();
2690 if (bookmark != null) {
2691 if (!bookmark.autojoin()) {
2692 bookmark.setAutojoin(true);
2693 createBookmark(account, bookmark);
2694 }
2695 } else {
2696 saveConversationAsBookmark(conversation, null);
2697 }
2698 }
2699 }
2700 if (mucOptions.push()) {
2701 enableMucPush(conversation);
2702 }
2703 synchronized (account.inProgressConferenceJoins) {
2704 account.inProgressConferenceJoins.remove(conversation);
2705 sendUnsentMessages(conversation);
2706 }
2707 }
2708
2709 @Override
2710 public void onConferenceConfigurationFetched(Conversation conversation) {
2711 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2712 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2713 return;
2714 }
2715 join(conversation);
2716 }
2717
2718 @Override
2719 public void onFetchFailed(final Conversation conversation, Element error) {
2720 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2721 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2722
2723 return;
2724 }
2725 if (error != null && "remote-server-not-found".equals(error.getName())) {
2726 synchronized (account.inProgressConferenceJoins) {
2727 account.inProgressConferenceJoins.remove(conversation);
2728 }
2729 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2730 updateConversationUi();
2731 } else {
2732 join(conversation);
2733 fetchConferenceConfiguration(conversation);
2734 }
2735 }
2736 });
2737 updateConversationUi();
2738 } else {
2739 synchronized (account.pendingConferenceJoins) {
2740 account.pendingConferenceJoins.add(conversation);
2741 }
2742 conversation.resetMucOptions();
2743 conversation.setHasMessagesLeftOnServer(false);
2744 updateConversationUi();
2745 }
2746 }
2747
2748 private void enableDirectMucPush(final Conversation conversation) {
2749 final Account account = conversation.getAccount();
2750 final Jid room = conversation.getJid().asBareJid();
2751 final IqPacket enable = mIqGenerator.enablePush(conversation.getAccount().getJid(), conversation.getUuid(), null);
2752 enable.setTo(room);
2753 sendIqPacket(account, enable, (a, response) -> {
2754 if (response.getType() == IqPacket.TYPE.RESULT) {
2755 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": enabled direct push for muc " + room);
2756 } else if (response.getType() == IqPacket.TYPE.ERROR) {
2757 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to enable direct push for muc " + room + " " + response.getError());
2758 }
2759 });
2760 }
2761
2762 private void enableMucPush(final Conversation conversation) {
2763 enableDirectMucPush(conversation);
2764 mPushManagementService.registerPushTokenOnServer(conversation);
2765 }
2766
2767 private void disableDirectMucPush(final Conversation conversation) {
2768 final Account account = conversation.getAccount();
2769 final Jid room = conversation.getJid().asBareJid();
2770 final IqPacket disable = mIqGenerator.disablePush(conversation.getAccount().getJid(), conversation.getUuid());
2771 disable.setTo(room);
2772 sendIqPacket(account, disable, (a, response) -> {
2773 if (response.getType() == IqPacket.TYPE.RESULT) {
2774 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": disabled direct push for muc " + room);
2775 } else if (response.getType() == IqPacket.TYPE.ERROR) {
2776 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to disable direct push for muc " + room + " " + response.getError());
2777 }
2778 });
2779 }
2780
2781 private void fetchConferenceMembers(final Conversation conversation) {
2782 final Account account = conversation.getAccount();
2783 final AxolotlService axolotlService = account.getAxolotlService();
2784 final String[] affiliations = {"member", "admin", "owner"};
2785 OnIqPacketReceived callback = new OnIqPacketReceived() {
2786
2787 private int i = 0;
2788 private boolean success = true;
2789
2790 @Override
2791 public void onIqPacketReceived(Account account, IqPacket packet) {
2792 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2793 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2794 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2795 for (Element child : query.getChildren()) {
2796 if ("item".equals(child.getName())) {
2797 MucOptions.User user = AbstractParser.parseItem(conversation, child);
2798 if (!user.realJidMatchesAccount()) {
2799 boolean isNew = conversation.getMucOptions().updateUser(user);
2800 Contact contact = user.getContact();
2801 if (omemoEnabled
2802 && isNew
2803 && user.getRealJid() != null
2804 && (contact == null || !contact.mutualPresenceSubscription())
2805 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2806 axolotlService.fetchDeviceIds(user.getRealJid());
2807 }
2808 }
2809 }
2810 }
2811 } else {
2812 success = false;
2813 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2814 }
2815 ++i;
2816 if (i >= affiliations.length) {
2817 List<Jid> members = conversation.getMucOptions().getMembers(true);
2818 if (success) {
2819 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2820 boolean changed = false;
2821 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2822 Jid jid = iterator.next();
2823 if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
2824 iterator.remove();
2825 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2826 changed = true;
2827 }
2828 }
2829 if (changed) {
2830 conversation.setAcceptedCryptoTargets(cryptoTargets);
2831 updateConversation(conversation);
2832 }
2833 }
2834 getAvatarService().clear(conversation);
2835 updateMucRosterUi();
2836 updateConversationUi();
2837 }
2838 }
2839 };
2840 for (String affiliation : affiliations) {
2841 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2842 }
2843 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2844 }
2845
2846 public void providePasswordForMuc(Conversation conversation, String password) {
2847 if (conversation.getMode() == Conversation.MODE_MULTI) {
2848 conversation.getMucOptions().setPassword(password);
2849 if (conversation.getBookmark() != null) {
2850 final Bookmark bookmark = conversation.getBookmark();
2851 if (synchronizeWithBookmarks()) {
2852 bookmark.setAutojoin(true);
2853 }
2854 createBookmark(conversation.getAccount(), bookmark);
2855 }
2856 updateConversation(conversation);
2857 joinMuc(conversation);
2858 }
2859 }
2860
2861 private boolean hasEnabledAccounts() {
2862 if (this.accounts == null) {
2863 return false;
2864 }
2865 for (Account account : this.accounts) {
2866 if (account.isEnabled()) {
2867 return true;
2868 }
2869 }
2870 return false;
2871 }
2872
2873
2874 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2875 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2876 }
2877
2878 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2879 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
2880 }
2881
2882
2883 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2884 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2885 }
2886
2887 public void persistSelfNick(MucOptions.User self) {
2888 final Conversation conversation = self.getConversation();
2889 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
2890 Jid full = self.getFullJid();
2891 if (!full.equals(conversation.getJid())) {
2892 Log.d(Config.LOGTAG, "nick changed. updating");
2893 conversation.setContactJid(full);
2894 databaseBackend.updateConversation(conversation);
2895 }
2896
2897 final Bookmark bookmark = conversation.getBookmark();
2898 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
2899 if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
2900 final Account account = conversation.getAccount();
2901 final String defaultNick = MucOptions.defaultNick(account);
2902 if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
2903 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
2904 return;
2905 }
2906 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
2907 bookmark.setNick(full.getResource());
2908 createBookmark(bookmark.getAccount(), bookmark);
2909 }
2910 }
2911
2912 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2913 final MucOptions options = conversation.getMucOptions();
2914 final Jid joinJid = options.createJoinJid(nick);
2915 if (joinJid == null) {
2916 return false;
2917 }
2918 if (options.online()) {
2919 Account account = conversation.getAccount();
2920 options.setOnRenameListener(new OnRenameListener() {
2921
2922 @Override
2923 public void onSuccess() {
2924 callback.success(conversation);
2925 }
2926
2927 @Override
2928 public void onFailure() {
2929 callback.error(R.string.nick_in_use, conversation);
2930 }
2931 });
2932
2933 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
2934 packet.setTo(joinJid);
2935 sendPresencePacket(account, packet);
2936 } else {
2937 conversation.setContactJid(joinJid);
2938 databaseBackend.updateConversation(conversation);
2939 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2940 Bookmark bookmark = conversation.getBookmark();
2941 if (bookmark != null) {
2942 bookmark.setNick(nick);
2943 createBookmark(bookmark.getAccount(), bookmark);
2944 }
2945 joinMuc(conversation);
2946 }
2947 }
2948 return true;
2949 }
2950
2951 public void leaveMuc(Conversation conversation) {
2952 leaveMuc(conversation, false);
2953 }
2954
2955 private void leaveMuc(Conversation conversation, boolean now) {
2956 final Account account = conversation.getAccount();
2957 synchronized (account.pendingConferenceJoins) {
2958 account.pendingConferenceJoins.remove(conversation);
2959 }
2960 synchronized (account.pendingConferenceLeaves) {
2961 account.pendingConferenceLeaves.remove(conversation);
2962 }
2963 if (account.getStatus() == Account.State.ONLINE || now) {
2964 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2965 conversation.getMucOptions().setOffline();
2966 Bookmark bookmark = conversation.getBookmark();
2967 if (bookmark != null) {
2968 bookmark.setConversation(null);
2969 }
2970 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2971 } else {
2972 synchronized (account.pendingConferenceLeaves) {
2973 account.pendingConferenceLeaves.add(conversation);
2974 }
2975 }
2976 }
2977
2978 public String findConferenceServer(final Account account) {
2979 String server;
2980 if (account.getXmppConnection() != null) {
2981 server = account.getXmppConnection().getMucServer();
2982 if (server != null) {
2983 return server;
2984 }
2985 }
2986 for (Account other : getAccounts()) {
2987 if (other != account && other.getXmppConnection() != null) {
2988 server = other.getXmppConnection().getMucServer();
2989 if (server != null) {
2990 return server;
2991 }
2992 }
2993 }
2994 return null;
2995 }
2996
2997
2998 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
2999 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3000 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3001 if (!TextUtils.isEmpty(name)) {
3002 configuration.putString("muc#roomconfig_roomname", name);
3003 }
3004 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3005 @Override
3006 public void onPushSucceeded() {
3007 saveConversationAsBookmark(conversation, name);
3008 callback.success(conversation);
3009 }
3010
3011 @Override
3012 public void onPushFailed() {
3013 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3014 callback.error(R.string.unable_to_set_channel_configuration, conversation);
3015 } else {
3016 callback.error(R.string.joined_an_existing_channel, conversation);
3017 }
3018 }
3019 });
3020 });
3021 }
3022
3023 public boolean createAdhocConference(final Account account,
3024 final String name,
3025 final Iterable<Jid> jids,
3026 final UiCallback<Conversation> callback) {
3027 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3028 if (account.getStatus() == Account.State.ONLINE) {
3029 try {
3030 String server = findConferenceServer(account);
3031 if (server == null) {
3032 if (callback != null) {
3033 callback.error(R.string.no_conference_server_found, null);
3034 }
3035 return false;
3036 }
3037 final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
3038 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3039 joinMuc(conversation, new OnConferenceJoined() {
3040 @Override
3041 public void onConferenceJoined(final Conversation conversation) {
3042 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3043 if (!TextUtils.isEmpty(name)) {
3044 configuration.putString("muc#roomconfig_roomname", name);
3045 }
3046 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3047 @Override
3048 public void onPushSucceeded() {
3049 for (Jid invite : jids) {
3050 invite(conversation, invite);
3051 }
3052 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3053 Jid other = account.getJid().withResource(resource);
3054 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3055 directInvite(conversation, other);
3056 }
3057 saveConversationAsBookmark(conversation, name);
3058 if (callback != null) {
3059 callback.success(conversation);
3060 }
3061 }
3062
3063 @Override
3064 public void onPushFailed() {
3065 archiveConversation(conversation);
3066 if (callback != null) {
3067 callback.error(R.string.conference_creation_failed, conversation);
3068 }
3069 }
3070 });
3071 }
3072 });
3073 return true;
3074 } catch (IllegalArgumentException e) {
3075 if (callback != null) {
3076 callback.error(R.string.conference_creation_failed, null);
3077 }
3078 return false;
3079 }
3080 } else {
3081 if (callback != null) {
3082 callback.error(R.string.not_connected_try_again, null);
3083 }
3084 return false;
3085 }
3086 }
3087
3088 public void fetchConferenceConfiguration(final Conversation conversation) {
3089 fetchConferenceConfiguration(conversation, null);
3090 }
3091
3092 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3093 IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3094 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3095 @Override
3096 public void onIqPacketReceived(Account account, IqPacket packet) {
3097 if (packet.getType() == IqPacket.TYPE.RESULT) {
3098 final MucOptions mucOptions = conversation.getMucOptions();
3099 final Bookmark bookmark = conversation.getBookmark();
3100 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3101
3102 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3103 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3104 updateConversation(conversation);
3105 }
3106
3107 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3108 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3109 createBookmark(account, bookmark);
3110 }
3111 }
3112
3113
3114 if (callback != null) {
3115 callback.onConferenceConfigurationFetched(conversation);
3116 }
3117
3118
3119 updateConversationUi();
3120 } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3121 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3122 } else {
3123 if (callback != null) {
3124 callback.onFetchFailed(conversation, packet.getError());
3125 }
3126 }
3127 }
3128 });
3129 }
3130
3131 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3132 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3133 }
3134
3135 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3136 Log.d(Config.LOGTAG, "pushing node configuration");
3137 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3138 @Override
3139 public void onIqPacketReceived(Account account, IqPacket packet) {
3140 if (packet.getType() == IqPacket.TYPE.RESULT) {
3141 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3142 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3143 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3144 if (x != null) {
3145 Data data = Data.parse(x);
3146 data.submit(options);
3147 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3148 @Override
3149 public void onIqPacketReceived(Account account, IqPacket packet) {
3150 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3151 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3152 callback.onPushSucceeded();
3153 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3154 callback.onPushFailed();
3155 }
3156 }
3157 });
3158 } else if (callback != null) {
3159 callback.onPushFailed();
3160 }
3161 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3162 callback.onPushFailed();
3163 }
3164 }
3165 });
3166 }
3167
3168 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3169 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3170 conversation.setAttribute("accept_non_anonymous", true);
3171 updateConversation(conversation);
3172 }
3173 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3174 request.setTo(conversation.getJid().asBareJid());
3175 request.query("http://jabber.org/protocol/muc#owner");
3176 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3177 @Override
3178 public void onIqPacketReceived(Account account, IqPacket packet) {
3179 if (packet.getType() == IqPacket.TYPE.RESULT) {
3180 Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3181 data.submit(options);
3182 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3183 set.setTo(conversation.getJid().asBareJid());
3184 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3185 sendIqPacket(account, set, new OnIqPacketReceived() {
3186 @Override
3187 public void onIqPacketReceived(Account account, IqPacket packet) {
3188 if (callback != null) {
3189 if (packet.getType() == IqPacket.TYPE.RESULT) {
3190 callback.onPushSucceeded();
3191 } else {
3192 callback.onPushFailed();
3193 }
3194 }
3195 }
3196 });
3197 } else {
3198 if (callback != null) {
3199 callback.onPushFailed();
3200 }
3201 }
3202 }
3203 });
3204 }
3205
3206 public void pushSubjectToConference(final Conversation conference, final String subject) {
3207 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3208 this.sendMessagePacket(conference.getAccount(), packet);
3209 }
3210
3211 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3212 final Jid jid = user.asBareJid();
3213 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3214 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
3215 @Override
3216 public void onIqPacketReceived(Account account, IqPacket packet) {
3217 if (packet.getType() == IqPacket.TYPE.RESULT) {
3218 conference.getMucOptions().changeAffiliation(jid, affiliation);
3219 getAvatarService().clear(conference);
3220 callback.onAffiliationChangedSuccessful(jid);
3221 } else {
3222 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3223 }
3224 }
3225 });
3226 }
3227
3228 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
3229 List<Jid> jids = new ArrayList<>();
3230 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
3231 if (user.getAffiliation() == before && user.getRealJid() != null) {
3232 jids.add(user.getRealJid());
3233 }
3234 }
3235 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
3236 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
3237 }
3238
3239 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3240 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3241 Log.d(Config.LOGTAG, request.toString());
3242 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3243 if (packet.getType() != IqPacket.TYPE.RESULT) {
3244 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3245 }
3246 });
3247 }
3248
3249 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3250 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3251 request.setTo(conversation.getJid().asBareJid());
3252 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3253 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3254 @Override
3255 public void onIqPacketReceived(Account account, IqPacket packet) {
3256 if (packet.getType() == IqPacket.TYPE.RESULT) {
3257 if (callback != null) {
3258 callback.onRoomDestroySucceeded();
3259 }
3260 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3261 if (callback != null) {
3262 callback.onRoomDestroyFailed();
3263 }
3264 }
3265 }
3266 });
3267 }
3268
3269 private void disconnect(Account account, boolean force) {
3270 if ((account.getStatus() == Account.State.ONLINE)
3271 || (account.getStatus() == Account.State.DISABLED)) {
3272 final XmppConnection connection = account.getXmppConnection();
3273 if (!force) {
3274 List<Conversation> conversations = getConversations();
3275 for (Conversation conversation : conversations) {
3276 if (conversation.getAccount() == account) {
3277 if (conversation.getMode() == Conversation.MODE_MULTI) {
3278 leaveMuc(conversation, true);
3279 }
3280 }
3281 }
3282 sendOfflinePresence(account);
3283 }
3284 connection.disconnect(force);
3285 }
3286 }
3287
3288 @Override
3289 public IBinder onBind(Intent intent) {
3290 return mBinder;
3291 }
3292
3293 public void updateMessage(Message message) {
3294 updateMessage(message, true);
3295 }
3296
3297 public void updateMessage(Message message, boolean includeBody) {
3298 databaseBackend.updateMessage(message, includeBody);
3299 updateConversationUi();
3300 }
3301
3302 public void updateMessage(Message message, String uuid) {
3303 if (!databaseBackend.updateMessage(message, uuid)) {
3304 Log.e(Config.LOGTAG, "error updated message in DB after edit");
3305 }
3306 updateConversationUi();
3307 }
3308
3309 protected void syncDirtyContacts(Account account) {
3310 for (Contact contact : account.getRoster().getContacts()) {
3311 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3312 pushContactToServer(contact);
3313 }
3314 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3315 deleteContactOnServer(contact);
3316 }
3317 }
3318 }
3319
3320 public void createContact(Contact contact, boolean autoGrant) {
3321 if (autoGrant) {
3322 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3323 contact.setOption(Contact.Options.ASKING);
3324 }
3325 pushContactToServer(contact);
3326 }
3327
3328 public void pushContactToServer(final Contact contact) {
3329 contact.resetOption(Contact.Options.DIRTY_DELETE);
3330 contact.setOption(Contact.Options.DIRTY_PUSH);
3331 final Account account = contact.getAccount();
3332 if (account.getStatus() == Account.State.ONLINE) {
3333 final boolean ask = contact.getOption(Contact.Options.ASKING);
3334 final boolean sendUpdates = contact
3335 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3336 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3337 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3338 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3339 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3340 if (sendUpdates) {
3341 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3342 }
3343 if (ask) {
3344 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
3345 }
3346 } else {
3347 syncRoster(contact.getAccount());
3348 }
3349 }
3350
3351 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3352 new Thread(() -> {
3353 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3354 final int size = Config.AVATAR_SIZE;
3355 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3356 if (avatar != null) {
3357 if (!getFileBackend().save(avatar)) {
3358 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3359 return;
3360 }
3361 avatar.owner = conversation.getJid().asBareJid();
3362 publishMucAvatar(conversation, avatar, callback);
3363 } else {
3364 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3365 }
3366 }).start();
3367 }
3368
3369 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3370 new Thread(() -> {
3371 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3372 final int size = Config.AVATAR_SIZE;
3373 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3374 if (avatar != null) {
3375 if (!getFileBackend().save(avatar)) {
3376 Log.d(Config.LOGTAG, "unable to save vcard");
3377 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3378 return;
3379 }
3380 publishAvatar(account, avatar, callback);
3381 } else {
3382 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3383 }
3384 }).start();
3385
3386 }
3387
3388 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3389 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3390 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3391 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3392 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3393 Element vcard = response.findChild("vCard", "vcard-temp");
3394 if (vcard == null) {
3395 vcard = new Element("vCard", "vcard-temp");
3396 }
3397 Element photo = vcard.findChild("PHOTO");
3398 if (photo == null) {
3399 photo = vcard.addChild("PHOTO");
3400 }
3401 photo.clearChildren();
3402 photo.addChild("TYPE").setContent(avatar.type);
3403 photo.addChild("BINVAL").setContent(avatar.image);
3404 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3405 publication.setTo(conversation.getJid().asBareJid());
3406 publication.addChild(vcard);
3407 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3408 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3409 callback.onAvatarPublicationSucceeded();
3410 } else {
3411 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
3412 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3413 }
3414 });
3415 } else {
3416 Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3417 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3418 }
3419 });
3420 }
3421
3422 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3423 final Bundle options;
3424 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3425 options = PublishOptions.openAccess();
3426 } else {
3427 options = null;
3428 }
3429 publishAvatar(account, avatar, options, true, callback);
3430 }
3431
3432 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3433 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3434 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3435 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3436
3437 @Override
3438 public void onIqPacketReceived(Account account, IqPacket result) {
3439 if (result.getType() == IqPacket.TYPE.RESULT) {
3440 publishAvatarMetadata(account, avatar, options, true, callback);
3441 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3442 pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3443 @Override
3444 public void onPushSucceeded() {
3445 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3446 publishAvatar(account, avatar, options, false, callback);
3447 }
3448
3449 @Override
3450 public void onPushFailed() {
3451 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3452 publishAvatar(account, avatar, null, false, callback);
3453 }
3454 });
3455 } else {
3456 Element error = result.findChild("error");
3457 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3458 if (callback != null) {
3459 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3460 }
3461 }
3462 }
3463 });
3464 }
3465
3466 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3467 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3468 sendIqPacket(account, packet, new OnIqPacketReceived() {
3469 @Override
3470 public void onIqPacketReceived(Account account, IqPacket result) {
3471 if (result.getType() == IqPacket.TYPE.RESULT) {
3472 if (account.setAvatar(avatar.getFilename())) {
3473 getAvatarService().clear(account);
3474 databaseBackend.updateAccount(account);
3475 notifyAccountAvatarHasChanged(account);
3476 }
3477 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3478 if (callback != null) {
3479 callback.onAvatarPublicationSucceeded();
3480 }
3481 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3482 pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3483 @Override
3484 public void onPushSucceeded() {
3485 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3486 publishAvatarMetadata(account, avatar, options, false, callback);
3487 }
3488
3489 @Override
3490 public void onPushFailed() {
3491 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3492 publishAvatarMetadata(account, avatar, null, false, callback);
3493 }
3494 });
3495 } else {
3496 if (callback != null) {
3497 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3498 }
3499 }
3500 }
3501 });
3502 }
3503
3504 public void republishAvatarIfNeeded(Account account) {
3505 if (account.getAxolotlService().isPepBroken()) {
3506 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3507 return;
3508 }
3509 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3510 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3511
3512 private Avatar parseAvatar(IqPacket packet) {
3513 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3514 if (pubsub != null) {
3515 Element items = pubsub.findChild("items");
3516 if (items != null) {
3517 return Avatar.parseMetadata(items);
3518 }
3519 }
3520 return null;
3521 }
3522
3523 private boolean errorIsItemNotFound(IqPacket packet) {
3524 Element error = packet.findChild("error");
3525 return packet.getType() == IqPacket.TYPE.ERROR
3526 && error != null
3527 && error.hasChild("item-not-found");
3528 }
3529
3530 @Override
3531 public void onIqPacketReceived(Account account, IqPacket packet) {
3532 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3533 Avatar serverAvatar = parseAvatar(packet);
3534 if (serverAvatar == null && account.getAvatar() != null) {
3535 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3536 if (avatar != null) {
3537 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3538 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3539 } else {
3540 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3541 }
3542 }
3543 }
3544 }
3545 });
3546 }
3547
3548 public void fetchAvatar(Account account, Avatar avatar) {
3549 fetchAvatar(account, avatar, null);
3550 }
3551
3552 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3553 final String KEY = generateFetchKey(account, avatar);
3554 synchronized (this.mInProgressAvatarFetches) {
3555 if (mInProgressAvatarFetches.add(KEY)) {
3556 switch (avatar.origin) {
3557 case PEP:
3558 this.mInProgressAvatarFetches.add(KEY);
3559 fetchAvatarPep(account, avatar, callback);
3560 break;
3561 case VCARD:
3562 this.mInProgressAvatarFetches.add(KEY);
3563 fetchAvatarVcard(account, avatar, callback);
3564 break;
3565 }
3566 } else if (avatar.origin == Avatar.Origin.PEP) {
3567 mOmittedPepAvatarFetches.add(KEY);
3568 } else {
3569 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
3570 }
3571 }
3572 }
3573
3574 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3575 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3576 sendIqPacket(account, packet, (a, result) -> {
3577 synchronized (mInProgressAvatarFetches) {
3578 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3579 }
3580 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3581 if (result.getType() == IqPacket.TYPE.RESULT) {
3582 avatar.image = mIqParser.avatarData(result);
3583 if (avatar.image != null) {
3584 if (getFileBackend().save(avatar)) {
3585 if (a.getJid().asBareJid().equals(avatar.owner)) {
3586 if (a.setAvatar(avatar.getFilename())) {
3587 databaseBackend.updateAccount(a);
3588 }
3589 getAvatarService().clear(a);
3590 updateConversationUi();
3591 updateAccountUi();
3592 } else {
3593 Contact contact = a.getRoster().getContact(avatar.owner);
3594 if (contact.setAvatar(avatar)) {
3595 syncRoster(account);
3596 getAvatarService().clear(contact);
3597 updateConversationUi();
3598 updateRosterUi();
3599 }
3600 }
3601 if (callback != null) {
3602 callback.success(avatar);
3603 }
3604 Log.d(Config.LOGTAG, a.getJid().asBareJid()
3605 + ": successfully fetched pep avatar for " + avatar.owner);
3606 return;
3607 }
3608 } else {
3609
3610 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3611 }
3612 } else {
3613 Element error = result.findChild("error");
3614 if (error == null) {
3615 Log.d(Config.LOGTAG, ERROR + "(server error)");
3616 } else {
3617 Log.d(Config.LOGTAG, ERROR + error.toString());
3618 }
3619 }
3620 if (callback != null) {
3621 callback.error(0, null);
3622 }
3623
3624 });
3625 }
3626
3627 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3628 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3629 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3630 @Override
3631 public void onIqPacketReceived(Account account, IqPacket packet) {
3632 final boolean previouslyOmittedPepFetch;
3633 synchronized (mInProgressAvatarFetches) {
3634 final String KEY = generateFetchKey(account, avatar);
3635 mInProgressAvatarFetches.remove(KEY);
3636 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3637 }
3638 if (packet.getType() == IqPacket.TYPE.RESULT) {
3639 Element vCard = packet.findChild("vCard", "vcard-temp");
3640 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3641 String image = photo != null ? photo.findChildContent("BINVAL") : null;
3642 if (image != null) {
3643 avatar.image = image;
3644 if (getFileBackend().save(avatar)) {
3645 Log.d(Config.LOGTAG, account.getJid().asBareJid()
3646 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
3647 if (avatar.owner.isBareJid()) {
3648 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3649 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3650 account.setAvatar(avatar.getFilename());
3651 databaseBackend.updateAccount(account);
3652 getAvatarService().clear(account);
3653 updateAccountUi();
3654 } else {
3655 Contact contact = account.getRoster().getContact(avatar.owner);
3656 if (contact.setAvatar(avatar, previouslyOmittedPepFetch)) {
3657 syncRoster(account);
3658 getAvatarService().clear(contact);
3659 updateRosterUi();
3660 }
3661 }
3662 updateConversationUi();
3663 } else {
3664 Conversation conversation = find(account, avatar.owner.asBareJid());
3665 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3666 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3667 if (user != null) {
3668 if (user.setAvatar(avatar)) {
3669 getAvatarService().clear(user);
3670 updateConversationUi();
3671 updateMucRosterUi();
3672 }
3673 if (user.getRealJid() != null) {
3674 Contact contact = account.getRoster().getContact(user.getRealJid());
3675 if (contact.setAvatar(avatar)) {
3676 syncRoster(account);
3677 getAvatarService().clear(contact);
3678 updateRosterUi();
3679 }
3680 }
3681 }
3682 }
3683 }
3684 }
3685 }
3686 }
3687 }
3688 });
3689 }
3690
3691 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3692 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3693 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3694
3695 @Override
3696 public void onIqPacketReceived(Account account, IqPacket packet) {
3697 if (packet.getType() == IqPacket.TYPE.RESULT) {
3698 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3699 if (pubsub != null) {
3700 Element items = pubsub.findChild("items");
3701 if (items != null) {
3702 Avatar avatar = Avatar.parseMetadata(items);
3703 if (avatar != null) {
3704 avatar.owner = account.getJid().asBareJid();
3705 if (fileBackend.isAvatarCached(avatar)) {
3706 if (account.setAvatar(avatar.getFilename())) {
3707 databaseBackend.updateAccount(account);
3708 }
3709 getAvatarService().clear(account);
3710 callback.success(avatar);
3711 } else {
3712 fetchAvatarPep(account, avatar, callback);
3713 }
3714 return;
3715 }
3716 }
3717 }
3718 }
3719 callback.error(0, null);
3720 }
3721 });
3722 }
3723
3724 public void notifyAccountAvatarHasChanged(final Account account) {
3725 final XmppConnection connection = account.getXmppConnection();
3726 if (connection != null && connection.getFeatures().bookmarksConversion()) {
3727 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
3728 for (Conversation conversation : conversations) {
3729 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3730 final MucOptions mucOptions = conversation.getMucOptions();
3731 if (mucOptions.online()) {
3732 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3733 packet.setTo(mucOptions.getSelf().getFullJid());
3734 connection.sendPresencePacket(packet);
3735 }
3736 }
3737 }
3738 }
3739 }
3740
3741 public void deleteContactOnServer(Contact contact) {
3742 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3743 contact.resetOption(Contact.Options.DIRTY_PUSH);
3744 contact.setOption(Contact.Options.DIRTY_DELETE);
3745 Account account = contact.getAccount();
3746 if (account.getStatus() == Account.State.ONLINE) {
3747 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3748 Element item = iq.query(Namespace.ROSTER).addChild("item");
3749 item.setAttribute("jid", contact.getJid().toString());
3750 item.setAttribute("subscription", "remove");
3751 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3752 }
3753 }
3754
3755 public void updateConversation(final Conversation conversation) {
3756 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3757 }
3758
3759 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3760 synchronized (account) {
3761 XmppConnection connection = account.getXmppConnection();
3762 if (connection == null) {
3763 connection = createConnection(account);
3764 account.setXmppConnection(connection);
3765 }
3766 boolean hasInternet = hasInternetConnection();
3767 if (account.isEnabled() && hasInternet) {
3768 if (!force) {
3769 disconnect(account, false);
3770 }
3771 Thread thread = new Thread(connection);
3772 connection.setInteractive(interactive);
3773 connection.prepareNewConnection();
3774 connection.interrupt();
3775 thread.start();
3776 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3777 } else {
3778 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3779 account.getRoster().clearPresences();
3780 connection.resetEverything();
3781 final AxolotlService axolotlService = account.getAxolotlService();
3782 if (axolotlService != null) {
3783 axolotlService.resetBrokenness();
3784 }
3785 if (!hasInternet) {
3786 account.setStatus(Account.State.NO_INTERNET);
3787 }
3788 }
3789 }
3790 }
3791
3792 public void reconnectAccountInBackground(final Account account) {
3793 new Thread(() -> reconnectAccount(account, false, true)).start();
3794 }
3795
3796 public void invite(Conversation conversation, Jid contact) {
3797 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3798 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3799 sendMessagePacket(conversation.getAccount(), packet);
3800 }
3801
3802 public void directInvite(Conversation conversation, Jid jid) {
3803 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3804 sendMessagePacket(conversation.getAccount(), packet);
3805 }
3806
3807 public void resetSendingToWaiting(Account account) {
3808 for (Conversation conversation : getConversations()) {
3809 if (conversation.getAccount() == account) {
3810 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3811 }
3812 }
3813 }
3814
3815 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3816 return markMessage(account, recipient, uuid, status, null);
3817 }
3818
3819 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3820 if (uuid == null) {
3821 return null;
3822 }
3823 for (Conversation conversation : getConversations()) {
3824 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3825 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3826 if (message != null) {
3827 markMessage(message, status, errorMessage);
3828 }
3829 return message;
3830 }
3831 }
3832 return null;
3833 }
3834
3835 public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3836 if (uuid == null) {
3837 return false;
3838 } else {
3839 Message message = conversation.findSentMessageWithUuid(uuid);
3840 if (message != null) {
3841 if (message.getServerMsgId() == null) {
3842 message.setServerMsgId(serverMessageId);
3843 }
3844 markMessage(message, status);
3845 return true;
3846 } else {
3847 return false;
3848 }
3849 }
3850 }
3851
3852 public void markMessage(Message message, int status) {
3853 markMessage(message, status, null);
3854 }
3855
3856
3857 public void markMessage(Message message, int status, String errorMessage) {
3858 final int oldStatus = message.getStatus();
3859 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
3860 return;
3861 }
3862 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
3863 return;
3864 }
3865 message.setErrorMessage(errorMessage);
3866 message.setStatus(status);
3867 databaseBackend.updateMessage(message, false);
3868 updateConversationUi();
3869 }
3870
3871 private SharedPreferences getPreferences() {
3872 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3873 }
3874
3875 public long getAutomaticMessageDeletionDate() {
3876 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3877 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3878 }
3879
3880 public long getLongPreference(String name, @IntegerRes int res) {
3881 long defaultValue = getResources().getInteger(res);
3882 try {
3883 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3884 } catch (NumberFormatException e) {
3885 return defaultValue;
3886 }
3887 }
3888
3889 public boolean getBooleanPreference(String name, @BoolRes int res) {
3890 return getPreferences().getBoolean(name, getResources().getBoolean(res));
3891 }
3892
3893 public boolean confirmMessages() {
3894 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3895 }
3896
3897 public boolean allowMessageCorrection() {
3898 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3899 }
3900
3901 public boolean sendChatStates() {
3902 return getBooleanPreference("chat_states", R.bool.chat_states);
3903 }
3904
3905 private boolean synchronizeWithBookmarks() {
3906 return getBooleanPreference("autojoin", R.bool.autojoin);
3907 }
3908
3909 public boolean useTorToConnect() {
3910 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
3911 }
3912
3913 public boolean showExtendedConnectionOptions() {
3914 return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3915 }
3916
3917 public boolean broadcastLastActivity() {
3918 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3919 }
3920
3921 public int unreadCount() {
3922 int count = 0;
3923 for (Conversation conversation : getConversations()) {
3924 count += conversation.unreadCount();
3925 }
3926 return count;
3927 }
3928
3929
3930 private <T> List<T> threadSafeList(Set<T> set) {
3931 synchronized (LISTENER_LOCK) {
3932 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3933 }
3934 }
3935
3936 public void showErrorToastInUi(int resId) {
3937 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3938 listener.onShowErrorToast(resId);
3939 }
3940 }
3941
3942 public void updateConversationUi() {
3943 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3944 listener.onConversationUpdate();
3945 }
3946 }
3947
3948 public void updateAccountUi() {
3949 for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3950 listener.onAccountUpdate();
3951 }
3952 }
3953
3954 public void updateRosterUi() {
3955 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3956 listener.onRosterUpdate();
3957 }
3958 }
3959
3960 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3961 if (mOnCaptchaRequested.size() > 0) {
3962 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3963 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3964 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3965 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3966 listener.onCaptchaRequested(account, id, data, scaled);
3967 }
3968 return true;
3969 }
3970 return false;
3971 }
3972
3973 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3974 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3975 listener.OnUpdateBlocklist(status);
3976 }
3977 }
3978
3979 public void updateMucRosterUi() {
3980 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3981 listener.onMucRosterUpdate();
3982 }
3983 }
3984
3985 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3986 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3987 listener.onKeyStatusUpdated(report);
3988 }
3989 }
3990
3991 public Account findAccountByJid(final Jid accountJid) {
3992 for (Account account : this.accounts) {
3993 if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3994 return account;
3995 }
3996 }
3997 return null;
3998 }
3999
4000 public Account findAccountByUuid(final String uuid) {
4001 for (Account account : this.accounts) {
4002 if (account.getUuid().equals(uuid)) {
4003 return account;
4004 }
4005 }
4006 return null;
4007 }
4008
4009 public Conversation findConversationByUuid(String uuid) {
4010 for (Conversation conversation : getConversations()) {
4011 if (conversation.getUuid().equals(uuid)) {
4012 return conversation;
4013 }
4014 }
4015 return null;
4016 }
4017
4018 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4019 List<Conversation> findings = new ArrayList<>();
4020 for (Conversation c : getConversations()) {
4021 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4022 findings.add(c);
4023 }
4024 }
4025 return findings.size() == 1 ? findings.get(0) : null;
4026 }
4027
4028 public boolean markRead(final Conversation conversation, boolean dismiss) {
4029 return markRead(conversation, null, dismiss).size() > 0;
4030 }
4031
4032 public void markRead(final Conversation conversation) {
4033 markRead(conversation, null, true);
4034 }
4035
4036 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4037 if (dismiss) {
4038 mNotificationService.clear(conversation);
4039 }
4040 final List<Message> readMessages = conversation.markRead(upToUuid);
4041 if (readMessages.size() > 0) {
4042 Runnable runnable = () -> {
4043 for (Message message : readMessages) {
4044 databaseBackend.updateMessage(message, false);
4045 }
4046 };
4047 mDatabaseWriterExecutor.execute(runnable);
4048 updateUnreadCountBadge();
4049 return readMessages;
4050 } else {
4051 return readMessages;
4052 }
4053 }
4054
4055 public synchronized void updateUnreadCountBadge() {
4056 int count = unreadCount();
4057 if (unreadCount != count) {
4058 Log.d(Config.LOGTAG, "update unread count to " + count);
4059 if (count > 0) {
4060 ShortcutBadger.applyCount(getApplicationContext(), count);
4061 } else {
4062 ShortcutBadger.removeCount(getApplicationContext());
4063 }
4064 unreadCount = count;
4065 }
4066 }
4067
4068 public void sendReadMarker(final Conversation conversation, String upToUuid) {
4069 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4070 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4071 if (readMessages.size() > 0) {
4072 updateConversationUi();
4073 }
4074 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4075 if (confirmMessages()
4076 && markable != null
4077 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4078 && markable.getRemoteMsgId() != null) {
4079 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4080 Account account = conversation.getAccount();
4081 final Jid to = markable.getCounterpart();
4082 final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
4083 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
4084 this.sendMessagePacket(conversation.getAccount(), packet);
4085 }
4086 }
4087
4088 public SecureRandom getRNG() {
4089 return this.mRandom;
4090 }
4091
4092 public MemorizingTrustManager getMemorizingTrustManager() {
4093 return this.mMemorizingTrustManager;
4094 }
4095
4096 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4097 this.mMemorizingTrustManager = trustManager;
4098 }
4099
4100 public void updateMemorizingTrustmanager() {
4101 final MemorizingTrustManager tm;
4102 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4103 if (dontTrustSystemCAs) {
4104 tm = new MemorizingTrustManager(getApplicationContext(), null);
4105 } else {
4106 tm = new MemorizingTrustManager(getApplicationContext());
4107 }
4108 setMemorizingTrustManager(tm);
4109 }
4110
4111 public LruCache<String, Bitmap> getBitmapCache() {
4112 return this.mBitmapCache;
4113 }
4114
4115 public Collection<String> getKnownHosts() {
4116 final Set<String> hosts = new HashSet<>();
4117 for (final Account account : getAccounts()) {
4118 hosts.add(account.getServer());
4119 for (final Contact contact : account.getRoster().getContacts()) {
4120 if (contact.showInRoster()) {
4121 final String server = contact.getServer();
4122 if (server != null) {
4123 hosts.add(server);
4124 }
4125 }
4126 }
4127 }
4128 if (Config.QUICKSY_DOMAIN != null) {
4129 hosts.remove(Config.QUICKSY_DOMAIN); //we only want to show this when we type a e164 number
4130 }
4131 if (Config.DOMAIN_LOCK != null) {
4132 hosts.add(Config.DOMAIN_LOCK);
4133 }
4134 if (Config.MAGIC_CREATE_DOMAIN != null) {
4135 hosts.add(Config.MAGIC_CREATE_DOMAIN);
4136 }
4137 return hosts;
4138 }
4139
4140 public Collection<String> getKnownConferenceHosts() {
4141 final Set<String> mucServers = new HashSet<>();
4142 for (final Account account : accounts) {
4143 if (account.getXmppConnection() != null) {
4144 mucServers.addAll(account.getXmppConnection().getMucServers());
4145 for (Bookmark bookmark : account.getBookmarks()) {
4146 final Jid jid = bookmark.getJid();
4147 final String s = jid == null ? null : jid.getDomain();
4148 if (s != null) {
4149 mucServers.add(s);
4150 }
4151 }
4152 }
4153 }
4154 return mucServers;
4155 }
4156
4157 public void sendMessagePacket(Account account, MessagePacket packet) {
4158 XmppConnection connection = account.getXmppConnection();
4159 if (connection != null) {
4160 connection.sendMessagePacket(packet);
4161 }
4162 }
4163
4164 public void sendPresencePacket(Account account, PresencePacket packet) {
4165 XmppConnection connection = account.getXmppConnection();
4166 if (connection != null) {
4167 connection.sendPresencePacket(packet);
4168 }
4169 }
4170
4171 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4172 final XmppConnection connection = account.getXmppConnection();
4173 if (connection != null) {
4174 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4175 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4176 }
4177 }
4178
4179 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4180 final XmppConnection connection = account.getXmppConnection();
4181 if (connection != null) {
4182 connection.sendIqPacket(packet, callback);
4183 } else if (callback != null) {
4184 callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4185 }
4186 }
4187
4188 public void sendPresence(final Account account) {
4189 sendPresence(account, checkListeners() && broadcastLastActivity());
4190 }
4191
4192 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4193 Presence.Status status;
4194 if (manuallyChangePresence()) {
4195 status = account.getPresenceStatus();
4196 } else {
4197 status = getTargetPresence();
4198 }
4199 final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4200 if (mLastActivity > 0 && includeIdleTimestamp) {
4201 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4202 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4203 }
4204 sendPresencePacket(account, packet);
4205 }
4206
4207 private void deactivateGracePeriod() {
4208 for (Account account : getAccounts()) {
4209 account.deactivateGracePeriod();
4210 }
4211 }
4212
4213 public void refreshAllPresences() {
4214 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4215 for (Account account : getAccounts()) {
4216 if (account.isEnabled()) {
4217 sendPresence(account, includeIdleTimestamp);
4218 }
4219 }
4220 }
4221
4222 private void refreshAllFcmTokens() {
4223 for (Account account : getAccounts()) {
4224 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4225 mPushManagementService.registerPushTokenOnServer(account);
4226 //TODO renew mucs
4227 }
4228 }
4229 }
4230
4231 private void sendOfflinePresence(final Account account) {
4232 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4233 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4234 }
4235
4236 public MessageGenerator getMessageGenerator() {
4237 return this.mMessageGenerator;
4238 }
4239
4240 public PresenceGenerator getPresenceGenerator() {
4241 return this.mPresenceGenerator;
4242 }
4243
4244 public IqGenerator getIqGenerator() {
4245 return this.mIqGenerator;
4246 }
4247
4248 public IqParser getIqParser() {
4249 return this.mIqParser;
4250 }
4251
4252 public JingleConnectionManager getJingleConnectionManager() {
4253 return this.mJingleConnectionManager;
4254 }
4255
4256 public MessageArchiveService getMessageArchiveService() {
4257 return this.mMessageArchiveService;
4258 }
4259
4260 public QuickConversationsService getQuickConversationsService() {
4261 return this.mQuickConversationsService;
4262 }
4263
4264 public List<Contact> findContacts(Jid jid, String accountJid) {
4265 ArrayList<Contact> contacts = new ArrayList<>();
4266 for (Account account : getAccounts()) {
4267 if ((account.isEnabled() || accountJid != null)
4268 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4269 Contact contact = account.getRoster().getContactFromContactList(jid);
4270 if (contact != null) {
4271 contacts.add(contact);
4272 }
4273 }
4274 }
4275 return contacts;
4276 }
4277
4278 public Conversation findFirstMuc(Jid jid) {
4279 for (Conversation conversation : getConversations()) {
4280 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4281 return conversation;
4282 }
4283 }
4284 return null;
4285 }
4286
4287 public NotificationService getNotificationService() {
4288 return this.mNotificationService;
4289 }
4290
4291 public HttpConnectionManager getHttpConnectionManager() {
4292 return this.mHttpConnectionManager;
4293 }
4294
4295 public void resendFailedMessages(final Message message) {
4296 final Collection<Message> messages = new ArrayList<>();
4297 Message current = message;
4298 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4299 messages.add(current);
4300 if (current.mergeable(current.next())) {
4301 current = current.next();
4302 } else {
4303 break;
4304 }
4305 }
4306 for (final Message msg : messages) {
4307 msg.setTime(System.currentTimeMillis());
4308 markMessage(msg, Message.STATUS_WAITING);
4309 this.resendMessage(msg, false);
4310 }
4311 if (message.getConversation() instanceof Conversation) {
4312 ((Conversation) message.getConversation()).sort();
4313 }
4314 updateConversationUi();
4315 }
4316
4317 public void clearConversationHistory(final Conversation conversation) {
4318 final long clearDate;
4319 final String reference;
4320 if (conversation.countMessages() > 0) {
4321 Message latestMessage = conversation.getLatestMessage();
4322 clearDate = latestMessage.getTimeSent() + 1000;
4323 reference = latestMessage.getServerMsgId();
4324 } else {
4325 clearDate = System.currentTimeMillis();
4326 reference = null;
4327 }
4328 conversation.clearMessages();
4329 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4330 conversation.setLastClearHistory(clearDate, reference);
4331 Runnable runnable = () -> {
4332 databaseBackend.deleteMessagesInConversation(conversation);
4333 databaseBackend.updateConversation(conversation);
4334 };
4335 mDatabaseWriterExecutor.execute(runnable);
4336 }
4337
4338 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4339 if (blockable != null && blockable.getBlockedJid() != null) {
4340 final Jid jid = blockable.getBlockedJid();
4341 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4342 if (response.getType() == IqPacket.TYPE.RESULT) {
4343 a.getBlocklist().add(jid);
4344 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4345 }
4346 });
4347 if (blockable.getBlockedJid().isFullJid()) {
4348 return false;
4349 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4350 updateConversationUi();
4351 return true;
4352 } else {
4353 return false;
4354 }
4355 } else {
4356 return false;
4357 }
4358 }
4359
4360 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4361 boolean removed = false;
4362 synchronized (this.conversations) {
4363 boolean domainJid = blockedJid.getLocal() == null;
4364 for (Conversation conversation : this.conversations) {
4365 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4366 || blockedJid.equals(conversation.getJid().asBareJid());
4367 if (conversation.getAccount() == account
4368 && conversation.getMode() == Conversation.MODE_SINGLE
4369 && jidMatches) {
4370 this.conversations.remove(conversation);
4371 markRead(conversation);
4372 conversation.setStatus(Conversation.STATUS_ARCHIVED);
4373 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4374 updateConversation(conversation);
4375 removed = true;
4376 }
4377 }
4378 }
4379 return removed;
4380 }
4381
4382 public void sendUnblockRequest(final Blockable blockable) {
4383 if (blockable != null && blockable.getJid() != null) {
4384 final Jid jid = blockable.getBlockedJid();
4385 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4386 @Override
4387 public void onIqPacketReceived(final Account account, final IqPacket packet) {
4388 if (packet.getType() == IqPacket.TYPE.RESULT) {
4389 account.getBlocklist().remove(jid);
4390 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4391 }
4392 }
4393 });
4394 }
4395 }
4396
4397 public void publishDisplayName(Account account) {
4398 String displayName = account.getDisplayName();
4399 final IqPacket request;
4400 if (TextUtils.isEmpty(displayName)) {
4401 request = mIqGenerator.deleteNode(Namespace.NICK);
4402 } else {
4403 request = mIqGenerator.publishNick(displayName);
4404 }
4405 mAvatarService.clear(account);
4406 sendIqPacket(account, request, (account1, packet) -> {
4407 if (packet.getType() == IqPacket.TYPE.ERROR) {
4408 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet.toString());
4409 }
4410 });
4411 }
4412
4413 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4414 ServiceDiscoveryResult result = discoCache.get(key);
4415 if (result != null) {
4416 return result;
4417 } else {
4418 result = databaseBackend.findDiscoveryResult(key.first, key.second);
4419 if (result != null) {
4420 discoCache.put(key, result);
4421 }
4422 return result;
4423 }
4424 }
4425
4426 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4427 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4428 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4429 if (disco != null) {
4430 presence.setServiceDiscoveryResult(disco);
4431 } else {
4432 if (!account.inProgressDiscoFetches.contains(key)) {
4433 account.inProgressDiscoFetches.add(key);
4434 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4435 request.setTo(jid);
4436 final String node = presence.getNode();
4437 final String ver = presence.getVer();
4438 final Element query = request.query(Namespace.DISCO_INFO);
4439 if (node != null && ver != null) {
4440 query.setAttribute("node", node + "#" + ver);
4441 }
4442 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4443 sendIqPacket(account, request, (a, response) -> {
4444 if (response.getType() == IqPacket.TYPE.RESULT) {
4445 ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4446 if (presence.getVer().equals(discoveryResult.getVer())) {
4447 databaseBackend.insertDiscoveryResult(discoveryResult);
4448 injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4449 } else {
4450 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4451 }
4452 }
4453 a.inProgressDiscoFetches.remove(key);
4454 });
4455 }
4456 }
4457 }
4458
4459 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4460 for (Contact contact : roster.getContacts()) {
4461 for (Presence presence : contact.getPresences().getPresences().values()) {
4462 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4463 presence.setServiceDiscoveryResult(disco);
4464 }
4465 }
4466 }
4467 }
4468
4469 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4470 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4471 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4472 request.addChild("prefs", version.namespace);
4473 sendIqPacket(account, request, (account1, packet) -> {
4474 Element prefs = packet.findChild("prefs", version.namespace);
4475 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4476 callback.onPreferencesFetched(prefs);
4477 } else {
4478 callback.onPreferencesFetchFailed();
4479 }
4480 });
4481 }
4482
4483 public PushManagementService getPushManagementService() {
4484 return mPushManagementService;
4485 }
4486
4487 public void changeStatus(Account account, PresenceTemplate template, String signature) {
4488 if (!template.getStatusMessage().isEmpty()) {
4489 databaseBackend.insertPresenceTemplate(template);
4490 }
4491 account.setPgpSignature(signature);
4492 account.setPresenceStatus(template.getStatus());
4493 account.setPresenceStatusMessage(template.getStatusMessage());
4494 databaseBackend.updateAccount(account);
4495 sendPresence(account);
4496 }
4497
4498 public List<PresenceTemplate> getPresenceTemplates(Account account) {
4499 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4500 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4501 if (!templates.contains(template)) {
4502 templates.add(0, template);
4503 }
4504 }
4505 return templates;
4506 }
4507
4508 public void saveConversationAsBookmark(Conversation conversation, String name) {
4509 final Account account = conversation.getAccount();
4510 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4511 final String nick = conversation.getJid().getResource();
4512 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4513 bookmark.setNick(nick);
4514 }
4515 if (!TextUtils.isEmpty(name)) {
4516 bookmark.setBookmarkName(name);
4517 }
4518 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4519 createBookmark(account, bookmark);
4520 bookmark.setConversation(conversation);
4521 }
4522
4523 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4524 boolean performedVerification = false;
4525 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4526 for (XmppUri.Fingerprint fp : fingerprints) {
4527 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4528 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4529 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4530 if (fingerprintStatus != null) {
4531 if (!fingerprintStatus.isVerified()) {
4532 performedVerification = true;
4533 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4534 }
4535 } else {
4536 axolotlService.preVerifyFingerprint(contact, fingerprint);
4537 }
4538 }
4539 }
4540 return performedVerification;
4541 }
4542
4543 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4544 final AxolotlService axolotlService = account.getAxolotlService();
4545 boolean verifiedSomething = false;
4546 for (XmppUri.Fingerprint fp : fingerprints) {
4547 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4548 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4549 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4550 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4551 if (fingerprintStatus != null) {
4552 if (!fingerprintStatus.isVerified()) {
4553 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4554 verifiedSomething = true;
4555 }
4556 } else {
4557 axolotlService.preVerifyFingerprint(account, fingerprint);
4558 verifiedSomething = true;
4559 }
4560 }
4561 }
4562 return verifiedSomething;
4563 }
4564
4565 public boolean blindTrustBeforeVerification() {
4566 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4567 }
4568
4569 public ShortcutService getShortcutService() {
4570 return mShortcutService;
4571 }
4572
4573 public void pushMamPreferences(Account account, Element prefs) {
4574 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4575 set.addChild(prefs);
4576 sendIqPacket(account, set, null);
4577 }
4578
4579 public interface OnMamPreferencesFetched {
4580 void onPreferencesFetched(Element prefs);
4581
4582 void onPreferencesFetchFailed();
4583 }
4584
4585 public interface OnAccountCreated {
4586 void onAccountCreated(Account account);
4587
4588 void informUser(int r);
4589 }
4590
4591 public interface OnMoreMessagesLoaded {
4592 void onMoreMessagesLoaded(int count, Conversation conversation);
4593
4594 void informUser(int r);
4595 }
4596
4597 public interface OnAccountPasswordChanged {
4598 void onPasswordChangeSucceeded();
4599
4600 void onPasswordChangeFailed();
4601 }
4602
4603 public interface OnRoomDestroy {
4604 void onRoomDestroySucceeded();
4605
4606 void onRoomDestroyFailed();
4607 }
4608
4609 public interface OnAffiliationChanged {
4610 void onAffiliationChangedSuccessful(Jid jid);
4611
4612 void onAffiliationChangeFailed(Jid jid, int resId);
4613 }
4614
4615 public interface OnConversationUpdate {
4616 void onConversationUpdate();
4617 }
4618
4619 public interface OnAccountUpdate {
4620 void onAccountUpdate();
4621 }
4622
4623 public interface OnCaptchaRequested {
4624 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4625 }
4626
4627 public interface OnRosterUpdate {
4628 void onRosterUpdate();
4629 }
4630
4631 public interface OnMucRosterUpdate {
4632 void onMucRosterUpdate();
4633 }
4634
4635 public interface OnConferenceConfigurationFetched {
4636 void onConferenceConfigurationFetched(Conversation conversation);
4637
4638 void onFetchFailed(Conversation conversation, Element error);
4639 }
4640
4641 public interface OnConferenceJoined {
4642 void onConferenceJoined(Conversation conversation);
4643 }
4644
4645 public interface OnConfigurationPushed {
4646 void onPushSucceeded();
4647
4648 void onPushFailed();
4649 }
4650
4651 public interface OnShowErrorToast {
4652 void onShowErrorToast(int resId);
4653 }
4654
4655 public class XmppConnectionBinder extends Binder {
4656 public XmppConnectionService getService() {
4657 return XmppConnectionService.this;
4658 }
4659 }
4660
4661 private class InternalEventReceiver extends BroadcastReceiver {
4662
4663 @Override
4664 public void onReceive(Context context, Intent intent) {
4665 onStartCommand(intent, 0, 0);
4666 }
4667 }
4668}