1package eu.siacs.conversations.services;
2
3import static eu.siacs.conversations.utils.Compatibility.s;
4import static eu.siacs.conversations.utils.Random.SECURE_RANDOM;
5
6import android.Manifest;
7import android.annotation.SuppressLint;
8import android.app.AlarmManager;
9import android.app.KeyguardManager;
10import android.app.Notification;
11import android.app.NotificationManager;
12import android.app.PendingIntent;
13import android.app.Service;
14import android.content.BroadcastReceiver;
15import android.content.ComponentName;
16import android.content.Context;
17import android.content.Intent;
18import android.content.IntentFilter;
19import android.content.SharedPreferences;
20import android.content.pm.PackageManager;
21import android.content.pm.ServiceInfo;
22import android.database.ContentObserver;
23import android.graphics.Bitmap;
24import android.media.AudioManager;
25import android.net.ConnectivityManager;
26import android.net.Network;
27import android.net.NetworkCapabilities;
28import android.net.NetworkInfo;
29import android.net.Uri;
30import android.os.Binder;
31import android.os.Build;
32import android.os.Bundle;
33import android.os.Environment;
34import android.os.IBinder;
35import android.os.Messenger;
36import android.os.PowerManager;
37import android.os.PowerManager.WakeLock;
38import android.os.SystemClock;
39import android.preference.PreferenceManager;
40import android.provider.ContactsContract;
41import android.security.KeyChain;
42import android.text.TextUtils;
43import android.util.DisplayMetrics;
44import android.util.Log;
45import android.util.LruCache;
46import android.util.Pair;
47import androidx.annotation.BoolRes;
48import androidx.annotation.IntegerRes;
49import androidx.annotation.NonNull;
50import androidx.annotation.Nullable;
51import androidx.core.app.RemoteInput;
52import androidx.core.content.ContextCompat;
53import com.google.common.base.Objects;
54import com.google.common.base.Optional;
55import com.google.common.base.Strings;
56import com.google.common.collect.Collections2;
57import com.google.common.collect.ImmutableMap;
58import com.google.common.collect.ImmutableSet;
59import com.google.common.collect.Iterables;
60import com.google.common.collect.Maps;
61import eu.siacs.conversations.AppSettings;
62import eu.siacs.conversations.Config;
63import eu.siacs.conversations.R;
64import eu.siacs.conversations.android.JabberIdContact;
65import eu.siacs.conversations.crypto.OmemoSetting;
66import eu.siacs.conversations.crypto.PgpDecryptionService;
67import eu.siacs.conversations.crypto.PgpEngine;
68import eu.siacs.conversations.crypto.axolotl.AxolotlService;
69import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
70import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
71import eu.siacs.conversations.entities.Account;
72import eu.siacs.conversations.entities.Blockable;
73import eu.siacs.conversations.entities.Bookmark;
74import eu.siacs.conversations.entities.Contact;
75import eu.siacs.conversations.entities.Conversation;
76import eu.siacs.conversations.entities.Conversational;
77import eu.siacs.conversations.entities.Message;
78import eu.siacs.conversations.entities.MucOptions;
79import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
80import eu.siacs.conversations.entities.Presence;
81import eu.siacs.conversations.entities.PresenceTemplate;
82import eu.siacs.conversations.entities.Reaction;
83import eu.siacs.conversations.entities.Roster;
84import eu.siacs.conversations.entities.ServiceDiscoveryResult;
85import eu.siacs.conversations.generator.AbstractGenerator;
86import eu.siacs.conversations.generator.IqGenerator;
87import eu.siacs.conversations.generator.MessageGenerator;
88import eu.siacs.conversations.generator.PresenceGenerator;
89import eu.siacs.conversations.http.HttpConnectionManager;
90import eu.siacs.conversations.parser.AbstractParser;
91import eu.siacs.conversations.parser.IqParser;
92import eu.siacs.conversations.persistance.DatabaseBackend;
93import eu.siacs.conversations.persistance.FileBackend;
94import eu.siacs.conversations.persistance.UnifiedPushDatabase;
95import eu.siacs.conversations.receiver.SystemEventReceiver;
96import eu.siacs.conversations.ui.ChooseAccountForProfilePictureActivity;
97import eu.siacs.conversations.ui.ConversationsActivity;
98import eu.siacs.conversations.ui.RtpSessionActivity;
99import eu.siacs.conversations.ui.UiCallback;
100import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
101import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
102import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
103import eu.siacs.conversations.utils.AccountUtils;
104import eu.siacs.conversations.utils.Compatibility;
105import eu.siacs.conversations.utils.ConversationsFileObserver;
106import eu.siacs.conversations.utils.CryptoHelper;
107import eu.siacs.conversations.utils.EasyOnboardingInvite;
108import eu.siacs.conversations.utils.Emoticons;
109import eu.siacs.conversations.utils.MimeUtils;
110import eu.siacs.conversations.utils.PhoneHelper;
111import eu.siacs.conversations.utils.QuickLoader;
112import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
113import eu.siacs.conversations.utils.ReplacingTaskManager;
114import eu.siacs.conversations.utils.Resolver;
115import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
116import eu.siacs.conversations.utils.StringUtils;
117import eu.siacs.conversations.utils.TorServiceUtils;
118import eu.siacs.conversations.utils.WakeLockHelper;
119import eu.siacs.conversations.utils.XmppUri;
120import eu.siacs.conversations.xml.Element;
121import eu.siacs.conversations.xml.LocalizedContent;
122import eu.siacs.conversations.xml.Namespace;
123import eu.siacs.conversations.xmpp.Jid;
124import eu.siacs.conversations.xmpp.OnContactStatusChanged;
125import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
126import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
127import eu.siacs.conversations.xmpp.OnStatusChanged;
128import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
129import eu.siacs.conversations.xmpp.XmppConnection;
130import eu.siacs.conversations.xmpp.chatstate.ChatState;
131import eu.siacs.conversations.xmpp.forms.Data;
132import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
133import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
134import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
135import eu.siacs.conversations.xmpp.jingle.Media;
136import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
137import eu.siacs.conversations.xmpp.mam.MamReference;
138import eu.siacs.conversations.xmpp.pep.Avatar;
139import eu.siacs.conversations.xmpp.pep.PublishOptions;
140import im.conversations.android.xmpp.model.avatar.Metadata;
141import im.conversations.android.xmpp.model.bookmark.Storage;
142import im.conversations.android.xmpp.model.mds.Displayed;
143import im.conversations.android.xmpp.model.pubsub.PubSub;
144import im.conversations.android.xmpp.model.stanza.Iq;
145import im.conversations.android.xmpp.model.storage.PrivateStorage;
146import java.io.File;
147import java.security.Security;
148import java.security.cert.CertificateException;
149import java.security.cert.X509Certificate;
150import java.util.ArrayList;
151import java.util.Arrays;
152import java.util.Collection;
153import java.util.Collections;
154import java.util.HashSet;
155import java.util.Iterator;
156import java.util.List;
157import java.util.ListIterator;
158import java.util.Map;
159import java.util.Set;
160import java.util.WeakHashMap;
161import java.util.concurrent.CopyOnWriteArrayList;
162import java.util.concurrent.CountDownLatch;
163import java.util.concurrent.Executor;
164import java.util.concurrent.Executors;
165import java.util.concurrent.RejectedExecutionException;
166import java.util.concurrent.ScheduledExecutorService;
167import java.util.concurrent.TimeUnit;
168import java.util.concurrent.atomic.AtomicBoolean;
169import java.util.concurrent.atomic.AtomicLong;
170import java.util.concurrent.atomic.AtomicReference;
171import java.util.function.Consumer;
172import me.leolin.shortcutbadger.ShortcutBadger;
173import org.conscrypt.Conscrypt;
174import org.jxmpp.stringprep.libidn.LibIdnXmppStringprep;
175import org.openintents.openpgp.IOpenPgpService2;
176import org.openintents.openpgp.util.OpenPgpApi;
177import org.openintents.openpgp.util.OpenPgpServiceConnection;
178
179public class XmppConnectionService extends Service {
180
181 public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
182 public static final String ACTION_MARK_AS_READ = "mark_as_read";
183 public static final String ACTION_SNOOZE = "snooze";
184 public static final String ACTION_CLEAR_MESSAGE_NOTIFICATION = "clear_message_notification";
185 public static final String ACTION_CLEAR_MISSED_CALL_NOTIFICATION =
186 "clear_missed_call_notification";
187 public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
188 public static final String ACTION_TRY_AGAIN = "try_again";
189
190 public static final String ACTION_TEMPORARILY_DISABLE = "temporarily_disable";
191 public static final String ACTION_PING = "ping";
192 public static final String ACTION_IDLE_PING = "idle_ping";
193 public static final String ACTION_INTERNAL_PING = "internal_ping";
194 public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
195 public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
196 public static final String ACTION_DISMISS_CALL = "dismiss_call";
197 public static final String ACTION_END_CALL = "end_call";
198 public static final String ACTION_PROVISION_ACCOUNT = "provision_account";
199 public static final String ACTION_CALL_INTEGRATION_SERVICE_STARTED =
200 "call_integration_service_started";
201 private static final String ACTION_POST_CONNECTIVITY_CHANGE =
202 "eu.siacs.conversations.POST_CONNECTIVITY_CHANGE";
203 public static final String ACTION_RENEW_UNIFIED_PUSH_ENDPOINTS =
204 "eu.siacs.conversations.UNIFIED_PUSH_RENEW";
205 public static final String ACTION_QUICK_LOG = "eu.siacs.conversations.QUICK_LOG";
206
207 private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
208
209 public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
210 private static final Executor FILE_OBSERVER_EXECUTOR = Executors.newSingleThreadExecutor();
211 public static final Executor FILE_ATTACHMENT_EXECUTOR = Executors.newSingleThreadExecutor();
212
213 private final ScheduledExecutorService internalPingExecutor =
214 Executors.newSingleThreadScheduledExecutor();
215 private static final SerialSingleThreadExecutor VIDEO_COMPRESSION_EXECUTOR =
216 new SerialSingleThreadExecutor("VideoCompression");
217 private final SerialSingleThreadExecutor mDatabaseWriterExecutor =
218 new SerialSingleThreadExecutor("DatabaseWriter");
219 private final SerialSingleThreadExecutor mDatabaseReaderExecutor =
220 new SerialSingleThreadExecutor("DatabaseReader");
221 private final SerialSingleThreadExecutor mNotificationExecutor =
222 new SerialSingleThreadExecutor("NotificationExecutor");
223 private final ReplacingTaskManager mRosterSyncTaskManager = new ReplacingTaskManager();
224 private final IBinder mBinder = new XmppConnectionBinder();
225 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
226 private final IqGenerator mIqGenerator = new IqGenerator(this);
227 private final Set<String> mInProgressAvatarFetches = new HashSet<>();
228 private final Set<String> mOmittedPepAvatarFetches = new HashSet<>();
229 private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
230 private final Consumer<Iq> mDefaultIqHandler =
231 (packet) -> {
232 if (packet.getType() != Iq.Type.RESULT) {
233 final var error = packet.getError();
234 String text = error != null ? error.findChildContent("text") : null;
235 if (text != null) {
236 Log.d(Config.LOGTAG, "received iq error: " + text);
237 }
238 }
239 };
240 public DatabaseBackend databaseBackend;
241 private final ReplacingSerialSingleThreadExecutor mContactMergerExecutor =
242 new ReplacingSerialSingleThreadExecutor("ContactMerger");
243 private long mLastActivity = 0;
244
245 private final AppSettings appSettings = new AppSettings(this);
246 private final FileBackend fileBackend = new FileBackend(this);
247 private MemorizingTrustManager mMemorizingTrustManager;
248 private final NotificationService mNotificationService = new NotificationService(this);
249 private final UnifiedPushBroker unifiedPushBroker = new UnifiedPushBroker(this);
250 private final ChannelDiscoveryService mChannelDiscoveryService =
251 new ChannelDiscoveryService(this);
252 private final ShortcutService mShortcutService = new ShortcutService(this);
253 private final AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
254 private final AtomicBoolean mOngoingVideoTranscoding = new AtomicBoolean(false);
255 private final AtomicBoolean mForceDuringOnCreate = new AtomicBoolean(false);
256 private final AtomicReference<OngoingCall> ongoingCall = new AtomicReference<>();
257 private final MessageGenerator mMessageGenerator = new MessageGenerator(this);
258 public OnContactStatusChanged onContactStatusChanged =
259 (contact, online) -> {
260 final var conversation = find(contact);
261 if (conversation == null) {
262 return;
263 }
264 if (online) {
265 if (contact.getPresences().size() == 1) {
266 sendUnsentMessages(conversation);
267 }
268 }
269 };
270 private final PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
271 private List<Account> accounts;
272 private final JingleConnectionManager mJingleConnectionManager =
273 new JingleConnectionManager(this);
274 private final HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
275 private final AvatarService mAvatarService = new AvatarService(this);
276 private final MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
277 private final PushManagementService mPushManagementService = new PushManagementService(this);
278 private final QuickConversationsService mQuickConversationsService =
279 new QuickConversationsService(this);
280 private final ConversationsFileObserver fileObserver =
281 new ConversationsFileObserver(
282 Environment.getExternalStorageDirectory().getAbsolutePath()) {
283 @Override
284 public void onEvent(final int event, final File file) {
285 markFileDeleted(file);
286 }
287 };
288 private final OnMessageAcknowledged mOnMessageAcknowledgedListener =
289 new OnMessageAcknowledged() {
290
291 @Override
292 public boolean onMessageAcknowledged(
293 final Account account, final Jid to, final String id) {
294 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
295 final String sessionId =
296 id.substring(
297 JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX
298 .length());
299 mJingleConnectionManager.updateProposedSessionDiscovered(
300 account,
301 to,
302 sessionId,
303 JingleConnectionManager.DeviceDiscoveryState
304 .SEARCHING_ACKNOWLEDGED);
305 }
306
307 final Jid bare = to.asBareJid();
308
309 for (final Conversation conversation : getConversations()) {
310 if (conversation.getAccount() == account
311 && conversation.getJid().asBareJid().equals(bare)) {
312 final Message message = conversation.findUnsentMessageWithUuid(id);
313 if (message != null) {
314 message.setStatus(Message.STATUS_SEND);
315 message.setErrorMessage(null);
316 databaseBackend.updateMessage(message, false);
317 return true;
318 }
319 }
320 }
321 return false;
322 }
323 };
324
325 private boolean destroyed = false;
326
327 private int unreadCount = -1;
328
329 // Ui callback listeners
330 private final Set<OnConversationUpdate> mOnConversationUpdates =
331 Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
332 private final Set<OnShowErrorToast> mOnShowErrorToasts =
333 Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
334 private final Set<OnAccountUpdate> mOnAccountUpdates =
335 Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
336 private final Set<OnCaptchaRequested> mOnCaptchaRequested =
337 Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
338 private final Set<OnRosterUpdate> mOnRosterUpdates =
339 Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
340 private final Set<OnUpdateBlocklist> mOnUpdateBlocklist =
341 Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
342 private final Set<OnMucRosterUpdate> mOnMucRosterUpdate =
343 Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
344 private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated =
345 Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
346 private final Set<OnJingleRtpConnectionUpdate> onJingleRtpConnectionUpdate =
347 Collections.newSetFromMap(new WeakHashMap<OnJingleRtpConnectionUpdate, Boolean>());
348
349 private final Object LISTENER_LOCK = new Object();
350
351 public final Set<String> FILENAMES_TO_IGNORE_DELETION = new HashSet<>();
352
353 private final AtomicLong mLastExpiryRun = new AtomicLong(0);
354 private final LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache =
355 new LruCache<>(20);
356 private final OnStatusChanged statusListener =
357 new OnStatusChanged() {
358
359 @Override
360 public void onStatusChanged(final Account account) {
361 XmppConnection connection = account.getXmppConnection();
362 updateAccountUi();
363
364 if (account.getStatus() == Account.State.ONLINE
365 || account.getStatus().isError()) {
366 mQuickConversationsService.signalAccountStateChange();
367 }
368
369 if (account.getStatus() == Account.State.ONLINE) {
370 synchronized (mLowPingTimeoutMode) {
371 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
372 Log.d(
373 Config.LOGTAG,
374 account.getJid().asBareJid()
375 + ": leaving low ping timeout mode");
376 }
377 }
378 if (account.setShowErrorNotification(true)) {
379 databaseBackend.updateAccount(account);
380 }
381 mMessageArchiveService.executePendingQueries(account);
382 if (connection != null && connection.getFeatures().csi()) {
383 if (checkListeners()) {
384 Log.d(
385 Config.LOGTAG,
386 account.getJid().asBareJid() + " sending csi//inactive");
387 connection.sendInactive();
388 } else {
389 Log.d(
390 Config.LOGTAG,
391 account.getJid().asBareJid() + " sending csi//active");
392 connection.sendActive();
393 }
394 }
395 List<Conversation> conversations = getConversations();
396 for (Conversation conversation : conversations) {
397 final boolean inProgressJoin;
398 synchronized (account.inProgressConferenceJoins) {
399 inProgressJoin =
400 account.inProgressConferenceJoins.contains(conversation);
401 }
402 final boolean pendingJoin;
403 synchronized (account.pendingConferenceJoins) {
404 pendingJoin = account.pendingConferenceJoins.contains(conversation);
405 }
406 if (conversation.getAccount() == account
407 && !pendingJoin
408 && !inProgressJoin) {
409 sendUnsentMessages(conversation);
410 }
411 }
412 final List<Conversation> pendingLeaves;
413 synchronized (account.pendingConferenceLeaves) {
414 pendingLeaves = new ArrayList<>(account.pendingConferenceLeaves);
415 account.pendingConferenceLeaves.clear();
416 }
417 for (Conversation conversation : pendingLeaves) {
418 leaveMuc(conversation);
419 }
420 final List<Conversation> pendingJoins;
421 synchronized (account.pendingConferenceJoins) {
422 pendingJoins = new ArrayList<>(account.pendingConferenceJoins);
423 account.pendingConferenceJoins.clear();
424 }
425 for (Conversation conversation : pendingJoins) {
426 joinMuc(conversation);
427 }
428 scheduleWakeUpCall(
429 Config.PING_MAX_INTERVAL * 1000L, account.getUuid().hashCode());
430 } else if (account.getStatus() == Account.State.OFFLINE
431 || account.getStatus() == Account.State.DISABLED
432 || account.getStatus() == Account.State.LOGGED_OUT) {
433 resetSendingToWaiting(account);
434 if (account.isConnectionEnabled() && isInLowPingTimeoutMode(account)) {
435 Log.d(
436 Config.LOGTAG,
437 account.getJid().asBareJid()
438 + ": went into offline state during low ping mode."
439 + " reconnecting now");
440 reconnectAccount(account, true, false);
441 } else {
442 final int timeToReconnect = SECURE_RANDOM.nextInt(10) + 2;
443 scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
444 }
445 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
446 databaseBackend.updateAccount(account);
447 reconnectAccount(account, true, false);
448 } else if (account.getStatus() != Account.State.CONNECTING
449 && account.getStatus() != Account.State.NO_INTERNET) {
450 resetSendingToWaiting(account);
451 if (connection != null && account.getStatus().isAttemptReconnect()) {
452 final boolean aggressive =
453 account.getStatus() == Account.State.SEE_OTHER_HOST
454 || hasJingleRtpConnection(account);
455 final int next = connection.getTimeToNextAttempt(aggressive);
456 final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
457 if (next <= 0) {
458 Log.d(
459 Config.LOGTAG,
460 account.getJid().asBareJid()
461 + ": error connecting account. reconnecting now."
462 + " lowPingTimeout="
463 + lowPingTimeoutMode);
464 reconnectAccount(account, true, false);
465 } else {
466 final int attempt = connection.getAttempt() + 1;
467 Log.d(
468 Config.LOGTAG,
469 account.getJid().asBareJid()
470 + ": error connecting account. try again in "
471 + next
472 + "s for the "
473 + attempt
474 + " time. lowPingTimeout="
475 + lowPingTimeoutMode
476 + ", aggressive="
477 + aggressive);
478 scheduleWakeUpCall(next, account.getUuid().hashCode());
479 if (aggressive) {
480 internalPingExecutor.schedule(
481 XmppConnectionService.this
482 ::manageAccountConnectionStatesInternal,
483 (next * 1000L) + 50,
484 TimeUnit.MILLISECONDS);
485 }
486 }
487 }
488 }
489 getNotificationService().updateErrorNotification();
490 }
491 };
492 private OpenPgpServiceConnection pgpServiceConnection;
493 private PgpEngine mPgpEngine = null;
494 private WakeLock wakeLock;
495 private LruCache<String, Bitmap> mBitmapCache;
496 private final BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
497 private final BroadcastReceiver mInternalRestrictedEventReceiver =
498 new RestrictedEventReceiver(Arrays.asList(TorServiceUtils.ACTION_STATUS));
499 private final BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
500
501 private static String generateFetchKey(Account account, final Avatar avatar) {
502 return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
503 }
504
505 private boolean isInLowPingTimeoutMode(Account account) {
506 synchronized (mLowPingTimeoutMode) {
507 return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
508 }
509 }
510
511 public void startOngoingVideoTranscodingForegroundNotification() {
512 mOngoingVideoTranscoding.set(true);
513 toggleForegroundService();
514 }
515
516 public void stopOngoingVideoTranscodingForegroundNotification() {
517 mOngoingVideoTranscoding.set(false);
518 toggleForegroundService();
519 }
520
521 public boolean areMessagesInitialized() {
522 return this.restoredFromDatabaseLatch.getCount() == 0;
523 }
524
525 public PgpEngine getPgpEngine() {
526 if (!Config.supportOpenPgp()) {
527 return null;
528 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
529 if (this.mPgpEngine == null) {
530 this.mPgpEngine =
531 new PgpEngine(
532 new OpenPgpApi(
533 getApplicationContext(), pgpServiceConnection.getService()),
534 this);
535 }
536 return mPgpEngine;
537 } else {
538 return null;
539 }
540 }
541
542 public OpenPgpApi getOpenPgpApi() {
543 if (!Config.supportOpenPgp()) {
544 return null;
545 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
546 return new OpenPgpApi(this, pgpServiceConnection.getService());
547 } else {
548 return null;
549 }
550 }
551
552 public AppSettings getAppSettings() {
553 return this.appSettings;
554 }
555
556 public FileBackend getFileBackend() {
557 return this.fileBackend;
558 }
559
560 public AvatarService getAvatarService() {
561 return this.mAvatarService;
562 }
563
564 public void attachLocationToConversation(
565 final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
566 int encryption = conversation.getNextEncryption();
567 if (encryption == Message.ENCRYPTION_PGP) {
568 encryption = Message.ENCRYPTION_DECRYPTED;
569 }
570 Message message = new Message(conversation, uri.toString(), encryption);
571 Message.configurePrivateMessage(message);
572 if (encryption == Message.ENCRYPTION_DECRYPTED) {
573 getPgpEngine().encrypt(message, callback);
574 } else {
575 sendMessage(message);
576 callback.success(message);
577 }
578 }
579
580 public void attachFileToConversation(
581 final Conversation conversation,
582 final Uri uri,
583 final String type,
584 final UiCallback<Message> callback) {
585 final Message message;
586 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
587 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
588 } else {
589 message = new Message(conversation, "", conversation.getNextEncryption());
590 }
591 if (!Message.configurePrivateFileMessage(message)) {
592 message.setCounterpart(conversation.getNextCounterpart());
593 message.setType(Message.TYPE_FILE);
594 }
595 Log.d(Config.LOGTAG, "attachFile: type=" + message.getType());
596 Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart());
597 final AttachFileToConversationRunnable runnable =
598 new AttachFileToConversationRunnable(this, uri, type, message, callback);
599 if (runnable.isVideoMessage()) {
600 VIDEO_COMPRESSION_EXECUTOR.execute(runnable);
601 } else {
602 FILE_ATTACHMENT_EXECUTOR.execute(runnable);
603 }
604 }
605
606 public void attachImageToConversation(
607 final Conversation conversation,
608 final Uri uri,
609 final String type,
610 final UiCallback<Message> callback) {
611 final String mimeType = MimeUtils.guessMimeTypeFromUriAndMime(this, uri, type);
612 final String compressPictures = getCompressPicturesPreference();
613
614 if ("never".equals(compressPictures)
615 || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
616 || (mimeType != null && mimeType.endsWith("/gif"))
617 || getFileBackend().unusualBounds(uri)) {
618 Log.d(
619 Config.LOGTAG,
620 conversation.getAccount().getJid().asBareJid()
621 + ": not compressing picture. sending as file");
622 attachFileToConversation(conversation, uri, mimeType, callback);
623 return;
624 }
625 final Message message;
626 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
627 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
628 } else {
629 message = new Message(conversation, "", conversation.getNextEncryption());
630 }
631 if (!Message.configurePrivateFileMessage(message)) {
632 message.setCounterpart(conversation.getNextCounterpart());
633 message.setType(Message.TYPE_IMAGE);
634 }
635 Log.d(Config.LOGTAG, "attachImage: type=" + message.getType());
636 FILE_ATTACHMENT_EXECUTOR.execute(
637 () -> {
638 try {
639 getFileBackend().copyImageToPrivateStorage(message, uri);
640 } catch (FileBackend.ImageCompressionException e) {
641 Log.d(
642 Config.LOGTAG,
643 "unable to compress image. fall back to file transfer",
644 e);
645 attachFileToConversation(conversation, uri, mimeType, callback);
646 return;
647 } catch (final FileBackend.FileCopyException e) {
648 callback.error(e.getResId(), message);
649 return;
650 }
651 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
652 final PgpEngine pgpEngine = getPgpEngine();
653 if (pgpEngine != null) {
654 pgpEngine.encrypt(message, callback);
655 } else if (callback != null) {
656 callback.error(R.string.unable_to_connect_to_keychain, null);
657 }
658 } else {
659 sendMessage(message);
660 callback.success(message);
661 }
662 });
663 }
664
665 public Conversation find(Bookmark bookmark) {
666 return find(bookmark.getAccount(), bookmark.getJid());
667 }
668
669 public Conversation find(final Account account, final Jid jid) {
670 return find(getConversations(), account, jid);
671 }
672
673 public boolean isMuc(final Account account, final Jid jid) {
674 final Conversation c = find(account, jid);
675 return c != null && c.getMode() == Conversational.MODE_MULTI;
676 }
677
678 public void search(
679 final List<String> term,
680 final String uuid,
681 final OnSearchResultsAvailable onSearchResultsAvailable) {
682 MessageSearchTask.search(this, term, uuid, onSearchResultsAvailable);
683 }
684
685 @Override
686 public int onStartCommand(final Intent intent, int flags, int startId) {
687 final String action = Strings.nullToEmpty(intent == null ? null : intent.getAction());
688 final boolean needsForegroundService =
689 intent != null
690 && intent.getBooleanExtra(
691 SystemEventReceiver.EXTRA_NEEDS_FOREGROUND_SERVICE, false);
692 if (needsForegroundService) {
693 Log.d(
694 Config.LOGTAG,
695 "toggle forced foreground service after receiving event (action="
696 + action
697 + ")");
698 toggleForegroundService(true);
699 }
700 final String uuid = intent == null ? null : intent.getStringExtra("uuid");
701 switch (action) {
702 case QuickConversationsService.SMS_RETRIEVED_ACTION:
703 mQuickConversationsService.handleSmsReceived(intent);
704 break;
705 case ConnectivityManager.CONNECTIVITY_ACTION:
706 if (hasInternetConnection()) {
707 if (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0) {
708 schedulePostConnectivityChange();
709 }
710 if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
711 resetAllAttemptCounts(true, false);
712 }
713 Resolver.clearCache();
714 }
715 break;
716 case Intent.ACTION_SHUTDOWN:
717 logoutAndSave(true);
718 return START_NOT_STICKY;
719 case ACTION_CLEAR_MESSAGE_NOTIFICATION:
720 mNotificationExecutor.execute(
721 () -> {
722 try {
723 final Conversation c = findConversationByUuid(uuid);
724 if (c != null) {
725 mNotificationService.clearMessages(c);
726 } else {
727 mNotificationService.clearMessages();
728 }
729 restoredFromDatabaseLatch.await();
730
731 } catch (InterruptedException e) {
732 Log.d(
733 Config.LOGTAG,
734 "unable to process clear message notification");
735 }
736 });
737 break;
738 case ACTION_CLEAR_MISSED_CALL_NOTIFICATION:
739 mNotificationExecutor.execute(
740 () -> {
741 try {
742 final Conversation c = findConversationByUuid(uuid);
743 if (c != null) {
744 mNotificationService.clearMissedCalls(c);
745 } else {
746 mNotificationService.clearMissedCalls();
747 }
748 restoredFromDatabaseLatch.await();
749
750 } catch (InterruptedException e) {
751 Log.d(
752 Config.LOGTAG,
753 "unable to process clear missed call notification");
754 }
755 });
756 break;
757 case ACTION_DISMISS_CALL:
758 {
759 if (intent == null) {
760 break;
761 }
762 final String sessionId =
763 intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
764 Log.d(
765 Config.LOGTAG,
766 "received intent to dismiss call with session id " + sessionId);
767 mJingleConnectionManager.rejectRtpSession(sessionId);
768 break;
769 }
770 case TorServiceUtils.ACTION_STATUS:
771 final String status =
772 intent == null ? null : intent.getStringExtra(TorServiceUtils.EXTRA_STATUS);
773 // TODO port and host are in 'extras' - but this may not be a reliable source?
774 if ("ON".equals(status)) {
775 handleOrbotStartedEvent();
776 return START_STICKY;
777 }
778 break;
779 case ACTION_END_CALL:
780 {
781 if (intent == null) {
782 break;
783 }
784 final String sessionId =
785 intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
786 Log.d(
787 Config.LOGTAG,
788 "received intent to end call with session id " + sessionId);
789 mJingleConnectionManager.endRtpSession(sessionId);
790 }
791 break;
792 case ACTION_PROVISION_ACCOUNT:
793 {
794 if (intent == null) {
795 break;
796 }
797 final String address = intent.getStringExtra("address");
798 final String password = intent.getStringExtra("password");
799 if (QuickConversationsService.isQuicksy()
800 || Strings.isNullOrEmpty(address)
801 || Strings.isNullOrEmpty(password)) {
802 break;
803 }
804 provisionAccount(address, password);
805 break;
806 }
807 case ACTION_DISMISS_ERROR_NOTIFICATIONS:
808 dismissErrorNotifications();
809 break;
810 case ACTION_TRY_AGAIN:
811 resetAllAttemptCounts(false, true);
812 break;
813 case ACTION_REPLY_TO_CONVERSATION:
814 final Bundle remoteInput =
815 intent == null ? null : RemoteInput.getResultsFromIntent(intent);
816 if (remoteInput == null) {
817 break;
818 }
819 final CharSequence body = remoteInput.getCharSequence("text_reply");
820 final boolean dismissNotification =
821 intent.getBooleanExtra("dismiss_notification", false);
822 final String lastMessageUuid = intent.getStringExtra("last_message_uuid");
823 if (body == null || body.length() <= 0) {
824 break;
825 }
826 mNotificationExecutor.execute(
827 () -> {
828 try {
829 restoredFromDatabaseLatch.await();
830 final Conversation c = findConversationByUuid(uuid);
831 if (c != null) {
832 directReply(
833 c,
834 body.toString(),
835 lastMessageUuid,
836 dismissNotification);
837 }
838 } catch (InterruptedException e) {
839 Log.d(Config.LOGTAG, "unable to process direct reply");
840 }
841 });
842 break;
843 case ACTION_MARK_AS_READ:
844 mNotificationExecutor.execute(
845 () -> {
846 final Conversation c = findConversationByUuid(uuid);
847 if (c == null) {
848 Log.d(
849 Config.LOGTAG,
850 "received mark read intent for unknown conversation ("
851 + uuid
852 + ")");
853 return;
854 }
855 try {
856 restoredFromDatabaseLatch.await();
857 sendReadMarker(c, null);
858 } catch (InterruptedException e) {
859 Log.d(
860 Config.LOGTAG,
861 "unable to process notification read marker for"
862 + " conversation "
863 + c.getName());
864 }
865 });
866 break;
867 case ACTION_SNOOZE:
868 mNotificationExecutor.execute(
869 () -> {
870 final Conversation c = findConversationByUuid(uuid);
871 if (c == null) {
872 Log.d(
873 Config.LOGTAG,
874 "received snooze intent for unknown conversation ("
875 + uuid
876 + ")");
877 return;
878 }
879 c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
880 mNotificationService.clearMessages(c);
881 updateConversation(c);
882 });
883 case AudioManager.RINGER_MODE_CHANGED_ACTION:
884 case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
885 if (dndOnSilentMode()) {
886 refreshAllPresences();
887 }
888 break;
889 case Intent.ACTION_SCREEN_ON:
890 deactivateGracePeriod();
891 case Intent.ACTION_USER_PRESENT:
892 case Intent.ACTION_SCREEN_OFF:
893 if (awayWhenScreenLocked()) {
894 refreshAllPresences();
895 }
896 break;
897 case ACTION_FCM_TOKEN_REFRESH:
898 refreshAllFcmTokens();
899 break;
900 case ACTION_RENEW_UNIFIED_PUSH_ENDPOINTS:
901 if (intent == null) {
902 break;
903 }
904 final String instance = intent.getStringExtra("instance");
905 final String application = intent.getStringExtra("application");
906 final Messenger messenger = intent.getParcelableExtra("messenger");
907 final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger;
908 if (messenger != null && application != null && instance != null) {
909 pushTargetMessenger =
910 new UnifiedPushBroker.PushTargetMessenger(
911 new UnifiedPushDatabase.PushTarget(application, instance),
912 messenger);
913 Log.d(Config.LOGTAG, "found push target messenger");
914 } else {
915 pushTargetMessenger = null;
916 }
917 final Optional<UnifiedPushBroker.Transport> transport =
918 renewUnifiedPushEndpoints(pushTargetMessenger);
919 if (instance != null && transport.isPresent()) {
920 unifiedPushBroker.rebroadcastEndpoint(messenger, instance, transport.get());
921 }
922 break;
923 case ACTION_IDLE_PING:
924 scheduleNextIdlePing();
925 break;
926 case ACTION_FCM_MESSAGE_RECEIVED:
927 Log.d(Config.LOGTAG, "push message arrived in service. account");
928 break;
929 case ACTION_QUICK_LOG:
930 final String message = intent == null ? null : intent.getStringExtra("message");
931 if (message != null && Config.QUICK_LOG) {
932 quickLog(message);
933 }
934 break;
935 case Intent.ACTION_SEND:
936 final Uri uri = intent == null ? null : intent.getData();
937 if (uri != null) {
938 Log.d(Config.LOGTAG, "received uri permission for " + uri);
939 }
940 return START_STICKY;
941 case ACTION_TEMPORARILY_DISABLE:
942 toggleSoftDisabled(true);
943 if (checkListeners()) {
944 stopSelf();
945 }
946 return START_NOT_STICKY;
947 }
948 final var extras = intent == null ? null : intent.getExtras();
949 try {
950 internalPingExecutor.execute(() -> manageAccountConnectionStates(action, extras));
951 } catch (final RejectedExecutionException e) {
952 Log.e(Config.LOGTAG, "can not schedule connection states manager");
953 }
954 if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
955 expireOldMessages();
956 }
957 return START_STICKY;
958 }
959
960 private void quickLog(final String message) {
961 if (Strings.isNullOrEmpty(message)) {
962 return;
963 }
964 final Account account = AccountUtils.getFirstEnabled(this);
965 if (account == null) {
966 return;
967 }
968 final Conversation conversation =
969 findOrCreateConversation(account, Config.BUG_REPORTS, false, true);
970 final Message report = new Message(conversation, message, Message.ENCRYPTION_NONE);
971 report.setStatus(Message.STATUS_RECEIVED);
972 conversation.add(report);
973 databaseBackend.createMessage(report);
974 updateConversationUi();
975 }
976
977 private void manageAccountConnectionStatesInternal() {
978 manageAccountConnectionStates(ACTION_INTERNAL_PING, null);
979 }
980
981 private synchronized void manageAccountConnectionStates(
982 final String action, final Bundle extras) {
983 final String pushedAccountHash = extras == null ? null : extras.getString("account");
984 final boolean interactive = java.util.Objects.equals(ACTION_TRY_AGAIN, action);
985 WakeLockHelper.acquire(wakeLock);
986 boolean pingNow =
987 ConnectivityManager.CONNECTIVITY_ACTION.equals(action)
988 || (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0
989 && ACTION_POST_CONNECTIVITY_CHANGE.equals(action));
990 final HashSet<Account> pingCandidates = new HashSet<>();
991 final String androidId = pushedAccountHash == null ? null : PhoneHelper.getAndroidId(this);
992 for (final Account account : accounts) {
993 final boolean pushWasMeantForThisAccount =
994 androidId != null
995 && CryptoHelper.getAccountFingerprint(account, androidId)
996 .equals(pushedAccountHash);
997 pingNow |=
998 processAccountState(
999 account,
1000 interactive,
1001 "ui".equals(action),
1002 pushWasMeantForThisAccount,
1003 pingCandidates);
1004 }
1005 if (pingNow) {
1006 for (final Account account : pingCandidates) {
1007 final var connection = account.getXmppConnection();
1008 final boolean lowTimeout = isInLowPingTimeoutMode(account);
1009 final var delta =
1010 (SystemClock.elapsedRealtime() - connection.getLastPacketReceived())
1011 / 1000L;
1012 connection.sendPing();
1013 Log.d(
1014 Config.LOGTAG,
1015 String.format(
1016 "%s: send ping (action=%s,lowTimeout=%s,interval=%s)",
1017 account.getJid().asBareJid(), action, lowTimeout, delta));
1018 scheduleWakeUpCall(
1019 lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT,
1020 account.getUuid().hashCode());
1021 }
1022 }
1023 WakeLockHelper.release(wakeLock);
1024 }
1025
1026 private void handleOrbotStartedEvent() {
1027 for (final Account account : accounts) {
1028 if (account.getStatus() == Account.State.TOR_NOT_AVAILABLE) {
1029 reconnectAccount(account, true, false);
1030 }
1031 }
1032 }
1033
1034 private boolean processAccountState(
1035 final Account account,
1036 final boolean interactive,
1037 final boolean isUiAction,
1038 final boolean isAccountPushed,
1039 final HashSet<Account> pingCandidates) {
1040 if (!account.getStatus().isAttemptReconnect()) {
1041 return false;
1042 }
1043 final var requestCode = account.getUuid().hashCode();
1044 if (!hasInternetConnection()) {
1045 account.setStatus(Account.State.NO_INTERNET);
1046 statusListener.onStatusChanged(account);
1047 } else {
1048 if (account.getStatus() == Account.State.NO_INTERNET) {
1049 account.setStatus(Account.State.OFFLINE);
1050 statusListener.onStatusChanged(account);
1051 }
1052 if (account.getStatus() == Account.State.ONLINE) {
1053 synchronized (mLowPingTimeoutMode) {
1054 long lastReceived = account.getXmppConnection().getLastPacketReceived();
1055 long lastSent = account.getXmppConnection().getLastPingSent();
1056 long pingInterval =
1057 isUiAction
1058 ? Config.PING_MIN_INTERVAL * 1000
1059 : Config.PING_MAX_INTERVAL * 1000;
1060 long msToNextPing =
1061 (Math.max(lastReceived, lastSent) + pingInterval)
1062 - SystemClock.elapsedRealtime();
1063 int pingTimeout =
1064 mLowPingTimeoutMode.contains(account.getJid().asBareJid())
1065 ? Config.LOW_PING_TIMEOUT * 1000
1066 : Config.PING_TIMEOUT * 1000;
1067 long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
1068 if (lastSent > lastReceived) {
1069 if (pingTimeoutIn < 0) {
1070 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
1071 this.reconnectAccount(account, true, interactive);
1072 } else {
1073 this.scheduleWakeUpCall(pingTimeoutIn, requestCode);
1074 }
1075 } else {
1076 pingCandidates.add(account);
1077 if (isAccountPushed) {
1078 if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
1079 Log.d(
1080 Config.LOGTAG,
1081 account.getJid().asBareJid()
1082 + ": entering low ping timeout mode");
1083 }
1084 return true;
1085 } else if (msToNextPing <= 0) {
1086 return true;
1087 } else {
1088 this.scheduleWakeUpCall(msToNextPing, requestCode);
1089 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
1090 Log.d(
1091 Config.LOGTAG,
1092 account.getJid().asBareJid()
1093 + ": leaving low ping timeout mode");
1094 }
1095 }
1096 }
1097 }
1098 } else if (account.getStatus() == Account.State.OFFLINE) {
1099 reconnectAccount(account, true, interactive);
1100 } else if (account.getStatus() == Account.State.CONNECTING) {
1101 final var connection = account.getXmppConnection();
1102 final var connectionDuration = connection.getConnectionDuration();
1103 final var discoDuration = connection.getDiscoDuration();
1104 final var connectionTimeout = Config.CONNECT_TIMEOUT * 1000L - connectionDuration;
1105 final var discoTimeout = Config.CONNECT_DISCO_TIMEOUT * 1000L - discoDuration;
1106 if (connectionTimeout < 0) {
1107 connection.triggerConnectionTimeout();
1108 } else if (discoTimeout < 0) {
1109 connection.sendDiscoTimeout();
1110 scheduleWakeUpCall(discoTimeout, requestCode);
1111 } else {
1112 scheduleWakeUpCall(Math.min(connectionTimeout, discoTimeout), requestCode);
1113 }
1114 } else {
1115 final boolean aggressive =
1116 account.getStatus() == Account.State.SEE_OTHER_HOST
1117 || hasJingleRtpConnection(account);
1118 if (account.getXmppConnection().getTimeToNextAttempt(aggressive) <= 0) {
1119 reconnectAccount(account, true, interactive);
1120 }
1121 }
1122 }
1123 return false;
1124 }
1125
1126 private void toggleSoftDisabled(final boolean softDisabled) {
1127 for (final Account account : this.accounts) {
1128 if (account.isEnabled()) {
1129 if (account.setOption(Account.OPTION_SOFT_DISABLED, softDisabled)) {
1130 updateAccount(account);
1131 }
1132 }
1133 }
1134 }
1135
1136 public boolean processUnifiedPushMessage(
1137 final Account account, final Jid transport, final Element push) {
1138 return unifiedPushBroker.processPushMessage(account, transport, push);
1139 }
1140
1141 public void reinitializeMuclumbusService() {
1142 mChannelDiscoveryService.initializeMuclumbusService();
1143 }
1144
1145 public void discoverChannels(
1146 String query,
1147 ChannelDiscoveryService.Method method,
1148 ChannelDiscoveryService.OnChannelSearchResultsFound onChannelSearchResultsFound) {
1149 mChannelDiscoveryService.discover(
1150 Strings.nullToEmpty(query).trim(), method, onChannelSearchResultsFound);
1151 }
1152
1153 public boolean isDataSaverDisabled() {
1154 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
1155 return true;
1156 }
1157 final ConnectivityManager connectivityManager = getSystemService(ConnectivityManager.class);
1158 return !Compatibility.isActiveNetworkMetered(connectivityManager)
1159 || Compatibility.getRestrictBackgroundStatus(connectivityManager)
1160 == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
1161 }
1162
1163 private void directReply(
1164 final Conversation conversation,
1165 final String body,
1166 final String lastMessageUuid,
1167 final boolean dismissAfterReply) {
1168 final Message inReplyTo =
1169 lastMessageUuid == null ? null : conversation.findMessageWithUuid(lastMessageUuid);
1170 final Message message = new Message(conversation, body, conversation.getNextEncryption());
1171 if (inReplyTo != null && inReplyTo.isPrivateMessage()) {
1172 Message.configurePrivateMessage(message, inReplyTo.getCounterpart());
1173 }
1174 message.markUnread();
1175 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
1176 getPgpEngine()
1177 .encrypt(
1178 message,
1179 new UiCallback<Message>() {
1180 @Override
1181 public void success(Message message) {
1182 if (dismissAfterReply) {
1183 markRead((Conversation) message.getConversation(), true);
1184 } else {
1185 mNotificationService.pushFromDirectReply(message);
1186 }
1187 }
1188
1189 @Override
1190 public void error(int errorCode, Message object) {}
1191
1192 @Override
1193 public void userInputRequired(PendingIntent pi, Message object) {}
1194 });
1195 } else {
1196 sendMessage(message);
1197 if (dismissAfterReply) {
1198 markRead(conversation, true);
1199 } else {
1200 mNotificationService.pushFromDirectReply(message);
1201 }
1202 }
1203 }
1204
1205 private boolean dndOnSilentMode() {
1206 return getBooleanPreference(AppSettings.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
1207 }
1208
1209 private boolean manuallyChangePresence() {
1210 return getBooleanPreference(
1211 AppSettings.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
1212 }
1213
1214 private boolean treatVibrateAsSilent() {
1215 return getBooleanPreference(
1216 AppSettings.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
1217 }
1218
1219 private boolean awayWhenScreenLocked() {
1220 return getBooleanPreference(
1221 AppSettings.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
1222 }
1223
1224 private String getCompressPicturesPreference() {
1225 return getPreferences()
1226 .getString(
1227 "picture_compression",
1228 getResources().getString(R.string.picture_compression));
1229 }
1230
1231 private Presence.Status getTargetPresence() {
1232 if (dndOnSilentMode() && isPhoneSilenced()) {
1233 return Presence.Status.DND;
1234 } else if (awayWhenScreenLocked() && isScreenLocked()) {
1235 return Presence.Status.AWAY;
1236 } else {
1237 return Presence.Status.ONLINE;
1238 }
1239 }
1240
1241 public boolean isScreenLocked() {
1242 final KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
1243 final PowerManager powerManager = getSystemService(PowerManager.class);
1244 final boolean locked = keyguardManager != null && keyguardManager.isKeyguardLocked();
1245 final boolean interactive;
1246 try {
1247 interactive = powerManager != null && powerManager.isInteractive();
1248 } catch (final Exception e) {
1249 return false;
1250 }
1251 return locked || !interactive;
1252 }
1253
1254 private boolean isPhoneSilenced() {
1255 final NotificationManager notificationManager = getSystemService(NotificationManager.class);
1256 final int filter =
1257 notificationManager == null
1258 ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN
1259 : notificationManager.getCurrentInterruptionFilter();
1260 final boolean notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
1261 final AudioManager audioManager = getSystemService(AudioManager.class);
1262 final int ringerMode =
1263 audioManager == null
1264 ? AudioManager.RINGER_MODE_NORMAL
1265 : audioManager.getRingerMode();
1266 try {
1267 if (treatVibrateAsSilent()) {
1268 return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
1269 } else {
1270 return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
1271 }
1272 } catch (final Throwable throwable) {
1273 Log.d(
1274 Config.LOGTAG,
1275 "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
1276 return notificationDnd;
1277 }
1278 }
1279
1280 private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
1281 Log.d(Config.LOGTAG, "resetting all attempt counts");
1282 for (Account account : accounts) {
1283 if (account.hasErrorStatus() || reallyAll) {
1284 final XmppConnection connection = account.getXmppConnection();
1285 if (connection != null) {
1286 connection.resetAttemptCount(retryImmediately);
1287 }
1288 }
1289 if (account.setShowErrorNotification(true)) {
1290 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1291 }
1292 }
1293 mNotificationService.updateErrorNotification();
1294 }
1295
1296 private void dismissErrorNotifications() {
1297 for (final Account account : this.accounts) {
1298 if (account.hasErrorStatus()) {
1299 Log.d(
1300 Config.LOGTAG,
1301 account.getJid().asBareJid() + ": dismissing error notification");
1302 if (account.setShowErrorNotification(false)) {
1303 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1304 }
1305 }
1306 }
1307 }
1308
1309 private void expireOldMessages() {
1310 expireOldMessages(false);
1311 }
1312
1313 public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
1314 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1315 mDatabaseWriterExecutor.execute(
1316 () -> {
1317 long timestamp = getAutomaticMessageDeletionDate();
1318 if (timestamp > 0) {
1319 databaseBackend.expireOldMessages(timestamp);
1320 synchronized (XmppConnectionService.this.conversations) {
1321 for (Conversation conversation :
1322 XmppConnectionService.this.conversations) {
1323 conversation.expireOldMessages(timestamp);
1324 if (resetHasMessagesLeftOnServer) {
1325 conversation.messagesLoaded.set(true);
1326 conversation.setHasMessagesLeftOnServer(true);
1327 }
1328 }
1329 }
1330 updateConversationUi();
1331 }
1332 });
1333 }
1334
1335 public boolean hasInternetConnection() {
1336 final ConnectivityManager cm =
1337 ContextCompat.getSystemService(this, ConnectivityManager.class);
1338 if (cm == null) {
1339 return true; // if internet connection can not be checked it is probably best to just
1340 // try
1341 }
1342 try {
1343 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
1344 final Network activeNetwork = cm.getActiveNetwork();
1345 final NetworkCapabilities capabilities =
1346 activeNetwork == null ? null : cm.getNetworkCapabilities(activeNetwork);
1347 return capabilities != null
1348 && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1349 } else {
1350 final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
1351 return networkInfo != null
1352 && (networkInfo.isConnected()
1353 || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET);
1354 }
1355 } catch (final RuntimeException e) {
1356 Log.d(Config.LOGTAG, "unable to check for internet connection", e);
1357 return true; // if internet connection can not be checked it is probably best to just
1358 // try
1359 }
1360 }
1361
1362 @SuppressLint("TrulyRandom")
1363 @Override
1364 public void onCreate() {
1365 LibIdnXmppStringprep.setup();
1366 if (Compatibility.runsTwentySix()) {
1367 mNotificationService.initializeChannels();
1368 }
1369 mChannelDiscoveryService.initializeMuclumbusService();
1370 mForceDuringOnCreate.set(Compatibility.runsAndTargetsTwentySix(this));
1371 toggleForegroundService();
1372 this.destroyed = false;
1373 OmemoSetting.load(this);
1374 try {
1375 Security.insertProviderAt(Conscrypt.newProvider(), 1);
1376 } catch (Throwable throwable) {
1377 Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
1378 }
1379 updateMemorizingTrustManager();
1380 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
1381 final int cacheSize = maxMemory / 8;
1382 this.mBitmapCache =
1383 new LruCache<String, Bitmap>(cacheSize) {
1384 @Override
1385 protected int sizeOf(final String key, final Bitmap bitmap) {
1386 return bitmap.getByteCount() / 1024;
1387 }
1388 };
1389 if (mLastActivity == 0) {
1390 mLastActivity =
1391 getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
1392 }
1393
1394 Log.d(Config.LOGTAG, "initializing database...");
1395 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
1396 Log.d(Config.LOGTAG, "restoring accounts...");
1397 this.accounts = databaseBackend.getAccounts();
1398 final SharedPreferences.Editor editor = getPreferences().edit();
1399 final boolean hasEnabledAccounts = hasEnabledAccounts();
1400 editor.putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
1401 editor.apply();
1402 toggleSetProfilePictureActivity(hasEnabledAccounts);
1403 reconfigurePushDistributor();
1404
1405 if (CallIntegration.hasSystemFeature(this)) {
1406 CallIntegrationConnectionService.togglePhoneAccountsAsync(this, this.accounts);
1407 }
1408
1409 restoreFromDatabase();
1410
1411 if (QuickConversationsService.isContactListIntegration(this)
1412 && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
1413 == PackageManager.PERMISSION_GRANTED) {
1414 startContactObserver();
1415 }
1416 FILE_OBSERVER_EXECUTOR.execute(fileBackend::deleteHistoricAvatarPath);
1417 if (Compatibility.hasStoragePermission(this)) {
1418 Log.d(Config.LOGTAG, "starting file observer");
1419 FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::startWatching);
1420 FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1421 }
1422 if (Config.supportOpenPgp()) {
1423 this.pgpServiceConnection =
1424 new OpenPgpServiceConnection(
1425 this,
1426 "org.sufficientlysecure.keychain",
1427 new OpenPgpServiceConnection.OnBound() {
1428 @Override
1429 public void onBound(final IOpenPgpService2 service) {
1430 for (Account account : accounts) {
1431 final PgpDecryptionService pgp =
1432 account.getPgpDecryptionService();
1433 if (pgp != null) {
1434 pgp.continueDecryption(true);
1435 }
1436 }
1437 }
1438
1439 @Override
1440 public void onError(final Exception exception) {
1441 Log.e(
1442 Config.LOGTAG,
1443 "could not bind to OpenKeyChain",
1444 exception);
1445 }
1446 });
1447 this.pgpServiceConnection.bindToService();
1448 }
1449
1450 final PowerManager powerManager = getSystemService(PowerManager.class);
1451 if (powerManager != null) {
1452 this.wakeLock =
1453 powerManager.newWakeLock(
1454 PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1455 }
1456
1457 toggleForegroundService();
1458 updateUnreadCountBadge();
1459 toggleScreenEventReceiver();
1460 final IntentFilter systemBroadcastFilter = new IntentFilter();
1461 scheduleNextIdlePing();
1462 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1463 systemBroadcastFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1464 }
1465 systemBroadcastFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1466 ContextCompat.registerReceiver(
1467 this,
1468 this.mInternalEventReceiver,
1469 systemBroadcastFilter,
1470 ContextCompat.RECEIVER_NOT_EXPORTED);
1471 final IntentFilter exportedBroadcastFilter = new IntentFilter();
1472 exportedBroadcastFilter.addAction(TorServiceUtils.ACTION_STATUS);
1473 ContextCompat.registerReceiver(
1474 this,
1475 this.mInternalRestrictedEventReceiver,
1476 exportedBroadcastFilter,
1477 ContextCompat.RECEIVER_EXPORTED);
1478 mForceDuringOnCreate.set(false);
1479 toggleForegroundService();
1480 internalPingExecutor.scheduleWithFixedDelay(
1481 this::manageAccountConnectionStatesInternal, 10, 10, TimeUnit.SECONDS);
1482 final SharedPreferences sharedPreferences =
1483 androidx.preference.PreferenceManager.getDefaultSharedPreferences(this);
1484 sharedPreferences.registerOnSharedPreferenceChangeListener(
1485 new SharedPreferences.OnSharedPreferenceChangeListener() {
1486 @Override
1487 public void onSharedPreferenceChanged(
1488 SharedPreferences sharedPreferences, @Nullable String key) {
1489 Log.d(Config.LOGTAG, "preference '" + key + "' has changed");
1490 if (AppSettings.KEEP_FOREGROUND_SERVICE.equals(key)) {
1491 toggleForegroundService();
1492 }
1493 }
1494 });
1495 }
1496
1497 private void checkForDeletedFiles() {
1498 if (destroyed) {
1499 Log.d(
1500 Config.LOGTAG,
1501 "Do not check for deleted files because service has been destroyed");
1502 return;
1503 }
1504 final long start = SystemClock.elapsedRealtime();
1505 final List<DatabaseBackend.FilePathInfo> relativeFilePaths =
1506 databaseBackend.getFilePathInfo();
1507 final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1508 for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1509 if (destroyed) {
1510 Log.d(
1511 Config.LOGTAG,
1512 "Stop checking for deleted files because service has been destroyed");
1513 return;
1514 }
1515 final File file = fileBackend.getFileForPath(filePath.path);
1516 if (filePath.setDeleted(!file.exists())) {
1517 changed.add(filePath);
1518 }
1519 }
1520 final long duration = SystemClock.elapsedRealtime() - start;
1521 Log.d(
1522 Config.LOGTAG,
1523 "found "
1524 + changed.size()
1525 + " changed files on start up. total="
1526 + relativeFilePaths.size()
1527 + ". ("
1528 + duration
1529 + "ms)");
1530 if (changed.size() > 0) {
1531 databaseBackend.markFilesAsChanged(changed);
1532 markChangedFiles(changed);
1533 }
1534 }
1535
1536 public void startContactObserver() {
1537 getContentResolver()
1538 .registerContentObserver(
1539 ContactsContract.Contacts.CONTENT_URI,
1540 true,
1541 new ContentObserver(null) {
1542 @Override
1543 public void onChange(boolean selfChange) {
1544 super.onChange(selfChange);
1545 if (restoredFromDatabaseLatch.getCount() == 0) {
1546 loadPhoneContacts();
1547 }
1548 }
1549 });
1550 }
1551
1552 @Override
1553 public void onTrimMemory(int level) {
1554 super.onTrimMemory(level);
1555 if (level >= TRIM_MEMORY_COMPLETE) {
1556 Log.d(Config.LOGTAG, "clear cache due to low memory");
1557 getBitmapCache().evictAll();
1558 }
1559 }
1560
1561 @Override
1562 public void onDestroy() {
1563 try {
1564 unregisterReceiver(this.mInternalEventReceiver);
1565 unregisterReceiver(this.mInternalRestrictedEventReceiver);
1566 unregisterReceiver(this.mInternalScreenEventReceiver);
1567 } catch (final IllegalArgumentException e) {
1568 // ignored
1569 }
1570 destroyed = false;
1571 fileObserver.stopWatching();
1572 internalPingExecutor.shutdown();
1573 super.onDestroy();
1574 }
1575
1576 public void restartFileObserver() {
1577 Log.d(Config.LOGTAG, "restarting file observer");
1578 FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::restartWatching);
1579 FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1580 }
1581
1582 public void toggleScreenEventReceiver() {
1583 if (awayWhenScreenLocked() && !manuallyChangePresence()) {
1584 final IntentFilter filter = new IntentFilter();
1585 filter.addAction(Intent.ACTION_SCREEN_ON);
1586 filter.addAction(Intent.ACTION_SCREEN_OFF);
1587 filter.addAction(Intent.ACTION_USER_PRESENT);
1588 registerReceiver(this.mInternalScreenEventReceiver, filter);
1589 } else {
1590 try {
1591 unregisterReceiver(this.mInternalScreenEventReceiver);
1592 } catch (IllegalArgumentException e) {
1593 // ignored
1594 }
1595 }
1596 }
1597
1598 public void toggleForegroundService() {
1599 toggleForegroundService(false);
1600 }
1601
1602 public void setOngoingCall(
1603 AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
1604 ongoingCall.set(new OngoingCall(id, media, reconnecting));
1605 toggleForegroundService(false);
1606 }
1607
1608 public void removeOngoingCall() {
1609 ongoingCall.set(null);
1610 toggleForegroundService(false);
1611 }
1612
1613 private void toggleForegroundService(final boolean force) {
1614 final boolean status;
1615 final OngoingCall ongoing = ongoingCall.get();
1616 final boolean ongoingVideoTranscoding = mOngoingVideoTranscoding.get();
1617 final int id;
1618 if (force
1619 || mForceDuringOnCreate.get()
1620 || ongoingVideoTranscoding
1621 || ongoing != null
1622 || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1623 final Notification notification;
1624 if (ongoing != null) {
1625 notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1626 id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1627 startForegroundOrCatch(id, notification, true);
1628 } else if (ongoingVideoTranscoding) {
1629 notification = this.mNotificationService.getIndeterminateVideoTranscoding();
1630 id = NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID;
1631 startForegroundOrCatch(id, notification, false);
1632 } else {
1633 notification = this.mNotificationService.createForegroundNotification();
1634 id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1635 startForegroundOrCatch(id, notification, false);
1636 }
1637 mNotificationService.notify(id, notification);
1638 status = true;
1639 } else {
1640 id = 0;
1641 stopForeground(true);
1642 status = false;
1643 }
1644
1645 for (final int toBeRemoved :
1646 Collections2.filter(
1647 Arrays.asList(
1648 NotificationService.FOREGROUND_NOTIFICATION_ID,
1649 NotificationService.ONGOING_CALL_NOTIFICATION_ID,
1650 NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID),
1651 i -> i != id)) {
1652 mNotificationService.cancel(toBeRemoved);
1653 }
1654 Log.d(
1655 Config.LOGTAG,
1656 "ForegroundService: " + (status ? "on" : "off") + ", notification: " + id);
1657 }
1658
1659 private void startForegroundOrCatch(
1660 final int id, final Notification notification, final boolean requireMicrophone) {
1661 try {
1662 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
1663 final int foregroundServiceType;
1664 if (requireMicrophone
1665 && ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1666 == PackageManager.PERMISSION_GRANTED) {
1667 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1668 Log.d(Config.LOGTAG, "defaulting to microphone foreground service type");
1669 } else if (getSystemService(PowerManager.class)
1670 .isIgnoringBatteryOptimizations(getPackageName())) {
1671 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED;
1672 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1673 == PackageManager.PERMISSION_GRANTED) {
1674 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1675 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
1676 == PackageManager.PERMISSION_GRANTED) {
1677 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;
1678 } else {
1679 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
1680 Log.w(Config.LOGTAG, "falling back to special use foreground service type");
1681 }
1682 startForeground(id, notification, foregroundServiceType);
1683 } else {
1684 startForeground(id, notification);
1685 }
1686 } catch (final IllegalStateException | SecurityException e) {
1687 Log.e(Config.LOGTAG, "Could not start foreground service", e);
1688 }
1689 }
1690
1691 public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1692 return !mOngoingVideoTranscoding.get()
1693 && ongoingCall.get() == null
1694 && Compatibility.keepForegroundService(this)
1695 && hasEnabledAccounts();
1696 }
1697
1698 @Override
1699 public void onTaskRemoved(final Intent rootIntent) {
1700 super.onTaskRemoved(rootIntent);
1701 if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts())
1702 || mOngoingVideoTranscoding.get()
1703 || ongoingCall.get() != null) {
1704 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1705 } else {
1706 this.logoutAndSave(false);
1707 }
1708 }
1709
1710 private void logoutAndSave(boolean stop) {
1711 int activeAccounts = 0;
1712 for (final Account account : accounts) {
1713 if (account.isConnectionEnabled()) {
1714 databaseBackend.writeRoster(account.getRoster());
1715 activeAccounts++;
1716 }
1717 if (account.getXmppConnection() != null) {
1718 new Thread(() -> disconnect(account, false)).start();
1719 }
1720 }
1721 if (stop || activeAccounts == 0) {
1722 Log.d(Config.LOGTAG, "good bye");
1723 stopSelf();
1724 }
1725 }
1726
1727 private void schedulePostConnectivityChange() {
1728 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1729 if (alarmManager == null) {
1730 return;
1731 }
1732 final long triggerAtMillis =
1733 SystemClock.elapsedRealtime()
1734 + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1735 final Intent intent = new Intent(this, SystemEventReceiver.class);
1736 intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1737 try {
1738 final PendingIntent pendingIntent =
1739 PendingIntent.getBroadcast(
1740 this,
1741 1,
1742 intent,
1743 s()
1744 ? PendingIntent.FLAG_IMMUTABLE
1745 | PendingIntent.FLAG_UPDATE_CURRENT
1746 : PendingIntent.FLAG_UPDATE_CURRENT);
1747 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1748 alarmManager.setAndAllowWhileIdle(
1749 AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1750 } else {
1751 alarmManager.set(
1752 AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1753 }
1754 } catch (RuntimeException e) {
1755 Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1756 }
1757 }
1758
1759 public void scheduleWakeUpCall(final int seconds, final int requestCode) {
1760 scheduleWakeUpCall((seconds < 0 ? 1 : seconds + 1) * 1000L, requestCode);
1761 }
1762
1763 public void scheduleWakeUpCall(final long milliSeconds, final int requestCode) {
1764 final var timeToWake = SystemClock.elapsedRealtime() + milliSeconds;
1765 final var alarmManager = getSystemService(AlarmManager.class);
1766 final Intent intent = new Intent(this, SystemEventReceiver.class);
1767 intent.setAction(ACTION_PING);
1768 try {
1769 final PendingIntent pendingIntent =
1770 PendingIntent.getBroadcast(
1771 this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1772 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1773 } catch (final RuntimeException e) {
1774 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1775 }
1776 }
1777
1778 private void scheduleNextIdlePing() {
1779 final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1780 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1781 if (alarmManager == null) {
1782 return;
1783 }
1784 final Intent intent = new Intent(this, SystemEventReceiver.class);
1785 intent.setAction(ACTION_IDLE_PING);
1786 try {
1787 final PendingIntent pendingIntent =
1788 PendingIntent.getBroadcast(
1789 this,
1790 0,
1791 intent,
1792 s()
1793 ? PendingIntent.FLAG_IMMUTABLE
1794 | PendingIntent.FLAG_UPDATE_CURRENT
1795 : PendingIntent.FLAG_UPDATE_CURRENT);
1796 alarmManager.setAndAllowWhileIdle(
1797 AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1798 } catch (RuntimeException e) {
1799 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1800 }
1801 }
1802
1803 public XmppConnection createConnection(final Account account) {
1804 final XmppConnection connection = new XmppConnection(account, this);
1805 connection.setOnStatusChangedListener(this.statusListener);
1806 connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1807 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1808 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1809 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1810 AxolotlService axolotlService = account.getAxolotlService();
1811 if (axolotlService != null) {
1812 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1813 }
1814 return connection;
1815 }
1816
1817 public void sendChatState(Conversation conversation) {
1818 if (sendChatStates()) {
1819 final var packet = mMessageGenerator.generateChatState(conversation);
1820 sendMessagePacket(conversation.getAccount(), packet);
1821 }
1822 }
1823
1824 private void sendFileMessage(
1825 final Message message, final boolean delay, final boolean forceP2P) {
1826 final var account = message.getConversation().getAccount();
1827 Log.d(
1828 Config.LOGTAG,
1829 account.getJid().asBareJid() + ": send file message. forceP2P=" + forceP2P);
1830 if ((account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1831 || message.getConversation().getMode() == Conversation.MODE_MULTI)
1832 && !forceP2P) {
1833 mHttpConnectionManager.createNewUploadConnection(message, delay);
1834 } else {
1835 mJingleConnectionManager.startJingleFileTransfer(message);
1836 }
1837 }
1838
1839 public void sendMessage(final Message message) {
1840 sendMessage(message, false, false, false);
1841 }
1842
1843 private void sendMessage(
1844 final Message message,
1845 final boolean resend,
1846 final boolean delay,
1847 final boolean forceP2P) {
1848 final Account account = message.getConversation().getAccount();
1849 if (account.setShowErrorNotification(true)) {
1850 databaseBackend.updateAccount(account);
1851 mNotificationService.updateErrorNotification();
1852 }
1853 final Conversation conversation = (Conversation) message.getConversation();
1854 account.deactivateGracePeriod();
1855
1856 if (QuickConversationsService.isQuicksy()
1857 && conversation.getMode() == Conversation.MODE_SINGLE) {
1858 final Contact contact = conversation.getContact();
1859 if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1860 Log.d(
1861 Config.LOGTAG,
1862 account.getJid().asBareJid()
1863 + ": adding "
1864 + contact.getJid()
1865 + " on sending message");
1866 createContact(contact, true);
1867 }
1868 }
1869
1870 im.conversations.android.xmpp.model.stanza.Message packet = null;
1871 final boolean addToConversation = !message.edited();
1872 boolean saveInDb = addToConversation;
1873 message.setStatus(Message.STATUS_WAITING);
1874
1875 if (message.getEncryption() != Message.ENCRYPTION_NONE
1876 && conversation.getMode() == Conversation.MODE_MULTI
1877 && conversation.isPrivateAndNonAnonymous()) {
1878 if (conversation.setAttribute(
1879 Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1880 databaseBackend.updateConversation(conversation);
1881 }
1882 }
1883
1884 final boolean inProgressJoin = isJoinInProgress(conversation);
1885
1886 if (account.isOnlineAndConnected() && !inProgressJoin) {
1887 switch (message.getEncryption()) {
1888 case Message.ENCRYPTION_NONE:
1889 if (message.needsUploading()) {
1890 if (account.httpUploadAvailable(
1891 fileBackend.getFile(message, false).getSize())
1892 || conversation.getMode() == Conversation.MODE_MULTI
1893 || message.fixCounterpart()) {
1894 this.sendFileMessage(message, delay, forceP2P);
1895 } else {
1896 break;
1897 }
1898 } else {
1899 packet = mMessageGenerator.generateChat(message);
1900 }
1901 break;
1902 case Message.ENCRYPTION_PGP:
1903 case Message.ENCRYPTION_DECRYPTED:
1904 if (message.needsUploading()) {
1905 if (account.httpUploadAvailable(
1906 fileBackend.getFile(message, false).getSize())
1907 || conversation.getMode() == Conversation.MODE_MULTI
1908 || message.fixCounterpart()) {
1909 this.sendFileMessage(message, delay, forceP2P);
1910 } else {
1911 break;
1912 }
1913 } else {
1914 packet = mMessageGenerator.generatePgpChat(message);
1915 }
1916 break;
1917 case Message.ENCRYPTION_AXOLOTL:
1918 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1919 if (message.needsUploading()) {
1920 if (account.httpUploadAvailable(
1921 fileBackend.getFile(message, false).getSize())
1922 || conversation.getMode() == Conversation.MODE_MULTI
1923 || message.fixCounterpart()) {
1924 this.sendFileMessage(message, delay, forceP2P);
1925 } else {
1926 break;
1927 }
1928 } else {
1929 XmppAxolotlMessage axolotlMessage =
1930 account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1931 if (axolotlMessage == null) {
1932 account.getAxolotlService().preparePayloadMessage(message, delay);
1933 } else {
1934 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1935 }
1936 }
1937 break;
1938 }
1939 if (packet != null) {
1940 if (account.getXmppConnection().getFeatures().sm()
1941 || (conversation.getMode() == Conversation.MODE_MULTI
1942 && message.getCounterpart().isBareJid())) {
1943 message.setStatus(Message.STATUS_UNSEND);
1944 } else {
1945 message.setStatus(Message.STATUS_SEND);
1946 }
1947 }
1948 } else {
1949 switch (message.getEncryption()) {
1950 case Message.ENCRYPTION_DECRYPTED:
1951 if (!message.needsUploading()) {
1952 String pgpBody = message.getEncryptedBody();
1953 String decryptedBody = message.getBody();
1954 message.setBody(pgpBody); // TODO might throw NPE
1955 message.setEncryption(Message.ENCRYPTION_PGP);
1956 if (message.edited()) {
1957 message.setBody(decryptedBody);
1958 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1959 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1960 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1961 }
1962 updateConversationUi();
1963 return;
1964 } else {
1965 databaseBackend.createMessage(message);
1966 saveInDb = false;
1967 message.setBody(decryptedBody);
1968 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1969 }
1970 }
1971 break;
1972 case Message.ENCRYPTION_AXOLOTL:
1973 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1974 break;
1975 }
1976 }
1977
1978 boolean mucMessage =
1979 conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1980 if (mucMessage) {
1981 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1982 }
1983
1984 if (resend) {
1985 if (packet != null && addToConversation) {
1986 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1987 markMessage(message, Message.STATUS_UNSEND);
1988 } else {
1989 markMessage(message, Message.STATUS_SEND);
1990 }
1991 }
1992 } else {
1993 if (addToConversation) {
1994 conversation.add(message);
1995 }
1996 if (saveInDb) {
1997 databaseBackend.createMessage(message);
1998 } else if (message.edited()) {
1999 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
2000 Log.e(Config.LOGTAG, "error updated message in DB after edit");
2001 }
2002 }
2003 updateConversationUi();
2004 }
2005 if (packet != null) {
2006 if (delay) {
2007 mMessageGenerator.addDelay(packet, message.getTimeSent());
2008 }
2009 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
2010 if (this.sendChatStates()) {
2011 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
2012 }
2013 }
2014 sendMessagePacket(account, packet);
2015 }
2016 }
2017
2018 private boolean isJoinInProgress(final Conversation conversation) {
2019 final Account account = conversation.getAccount();
2020 synchronized (account.inProgressConferenceJoins) {
2021 if (conversation.getMode() == Conversational.MODE_MULTI) {
2022 final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
2023 final boolean pending = account.pendingConferenceJoins.contains(conversation);
2024 final boolean inProgressJoin = inProgress || pending;
2025 if (inProgressJoin) {
2026 Log.d(
2027 Config.LOGTAG,
2028 account.getJid().asBareJid()
2029 + ": holding back message to group. inProgress="
2030 + inProgress
2031 + ", pending="
2032 + pending);
2033 }
2034 return inProgressJoin;
2035 } else {
2036 return false;
2037 }
2038 }
2039 }
2040
2041 private void sendUnsentMessages(final Conversation conversation) {
2042 conversation.findWaitingMessages(message -> resendMessage(message, true));
2043 }
2044
2045 public void resendMessage(final Message message, final boolean delay) {
2046 sendMessage(message, true, delay, false);
2047 }
2048
2049 public void requestEasyOnboardingInvite(
2050 final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
2051 final XmppConnection connection = account.getXmppConnection();
2052 final Jid jid =
2053 connection == null
2054 ? null
2055 : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
2056 if (jid == null) {
2057 callback.inviteRequestFailed(
2058 getString(R.string.server_does_not_support_easy_onboarding_invites));
2059 return;
2060 }
2061 final Iq request = new Iq(Iq.Type.SET);
2062 request.setTo(jid);
2063 final Element command = request.addChild("command", Namespace.COMMANDS);
2064 command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
2065 command.setAttribute("action", "execute");
2066 sendIqPacket(
2067 account,
2068 request,
2069 (response) -> {
2070 if (response.getType() == Iq.Type.RESULT) {
2071 final Element resultCommand =
2072 response.findChild("command", Namespace.COMMANDS);
2073 final Element x =
2074 resultCommand == null
2075 ? null
2076 : resultCommand.findChild("x", Namespace.DATA);
2077 if (x != null) {
2078 final Data data = Data.parse(x);
2079 final String uri = data.getValue("uri");
2080 final String landingUrl = data.getValue("landing-url");
2081 if (uri != null) {
2082 final EasyOnboardingInvite invite =
2083 new EasyOnboardingInvite(
2084 jid.getDomain().toString(), uri, landingUrl);
2085 callback.inviteRequested(invite);
2086 return;
2087 }
2088 }
2089 callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
2090 Log.d(Config.LOGTAG, response.toString());
2091 } else if (response.getType() == Iq.Type.ERROR) {
2092 callback.inviteRequestFailed(IqParser.errorMessage(response));
2093 } else {
2094 callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
2095 }
2096 });
2097 }
2098
2099 public void fetchBookmarks(final Account account) {
2100 final Iq iqPacket = new Iq(Iq.Type.GET);
2101 iqPacket.addExtension(new PrivateStorage()).addExtension(new Storage());
2102 final Consumer<Iq> callback =
2103 (response) -> {
2104 if (response.getType() == Iq.Type.RESULT) {
2105 final var privateStorage = response.getExtension(PrivateStorage.class);
2106 if (privateStorage == null) {
2107 return;
2108 }
2109 final var bookmarkStorage = privateStorage.getExtension(Storage.class);
2110 Map<Jid, Bookmark> bookmarks =
2111 Bookmark.parseFromStorage(bookmarkStorage, account);
2112 processBookmarksInitial(account, bookmarks, false);
2113 } else {
2114 Log.d(
2115 Config.LOGTAG,
2116 account.getJid().asBareJid() + ": could not fetch bookmarks");
2117 }
2118 };
2119 sendIqPacket(account, iqPacket, callback);
2120 }
2121
2122 public void fetchBookmarks2(final Account account) {
2123 final Iq retrieve = mIqGenerator.retrieveBookmarks();
2124 sendIqPacket(
2125 account,
2126 retrieve,
2127 (response) -> {
2128 if (response.getType() == Iq.Type.RESULT) {
2129 final var pubsub = response.getExtension(PubSub.class);
2130 final Map<Jid, Bookmark> bookmarks =
2131 Bookmark.parseFromPubSub(pubsub, account);
2132 processBookmarksInitial(account, bookmarks, true);
2133 }
2134 });
2135 }
2136
2137 public void fetchMessageDisplayedSynchronization(final Account account) {
2138 Log.d(Config.LOGTAG, account.getJid() + ": retrieve mds");
2139 final var retrieve = mIqGenerator.retrieveMds();
2140 sendIqPacket(
2141 account,
2142 retrieve,
2143 (response) -> {
2144 if (response.getType() != Iq.Type.RESULT) {
2145 return;
2146 }
2147 final var pubsub = response.getExtension(PubSub.class);
2148 if (pubsub == null) {
2149 return;
2150 }
2151 final var items = pubsub.getItems();
2152 if (items == null) {
2153 return;
2154 }
2155 if (Namespace.MDS_DISPLAYED.equals(items.getNode())) {
2156 for (final var item :
2157 items.getItemMap(
2158 im.conversations.android.xmpp.model.mds.Displayed
2159 .class)
2160 .entrySet()) {
2161 processMdsItem(account, item);
2162 }
2163 }
2164 });
2165 }
2166
2167 public void processMdsItem(final Account account, final Map.Entry<String, Displayed> item) {
2168 final Jid jid = Jid.Invalid.getNullForInvalid(Jid.ofOrInvalid(item.getKey()));
2169 if (jid == null) {
2170 return;
2171 }
2172 final var displayed = item.getValue();
2173 final var stanzaId = displayed.getStanzaId();
2174 final String id = stanzaId == null ? null : stanzaId.getId();
2175 final Conversation conversation = find(account, jid);
2176 if (id != null && conversation != null) {
2177 conversation.setDisplayState(id);
2178 markReadUpToStanzaId(conversation, id);
2179 }
2180 }
2181
2182 public void markReadUpToStanzaId(final Conversation conversation, final String stanzaId) {
2183 final Message message = conversation.findMessageWithServerMsgId(stanzaId);
2184 if (message == null) { // do we want to check if isRead?
2185 return;
2186 }
2187 markReadUpTo(conversation, message);
2188 }
2189
2190 public void markReadUpTo(final Conversation conversation, final Message message) {
2191 final boolean isDismissNotification = isDismissNotification(message);
2192 final var uuid = message.getUuid();
2193 Log.d(
2194 Config.LOGTAG,
2195 conversation.getAccount().getJid().asBareJid()
2196 + ": mark "
2197 + conversation.getJid().asBareJid()
2198 + " as read up to "
2199 + uuid);
2200 markRead(conversation, uuid, isDismissNotification);
2201 }
2202
2203 private static boolean isDismissNotification(final Message message) {
2204 Message next = message.next();
2205 while (next != null) {
2206 if (message.getStatus() == Message.STATUS_RECEIVED) {
2207 return false;
2208 }
2209 next = next.next();
2210 }
2211 return true;
2212 }
2213
2214 public void processBookmarksInitial(
2215 final Account account, final Map<Jid, Bookmark> bookmarks, final boolean pep) {
2216 final Set<Jid> previousBookmarks = account.getBookmarkedJids();
2217 for (final Bookmark bookmark : bookmarks.values()) {
2218 previousBookmarks.remove(bookmark.getJid().asBareJid());
2219 processModifiedBookmark(bookmark, pep);
2220 }
2221 if (pep) {
2222 processDeletedBookmarks(account, previousBookmarks);
2223 }
2224 account.setBookmarks(bookmarks);
2225 }
2226
2227 public void processDeletedBookmarks(final Account account, final Collection<Jid> bookmarks) {
2228 Log.d(
2229 Config.LOGTAG,
2230 account.getJid().asBareJid()
2231 + ": "
2232 + bookmarks.size()
2233 + " bookmarks have been removed");
2234 for (final Jid bookmark : bookmarks) {
2235 processDeletedBookmark(account, bookmark);
2236 }
2237 }
2238
2239 public void processDeletedBookmark(final Account account, final Jid jid) {
2240 final Conversation conversation = find(account, jid);
2241 if (conversation == null) {
2242 return;
2243 }
2244 Log.d(
2245 Config.LOGTAG,
2246 account.getJid().asBareJid() + ": archiving MUC " + jid + " after PEP update");
2247 archiveConversation(conversation, false);
2248 }
2249
2250 private void processModifiedBookmark(final Bookmark bookmark, final boolean pep) {
2251 final Account account = bookmark.getAccount();
2252 Conversation conversation = find(bookmark);
2253 if (conversation != null) {
2254 if (conversation.getMode() != Conversation.MODE_MULTI) {
2255 return;
2256 }
2257 bookmark.setConversation(conversation);
2258 if (pep && !bookmark.autojoin()) {
2259 Log.d(
2260 Config.LOGTAG,
2261 account.getJid().asBareJid()
2262 + ": archiving conference ("
2263 + conversation.getJid()
2264 + ") after receiving pep");
2265 archiveConversation(conversation, false);
2266 } else {
2267 final MucOptions mucOptions = conversation.getMucOptions();
2268 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
2269 final String current = mucOptions.getActualNick();
2270 final String proposed = mucOptions.getProposedNickPure();
2271 if (current != null && !current.equals(proposed)) {
2272 Log.d(
2273 Config.LOGTAG,
2274 account.getJid().asBareJid()
2275 + ": proposed nick changed after bookmark push "
2276 + current
2277 + "->"
2278 + proposed);
2279 joinMuc(conversation);
2280 }
2281 } else {
2282 checkMucRequiresRename(conversation);
2283 }
2284 }
2285 } else if (bookmark.autojoin()) {
2286 conversation =
2287 findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
2288 bookmark.setConversation(conversation);
2289 }
2290 }
2291
2292 public void processModifiedBookmark(final Bookmark bookmark) {
2293 processModifiedBookmark(bookmark, true);
2294 }
2295
2296 public void ensureBookmarkIsAutoJoin(final Conversation conversation) {
2297 final var account = conversation.getAccount();
2298 final var existingBookmark = conversation.getBookmark();
2299 if (existingBookmark == null) {
2300 final var bookmark = new Bookmark(account, conversation.getJid().asBareJid());
2301 bookmark.setAutojoin(true);
2302 createBookmark(account, bookmark);
2303 } else {
2304 if (existingBookmark.autojoin()) {
2305 return;
2306 }
2307 existingBookmark.setAutojoin(true);
2308 createBookmark(account, existingBookmark);
2309 }
2310 }
2311
2312 public void createBookmark(final Account account, final Bookmark bookmark) {
2313 account.putBookmark(bookmark);
2314 final XmppConnection connection = account.getXmppConnection();
2315 if (connection == null) {
2316 Log.d(
2317 Config.LOGTAG,
2318 account.getJid().asBareJid() + ": no connection. ignoring bookmark creation");
2319 } else if (connection.getFeatures().bookmarks2()) {
2320 Log.d(
2321 Config.LOGTAG,
2322 account.getJid().asBareJid() + ": pushing bookmark via Bookmarks 2");
2323 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
2324 pushNodeAndEnforcePublishOptions(
2325 account,
2326 Namespace.BOOKMARKS2,
2327 item,
2328 bookmark.getJid().asBareJid().toString(),
2329 PublishOptions.persistentWhitelistAccessMaxItems());
2330 } else if (connection.getFeatures().bookmarksConversion()) {
2331 pushBookmarksPep(account);
2332 } else {
2333 pushBookmarksPrivateXml(account);
2334 }
2335 }
2336
2337 public void deleteBookmark(final Account account, final Bookmark bookmark) {
2338 account.removeBookmark(bookmark);
2339 final XmppConnection connection = account.getXmppConnection();
2340 if (connection.getFeatures().bookmarks2()) {
2341 final Iq request =
2342 mIqGenerator.deleteItem(
2343 Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toString());
2344 Log.d(
2345 Config.LOGTAG,
2346 account.getJid().asBareJid() + ": removing bookmark via Bookmarks 2");
2347 sendIqPacket(
2348 account,
2349 request,
2350 (response) -> {
2351 if (response.getType() == Iq.Type.ERROR) {
2352 Log.d(
2353 Config.LOGTAG,
2354 account.getJid().asBareJid()
2355 + ": unable to delete bookmark "
2356 + response.getErrorCondition());
2357 }
2358 });
2359 } else if (connection.getFeatures().bookmarksConversion()) {
2360 pushBookmarksPep(account);
2361 } else {
2362 pushBookmarksPrivateXml(account);
2363 }
2364 }
2365
2366 private void pushBookmarksPrivateXml(Account account) {
2367 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
2368 final Iq iqPacket = new Iq(Iq.Type.SET);
2369 Element query = iqPacket.query("jabber:iq:private");
2370 Element storage = query.addChild("storage", "storage:bookmarks");
2371 for (final Bookmark bookmark : account.getBookmarks()) {
2372 storage.addChild(bookmark);
2373 }
2374 sendIqPacket(account, iqPacket, mDefaultIqHandler);
2375 }
2376
2377 private void pushBookmarksPep(Account account) {
2378 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
2379 final Element storage = new Element("storage", "storage:bookmarks");
2380 for (final Bookmark bookmark : account.getBookmarks()) {
2381 storage.addChild(bookmark);
2382 }
2383 pushNodeAndEnforcePublishOptions(
2384 account,
2385 Namespace.BOOKMARKS,
2386 storage,
2387 "current",
2388 PublishOptions.persistentWhitelistAccess());
2389 }
2390
2391 private void pushNodeAndEnforcePublishOptions(
2392 final Account account,
2393 final String node,
2394 final Element element,
2395 final String id,
2396 final Bundle options) {
2397 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2398 }
2399
2400 private void pushNodeAndEnforcePublishOptions(
2401 final Account account,
2402 final String node,
2403 final Element element,
2404 final String id,
2405 final Bundle options,
2406 final boolean retry) {
2407 final Iq packet = mIqGenerator.publishElement(node, element, id, options);
2408 sendIqPacket(
2409 account,
2410 packet,
2411 (response) -> {
2412 if (response.getType() == Iq.Type.RESULT) {
2413 return;
2414 }
2415 if (retry && PublishOptions.preconditionNotMet(response)) {
2416 pushNodeConfiguration(
2417 account,
2418 node,
2419 options,
2420 new OnConfigurationPushed() {
2421 @Override
2422 public void onPushSucceeded() {
2423 pushNodeAndEnforcePublishOptions(
2424 account, node, element, id, options, false);
2425 }
2426
2427 @Override
2428 public void onPushFailed() {
2429 Log.d(
2430 Config.LOGTAG,
2431 account.getJid().asBareJid()
2432 + ": unable to push node configuration ("
2433 + node
2434 + ")");
2435 }
2436 });
2437 } else {
2438 Log.d(
2439 Config.LOGTAG,
2440 account.getJid().asBareJid()
2441 + ": error publishing "
2442 + node
2443 + " (retry="
2444 + retry
2445 + ") "
2446 + response);
2447 }
2448 });
2449 }
2450
2451 private void restoreFromDatabase() {
2452 synchronized (this.conversations) {
2453 final Map<String, Account> accountLookupTable =
2454 ImmutableMap.copyOf(Maps.uniqueIndex(this.accounts, Account::getUuid));
2455 Log.d(Config.LOGTAG, "restoring conversations...");
2456 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2457 this.conversations.addAll(
2458 databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2459 for (Iterator<Conversation> iterator = conversations.listIterator();
2460 iterator.hasNext(); ) {
2461 Conversation conversation = iterator.next();
2462 Account account = accountLookupTable.get(conversation.getAccountUuid());
2463 if (account != null) {
2464 conversation.setAccount(account);
2465 } else {
2466 Log.e(
2467 Config.LOGTAG,
2468 "unable to restore Conversations with " + conversation.getJid());
2469 iterator.remove();
2470 }
2471 }
2472 long diffConversationsRestore =
2473 SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2474 Log.d(
2475 Config.LOGTAG,
2476 "finished restoring conversations in " + diffConversationsRestore + "ms");
2477 Runnable runnable =
2478 () -> {
2479 if (DatabaseBackend.requiresMessageIndexRebuild()) {
2480 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2481 }
2482 final long deletionDate = getAutomaticMessageDeletionDate();
2483 mLastExpiryRun.set(SystemClock.elapsedRealtime());
2484 if (deletionDate > 0) {
2485 Log.d(
2486 Config.LOGTAG,
2487 "deleting messages that are older than "
2488 + AbstractGenerator.getTimestamp(deletionDate));
2489 databaseBackend.expireOldMessages(deletionDate);
2490 }
2491 Log.d(Config.LOGTAG, "restoring roster...");
2492 for (final Account account : accounts) {
2493 databaseBackend.readRoster(account.getRoster());
2494 account.initAccountServices(
2495 XmppConnectionService
2496 .this); // roster needs to be loaded at this stage
2497 }
2498 getBitmapCache().evictAll();
2499 loadPhoneContacts();
2500 Log.d(Config.LOGTAG, "restoring messages...");
2501 final long startMessageRestore = SystemClock.elapsedRealtime();
2502 final Conversation quickLoad = QuickLoader.get(this.conversations);
2503 if (quickLoad != null) {
2504 restoreMessages(quickLoad);
2505 updateConversationUi();
2506 final long diffMessageRestore =
2507 SystemClock.elapsedRealtime() - startMessageRestore;
2508 Log.d(
2509 Config.LOGTAG,
2510 "quickly restored "
2511 + quickLoad.getName()
2512 + " after "
2513 + diffMessageRestore
2514 + "ms");
2515 }
2516 for (Conversation conversation : this.conversations) {
2517 if (quickLoad != conversation) {
2518 restoreMessages(conversation);
2519 }
2520 }
2521 mNotificationService.finishBacklog();
2522 restoredFromDatabaseLatch.countDown();
2523 final long diffMessageRestore =
2524 SystemClock.elapsedRealtime() - startMessageRestore;
2525 Log.d(
2526 Config.LOGTAG,
2527 "finished restoring messages in " + diffMessageRestore + "ms");
2528 updateConversationUi();
2529 };
2530 mDatabaseReaderExecutor.execute(
2531 runnable); // will contain one write command (expiry) but that's fine
2532 }
2533 }
2534
2535 private void restoreMessages(Conversation conversation) {
2536 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2537 conversation.findUnsentTextMessages(
2538 message -> markMessage(message, Message.STATUS_WAITING));
2539 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2540 }
2541
2542 public void loadPhoneContacts() {
2543 mContactMergerExecutor.execute(
2544 () -> {
2545 final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2546 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2547 for (final Account account : accounts) {
2548 final List<Contact> withSystemAccounts =
2549 account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2550 for (final JabberIdContact jidContact : contacts.values()) {
2551 final Contact contact =
2552 account.getRoster().getContact(jidContact.getJid());
2553 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2554 if (needsCacheClean) {
2555 getAvatarService().clear(contact);
2556 }
2557 withSystemAccounts.remove(contact);
2558 }
2559 for (final Contact contact : withSystemAccounts) {
2560 boolean needsCacheClean =
2561 contact.unsetPhoneContact(JabberIdContact.class);
2562 if (needsCacheClean) {
2563 getAvatarService().clear(contact);
2564 }
2565 }
2566 }
2567 Log.d(Config.LOGTAG, "finished merging phone contacts");
2568 mShortcutService.refresh(
2569 mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2570 updateRosterUi();
2571 mQuickConversationsService.considerSync();
2572 });
2573 }
2574
2575 public void syncRoster(final Account account) {
2576 mRosterSyncTaskManager.execute(
2577 account, () -> databaseBackend.writeRoster(account.getRoster()));
2578 }
2579
2580 public List<Conversation> getConversations() {
2581 return this.conversations;
2582 }
2583
2584 private void markFileDeleted(final File file) {
2585 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2586 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2587 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2588 return;
2589 }
2590 }
2591 final boolean isInternalFile = fileBackend.isInternalFile(file);
2592 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2593 Log.d(
2594 Config.LOGTAG,
2595 "deleted file "
2596 + file.getAbsolutePath()
2597 + " internal="
2598 + isInternalFile
2599 + ", database hits="
2600 + uuids.size());
2601 markUuidsAsDeletedFiles(uuids);
2602 }
2603
2604 private void markUuidsAsDeletedFiles(List<String> uuids) {
2605 boolean deleted = false;
2606 for (Conversation conversation : getConversations()) {
2607 deleted |= conversation.markAsDeleted(uuids);
2608 }
2609 for (final String uuid : uuids) {
2610 evictPreview(uuid);
2611 }
2612 if (deleted) {
2613 updateConversationUi();
2614 }
2615 }
2616
2617 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2618 boolean changed = false;
2619 for (Conversation conversation : getConversations()) {
2620 changed |= conversation.markAsChanged(infos);
2621 }
2622 if (changed) {
2623 updateConversationUi();
2624 }
2625 }
2626
2627 public void populateWithOrderedConversations(final List<Conversation> list) {
2628 populateWithOrderedConversations(list, true, true);
2629 }
2630
2631 public void populateWithOrderedConversations(
2632 final List<Conversation> list, final boolean includeNoFileUpload) {
2633 populateWithOrderedConversations(list, includeNoFileUpload, true);
2634 }
2635
2636 public void populateWithOrderedConversations(
2637 final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2638 final List<String> orderedUuids;
2639 if (sort) {
2640 orderedUuids = null;
2641 } else {
2642 orderedUuids = new ArrayList<>();
2643 for (Conversation conversation : list) {
2644 orderedUuids.add(conversation.getUuid());
2645 }
2646 }
2647 list.clear();
2648 if (includeNoFileUpload) {
2649 list.addAll(getConversations());
2650 } else {
2651 for (Conversation conversation : getConversations()) {
2652 if (conversation.getMode() == Conversation.MODE_SINGLE
2653 || (conversation.getAccount().httpUploadAvailable()
2654 && conversation.getMucOptions().participating())) {
2655 list.add(conversation);
2656 }
2657 }
2658 }
2659 try {
2660 if (orderedUuids != null) {
2661 Collections.sort(
2662 list,
2663 (a, b) -> {
2664 final int indexA = orderedUuids.indexOf(a.getUuid());
2665 final int indexB = orderedUuids.indexOf(b.getUuid());
2666 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2667 return a.compareTo(b);
2668 }
2669 return indexA - indexB;
2670 });
2671 } else {
2672 Collections.sort(list);
2673 }
2674 } catch (IllegalArgumentException e) {
2675 // ignore
2676 }
2677 }
2678
2679 public void loadMoreMessages(
2680 final Conversation conversation,
2681 final long timestamp,
2682 final OnMoreMessagesLoaded callback) {
2683 if (XmppConnectionService.this
2684 .getMessageArchiveService()
2685 .queryInProgress(conversation, callback)) {
2686 return;
2687 } else if (timestamp == 0) {
2688 return;
2689 }
2690 Log.d(
2691 Config.LOGTAG,
2692 "load more messages for "
2693 + conversation.getName()
2694 + " prior to "
2695 + MessageGenerator.getTimestamp(timestamp));
2696 final Runnable runnable =
2697 () -> {
2698 final Account account = conversation.getAccount();
2699 List<Message> messages =
2700 databaseBackend.getMessages(conversation, 50, timestamp);
2701 if (messages.size() > 0) {
2702 conversation.addAll(0, messages);
2703 callback.onMoreMessagesLoaded(messages.size(), conversation);
2704 } else if (conversation.hasMessagesLeftOnServer()
2705 && account.isOnlineAndConnected()
2706 && conversation.getLastClearHistory().getTimestamp() == 0) {
2707 final boolean mamAvailable;
2708 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2709 mamAvailable =
2710 account.getXmppConnection().getFeatures().mam()
2711 && !conversation.getContact().isBlocked();
2712 } else {
2713 mamAvailable = conversation.getMucOptions().mamSupport();
2714 }
2715 if (mamAvailable) {
2716 MessageArchiveService.Query query =
2717 getMessageArchiveService()
2718 .query(
2719 conversation,
2720 new MamReference(0),
2721 timestamp,
2722 false);
2723 if (query != null) {
2724 query.setCallback(callback);
2725 callback.informUser(R.string.fetching_history_from_server);
2726 } else {
2727 callback.informUser(R.string.not_fetching_history_retention_period);
2728 }
2729 }
2730 }
2731 };
2732 mDatabaseReaderExecutor.execute(runnable);
2733 }
2734
2735 public List<Account> getAccounts() {
2736 return this.accounts;
2737 }
2738
2739 /**
2740 * This will find all conferences with the contact as member and also the conference that is the
2741 * contact (that 'fake' contact is used to store the avatar)
2742 */
2743 public List<Conversation> findAllConferencesWith(Contact contact) {
2744 final ArrayList<Conversation> results = new ArrayList<>();
2745 for (final Conversation c : conversations) {
2746 if (c.getMode() != Conversation.MODE_MULTI) {
2747 continue;
2748 }
2749 final MucOptions mucOptions = c.getMucOptions();
2750 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid())
2751 || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2752 results.add(c);
2753 }
2754 }
2755 return results;
2756 }
2757
2758 public Conversation find(final Contact contact) {
2759 for (final Conversation conversation : this.conversations) {
2760 if (conversation.getContact() == contact) {
2761 return conversation;
2762 }
2763 }
2764 return null;
2765 }
2766
2767 public Conversation find(
2768 final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2769 if (jid == null) {
2770 return null;
2771 }
2772 for (final Conversation conversation : haystack) {
2773 if ((account == null || conversation.getAccount() == account)
2774 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2775 return conversation;
2776 }
2777 }
2778 return null;
2779 }
2780
2781 public boolean isConversationsListEmpty(final Conversation ignore) {
2782 synchronized (this.conversations) {
2783 final int size = this.conversations.size();
2784 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2785 }
2786 }
2787
2788 public boolean isConversationStillOpen(final Conversation conversation) {
2789 synchronized (this.conversations) {
2790 for (Conversation current : this.conversations) {
2791 if (current == conversation) {
2792 return true;
2793 }
2794 }
2795 }
2796 return false;
2797 }
2798
2799 public Conversation findOrCreateConversation(
2800 Account account, Jid jid, boolean muc, final boolean async) {
2801 return this.findOrCreateConversation(account, jid, muc, false, async);
2802 }
2803
2804 public Conversation findOrCreateConversation(
2805 final Account account,
2806 final Jid jid,
2807 final boolean muc,
2808 final boolean joinAfterCreate,
2809 final boolean async) {
2810 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2811 }
2812
2813 public Conversation findOrCreateConversation(
2814 final Account account,
2815 final Jid jid,
2816 final boolean muc,
2817 final boolean joinAfterCreate,
2818 final MessageArchiveService.Query query,
2819 final boolean async) {
2820 synchronized (this.conversations) {
2821 final var cached = find(account, jid);
2822 if (cached != null) {
2823 return cached;
2824 }
2825 final var existing = databaseBackend.findConversation(account, jid);
2826 final Conversation conversation;
2827 final boolean loadMessagesFromDb;
2828 if (existing != null) {
2829 conversation = existing;
2830 loadMessagesFromDb = restoreFromArchive(conversation, jid, muc);
2831 } else {
2832 String conversationName;
2833 final Contact contact = account.getRoster().getContact(jid);
2834 if (contact != null) {
2835 conversationName = contact.getDisplayName();
2836 } else {
2837 conversationName = jid.getLocal();
2838 }
2839 if (muc) {
2840 conversation =
2841 new Conversation(
2842 conversationName, account, jid, Conversation.MODE_MULTI);
2843 } else {
2844 conversation =
2845 new Conversation(
2846 conversationName,
2847 account,
2848 jid.asBareJid(),
2849 Conversation.MODE_SINGLE);
2850 }
2851 this.databaseBackend.createConversation(conversation);
2852 loadMessagesFromDb = false;
2853 }
2854 if (async) {
2855 mDatabaseReaderExecutor.execute(
2856 () ->
2857 postProcessConversation(
2858 conversation, loadMessagesFromDb, joinAfterCreate, query));
2859 } else {
2860 postProcessConversation(conversation, loadMessagesFromDb, joinAfterCreate, query);
2861 }
2862 this.conversations.add(conversation);
2863 updateConversationUi();
2864 return conversation;
2865 }
2866 }
2867
2868 public Conversation findConversationByUuidReliable(final String uuid) {
2869 final var cached = findConversationByUuid(uuid);
2870 if (cached != null) {
2871 return cached;
2872 }
2873 final var existing = databaseBackend.findConversation(uuid);
2874 if (existing == null) {
2875 return null;
2876 }
2877 Log.d(Config.LOGTAG, "restoring conversation with " + existing.getJid() + " from DB");
2878 final Map<String, Account> accounts =
2879 ImmutableMap.copyOf(Maps.uniqueIndex(this.accounts, Account::getUuid));
2880 final var account = accounts.get(existing.getAccountUuid());
2881 if (account == null) {
2882 Log.d(Config.LOGTAG, "could not find account " + existing.getAccountUuid());
2883 return null;
2884 }
2885 existing.setAccount(account);
2886 final var loadMessagesFromDb = restoreFromArchive(existing);
2887 mDatabaseReaderExecutor.execute(
2888 () ->
2889 postProcessConversation(
2890 existing,
2891 loadMessagesFromDb,
2892 existing.getMode() == Conversational.MODE_MULTI,
2893 null));
2894 this.conversations.add(existing);
2895 if (existing.getMode() == Conversational.MODE_MULTI) {
2896 ensureBookmarkIsAutoJoin(existing);
2897 }
2898 updateConversationUi();
2899 return existing;
2900 }
2901
2902 private boolean restoreFromArchive(
2903 final Conversation conversation, final Jid jid, final boolean muc) {
2904 if (muc) {
2905 conversation.setMode(Conversation.MODE_MULTI);
2906 conversation.setContactJid(jid);
2907 } else {
2908 conversation.setMode(Conversation.MODE_SINGLE);
2909 conversation.setContactJid(jid.asBareJid());
2910 }
2911 return restoreFromArchive(conversation);
2912 }
2913
2914 private boolean restoreFromArchive(final Conversation conversation) {
2915 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2916 databaseBackend.updateConversation(conversation);
2917 return conversation.messagesLoaded.compareAndSet(true, false);
2918 }
2919
2920 private void postProcessConversation(
2921 final Conversation c,
2922 final boolean loadMessagesFromDb,
2923 final boolean joinAfterCreate,
2924 final MessageArchiveService.Query query) {
2925 final var singleMode = c.getMode() == Conversational.MODE_SINGLE;
2926 final var account = c.getAccount();
2927 if (loadMessagesFromDb) {
2928 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2929 updateConversationUi();
2930 c.messagesLoaded.set(true);
2931 }
2932 if (account.getXmppConnection() != null
2933 && !c.getContact().isBlocked()
2934 && account.getXmppConnection().getFeatures().mam()
2935 && singleMode) {
2936 if (query == null) {
2937 mMessageArchiveService.query(c);
2938 } else {
2939 if (query.getConversation() == null) {
2940 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2941 }
2942 }
2943 }
2944 if (joinAfterCreate) {
2945 joinMuc(c);
2946 }
2947 }
2948
2949 public void archiveConversation(Conversation conversation) {
2950 archiveConversation(conversation, true);
2951 }
2952
2953 private void archiveConversation(
2954 Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2955 getNotificationService().clear(conversation);
2956 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2957 conversation.setNextMessage(null);
2958 synchronized (this.conversations) {
2959 getMessageArchiveService().kill(conversation);
2960 if (conversation.getMode() == Conversation.MODE_MULTI) {
2961 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2962 final Bookmark bookmark = conversation.getBookmark();
2963 if (maySynchronizeWithBookmarks && bookmark != null) {
2964 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2965 Account account = bookmark.getAccount();
2966 bookmark.setConversation(null);
2967 deleteBookmark(account, bookmark);
2968 } else if (bookmark.autojoin()) {
2969 bookmark.setAutojoin(false);
2970 createBookmark(bookmark.getAccount(), bookmark);
2971 }
2972 }
2973 }
2974 leaveMuc(conversation);
2975 } else {
2976 if (conversation
2977 .getContact()
2978 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2979 stopPresenceUpdatesTo(conversation.getContact());
2980 }
2981 }
2982 updateConversation(conversation);
2983 this.conversations.remove(conversation);
2984 updateConversationUi();
2985 }
2986 }
2987
2988 public void stopPresenceUpdatesTo(Contact contact) {
2989 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2990 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2991 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2992 }
2993
2994 public void createAccount(final Account account) {
2995 account.initAccountServices(this);
2996 databaseBackend.createAccount(account);
2997 if (CallIntegration.hasSystemFeature(this)) {
2998 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2999 }
3000 this.accounts.add(account);
3001 this.reconnectAccountInBackground(account);
3002 updateAccountUi();
3003 syncEnabledAccountSetting();
3004 toggleForegroundService();
3005 }
3006
3007 private void syncEnabledAccountSetting() {
3008 final boolean hasEnabledAccounts = hasEnabledAccounts();
3009 getPreferences()
3010 .edit()
3011 .putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts)
3012 .apply();
3013 toggleSetProfilePictureActivity(hasEnabledAccounts);
3014 }
3015
3016 private void toggleSetProfilePictureActivity(final boolean enabled) {
3017 try {
3018 final ComponentName name =
3019 new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
3020 final int targetState =
3021 enabled
3022 ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
3023 : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
3024 getPackageManager()
3025 .setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
3026 } catch (IllegalStateException e) {
3027 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
3028 }
3029 }
3030
3031 public boolean reconfigurePushDistributor() {
3032 return this.unifiedPushBroker.reconfigurePushDistributor();
3033 }
3034
3035 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(
3036 final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
3037 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
3038 }
3039
3040 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
3041 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
3042 }
3043
3044 public UnifiedPushBroker getUnifiedPushBroker() {
3045 return this.unifiedPushBroker;
3046 }
3047
3048 private void provisionAccount(final String address, final String password) {
3049 final Jid jid = Jid.of(address);
3050 final Account account = new Account(jid, password);
3051 account.setOption(Account.OPTION_DISABLED, true);
3052 Log.d(Config.LOGTAG, jid.asBareJid().toString() + ": provisioning account");
3053 createAccount(account);
3054 }
3055
3056 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
3057 new Thread(
3058 () -> {
3059 try {
3060 final X509Certificate[] chain =
3061 KeyChain.getCertificateChain(this, alias);
3062 final X509Certificate cert =
3063 chain != null && chain.length > 0 ? chain[0] : null;
3064 if (cert == null) {
3065 callback.informUser(R.string.unable_to_parse_certificate);
3066 return;
3067 }
3068 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
3069 if (info == null) {
3070 callback.informUser(R.string.certificate_does_not_contain_jid);
3071 return;
3072 }
3073 if (findAccountByJid(info.first) == null) {
3074 final Account account = new Account(info.first, "");
3075 account.setPrivateKeyAlias(alias);
3076 account.setOption(Account.OPTION_DISABLED, true);
3077 account.setOption(Account.OPTION_FIXED_USERNAME, true);
3078 account.setDisplayName(info.second);
3079 createAccount(account);
3080 callback.onAccountCreated(account);
3081 if (Config.X509_VERIFICATION) {
3082 try {
3083 getMemorizingTrustManager()
3084 .getNonInteractive(account.getServer())
3085 .checkClientTrusted(chain, "RSA");
3086 } catch (CertificateException e) {
3087 callback.informUser(
3088 R.string.certificate_chain_is_not_trusted);
3089 }
3090 }
3091 } else {
3092 callback.informUser(R.string.account_already_exists);
3093 }
3094 } catch (Exception e) {
3095 callback.informUser(R.string.unable_to_parse_certificate);
3096 }
3097 })
3098 .start();
3099 }
3100
3101 public void updateKeyInAccount(final Account account, final String alias) {
3102 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
3103 try {
3104 X509Certificate[] chain =
3105 KeyChain.getCertificateChain(XmppConnectionService.this, alias);
3106 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
3107 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
3108 if (info == null) {
3109 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
3110 return;
3111 }
3112 if (account.getJid().asBareJid().equals(info.first)) {
3113 account.setPrivateKeyAlias(alias);
3114 account.setDisplayName(info.second);
3115 databaseBackend.updateAccount(account);
3116 if (Config.X509_VERIFICATION) {
3117 try {
3118 getMemorizingTrustManager()
3119 .getNonInteractive()
3120 .checkClientTrusted(chain, "RSA");
3121 } catch (CertificateException e) {
3122 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
3123 }
3124 account.getAxolotlService().regenerateKeys(true);
3125 }
3126 } else {
3127 showErrorToastInUi(R.string.jid_does_not_match_certificate);
3128 }
3129 } catch (Exception e) {
3130 e.printStackTrace();
3131 }
3132 }
3133
3134 public boolean updateAccount(final Account account) {
3135 if (databaseBackend.updateAccount(account)) {
3136 account.setShowErrorNotification(true);
3137 this.statusListener.onStatusChanged(account);
3138 databaseBackend.updateAccount(account);
3139 reconnectAccountInBackground(account);
3140 updateAccountUi();
3141 getNotificationService().updateErrorNotification();
3142 toggleForegroundService();
3143 syncEnabledAccountSetting();
3144 mChannelDiscoveryService.cleanCache();
3145 if (CallIntegration.hasSystemFeature(this)) {
3146 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
3147 }
3148 return true;
3149 } else {
3150 return false;
3151 }
3152 }
3153
3154 public void updateAccountPasswordOnServer(
3155 final Account account,
3156 final String newPassword,
3157 final OnAccountPasswordChanged callback) {
3158 final Iq iq = getIqGenerator().generateSetPassword(account, newPassword);
3159 sendIqPacket(
3160 account,
3161 iq,
3162 (packet) -> {
3163 if (packet.getType() == Iq.Type.RESULT) {
3164 account.setPassword(newPassword);
3165 account.setOption(Account.OPTION_MAGIC_CREATE, false);
3166 databaseBackend.updateAccount(account);
3167 callback.onPasswordChangeSucceeded();
3168 } else {
3169 callback.onPasswordChangeFailed();
3170 }
3171 });
3172 }
3173
3174 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
3175 final Iq iqPacket = new Iq(Iq.Type.SET);
3176 final Element query = iqPacket.addChild("query", Namespace.REGISTER);
3177 query.addChild("remove");
3178 sendIqPacket(
3179 account,
3180 iqPacket,
3181 (response) -> {
3182 if (response.getType() == Iq.Type.RESULT) {
3183 deleteAccount(account);
3184 callback.accept(true);
3185 } else {
3186 callback.accept(false);
3187 }
3188 });
3189 }
3190
3191 public void deleteAccount(final Account account) {
3192 final boolean connected = account.getStatus() == Account.State.ONLINE;
3193 synchronized (this.conversations) {
3194 if (connected) {
3195 account.getAxolotlService().deleteOmemoIdentity();
3196 }
3197 for (final Conversation conversation : conversations) {
3198 if (conversation.getAccount() == account) {
3199 if (conversation.getMode() == Conversation.MODE_MULTI) {
3200 if (connected) {
3201 leaveMuc(conversation);
3202 }
3203 }
3204 conversations.remove(conversation);
3205 mNotificationService.clear(conversation);
3206 }
3207 }
3208 if (account.getXmppConnection() != null) {
3209 new Thread(() -> disconnect(account, !connected)).start();
3210 }
3211 final Runnable runnable =
3212 () -> {
3213 if (!databaseBackend.deleteAccount(account)) {
3214 Log.d(
3215 Config.LOGTAG,
3216 account.getJid().asBareJid() + ": unable to delete account");
3217 }
3218 };
3219 mDatabaseWriterExecutor.execute(runnable);
3220 this.accounts.remove(account);
3221 if (CallIntegration.hasSystemFeature(this)) {
3222 CallIntegrationConnectionService.unregisterPhoneAccount(this, account);
3223 }
3224 this.mRosterSyncTaskManager.clear(account);
3225 updateAccountUi();
3226 mNotificationService.updateErrorNotification();
3227 syncEnabledAccountSetting();
3228 toggleForegroundService();
3229 }
3230 }
3231
3232 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
3233 final boolean remainingListeners;
3234 synchronized (LISTENER_LOCK) {
3235 remainingListeners = checkListeners();
3236 if (!this.mOnConversationUpdates.add(listener)) {
3237 Log.w(
3238 Config.LOGTAG,
3239 listener.getClass().getName()
3240 + " is already registered as ConversationListChangedListener");
3241 }
3242 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3243 }
3244 if (remainingListeners) {
3245 switchToForeground();
3246 }
3247 }
3248
3249 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
3250 final boolean remainingListeners;
3251 synchronized (LISTENER_LOCK) {
3252 this.mOnConversationUpdates.remove(listener);
3253 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3254 remainingListeners = checkListeners();
3255 }
3256 if (remainingListeners) {
3257 switchToBackground();
3258 }
3259 }
3260
3261 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
3262 final boolean remainingListeners;
3263 synchronized (LISTENER_LOCK) {
3264 remainingListeners = checkListeners();
3265 if (!this.mOnShowErrorToasts.add(listener)) {
3266 Log.w(
3267 Config.LOGTAG,
3268 listener.getClass().getName()
3269 + " is already registered as OnShowErrorToastListener");
3270 }
3271 }
3272 if (remainingListeners) {
3273 switchToForeground();
3274 }
3275 }
3276
3277 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
3278 final boolean remainingListeners;
3279 synchronized (LISTENER_LOCK) {
3280 this.mOnShowErrorToasts.remove(onShowErrorToast);
3281 remainingListeners = checkListeners();
3282 }
3283 if (remainingListeners) {
3284 switchToBackground();
3285 }
3286 }
3287
3288 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
3289 final boolean remainingListeners;
3290 synchronized (LISTENER_LOCK) {
3291 remainingListeners = checkListeners();
3292 if (!this.mOnAccountUpdates.add(listener)) {
3293 Log.w(
3294 Config.LOGTAG,
3295 listener.getClass().getName()
3296 + " is already registered as OnAccountListChangedtListener");
3297 }
3298 }
3299 if (remainingListeners) {
3300 switchToForeground();
3301 }
3302 }
3303
3304 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
3305 final boolean remainingListeners;
3306 synchronized (LISTENER_LOCK) {
3307 this.mOnAccountUpdates.remove(listener);
3308 remainingListeners = checkListeners();
3309 }
3310 if (remainingListeners) {
3311 switchToBackground();
3312 }
3313 }
3314
3315 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3316 final boolean remainingListeners;
3317 synchronized (LISTENER_LOCK) {
3318 remainingListeners = checkListeners();
3319 if (!this.mOnCaptchaRequested.add(listener)) {
3320 Log.w(
3321 Config.LOGTAG,
3322 listener.getClass().getName()
3323 + " is already registered as OnCaptchaRequestListener");
3324 }
3325 }
3326 if (remainingListeners) {
3327 switchToForeground();
3328 }
3329 }
3330
3331 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3332 final boolean remainingListeners;
3333 synchronized (LISTENER_LOCK) {
3334 this.mOnCaptchaRequested.remove(listener);
3335 remainingListeners = checkListeners();
3336 }
3337 if (remainingListeners) {
3338 switchToBackground();
3339 }
3340 }
3341
3342 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
3343 final boolean remainingListeners;
3344 synchronized (LISTENER_LOCK) {
3345 remainingListeners = checkListeners();
3346 if (!this.mOnRosterUpdates.add(listener)) {
3347 Log.w(
3348 Config.LOGTAG,
3349 listener.getClass().getName()
3350 + " is already registered as OnRosterUpdateListener");
3351 }
3352 }
3353 if (remainingListeners) {
3354 switchToForeground();
3355 }
3356 }
3357
3358 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
3359 final boolean remainingListeners;
3360 synchronized (LISTENER_LOCK) {
3361 this.mOnRosterUpdates.remove(listener);
3362 remainingListeners = checkListeners();
3363 }
3364 if (remainingListeners) {
3365 switchToBackground();
3366 }
3367 }
3368
3369 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3370 final boolean remainingListeners;
3371 synchronized (LISTENER_LOCK) {
3372 remainingListeners = checkListeners();
3373 if (!this.mOnUpdateBlocklist.add(listener)) {
3374 Log.w(
3375 Config.LOGTAG,
3376 listener.getClass().getName()
3377 + " is already registered as OnUpdateBlocklistListener");
3378 }
3379 }
3380 if (remainingListeners) {
3381 switchToForeground();
3382 }
3383 }
3384
3385 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3386 final boolean remainingListeners;
3387 synchronized (LISTENER_LOCK) {
3388 this.mOnUpdateBlocklist.remove(listener);
3389 remainingListeners = checkListeners();
3390 }
3391 if (remainingListeners) {
3392 switchToBackground();
3393 }
3394 }
3395
3396 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
3397 final boolean remainingListeners;
3398 synchronized (LISTENER_LOCK) {
3399 remainingListeners = checkListeners();
3400 if (!this.mOnKeyStatusUpdated.add(listener)) {
3401 Log.w(
3402 Config.LOGTAG,
3403 listener.getClass().getName()
3404 + " is already registered as OnKeyStatusUpdateListener");
3405 }
3406 }
3407 if (remainingListeners) {
3408 switchToForeground();
3409 }
3410 }
3411
3412 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
3413 final boolean remainingListeners;
3414 synchronized (LISTENER_LOCK) {
3415 this.mOnKeyStatusUpdated.remove(listener);
3416 remainingListeners = checkListeners();
3417 }
3418 if (remainingListeners) {
3419 switchToBackground();
3420 }
3421 }
3422
3423 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3424 final boolean remainingListeners;
3425 synchronized (LISTENER_LOCK) {
3426 remainingListeners = checkListeners();
3427 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
3428 Log.w(
3429 Config.LOGTAG,
3430 listener.getClass().getName()
3431 + " is already registered as OnJingleRtpConnectionUpdate");
3432 }
3433 }
3434 if (remainingListeners) {
3435 switchToForeground();
3436 }
3437 }
3438
3439 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3440 final boolean remainingListeners;
3441 synchronized (LISTENER_LOCK) {
3442 this.onJingleRtpConnectionUpdate.remove(listener);
3443 remainingListeners = checkListeners();
3444 }
3445 if (remainingListeners) {
3446 switchToBackground();
3447 }
3448 }
3449
3450 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
3451 final boolean remainingListeners;
3452 synchronized (LISTENER_LOCK) {
3453 remainingListeners = checkListeners();
3454 if (!this.mOnMucRosterUpdate.add(listener)) {
3455 Log.w(
3456 Config.LOGTAG,
3457 listener.getClass().getName()
3458 + " is already registered as OnMucRosterListener");
3459 }
3460 }
3461 if (remainingListeners) {
3462 switchToForeground();
3463 }
3464 }
3465
3466 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
3467 final boolean remainingListeners;
3468 synchronized (LISTENER_LOCK) {
3469 this.mOnMucRosterUpdate.remove(listener);
3470 remainingListeners = checkListeners();
3471 }
3472 if (remainingListeners) {
3473 switchToBackground();
3474 }
3475 }
3476
3477 public boolean checkListeners() {
3478 return (this.mOnAccountUpdates.isEmpty()
3479 && this.mOnConversationUpdates.isEmpty()
3480 && this.mOnRosterUpdates.isEmpty()
3481 && this.mOnCaptchaRequested.isEmpty()
3482 && this.mOnMucRosterUpdate.isEmpty()
3483 && this.mOnUpdateBlocklist.isEmpty()
3484 && this.mOnShowErrorToasts.isEmpty()
3485 && this.onJingleRtpConnectionUpdate.isEmpty()
3486 && this.mOnKeyStatusUpdated.isEmpty());
3487 }
3488
3489 private void switchToForeground() {
3490 toggleSoftDisabled(false);
3491 final boolean broadcastLastActivity = broadcastLastActivity();
3492 for (Conversation conversation : getConversations()) {
3493 if (conversation.getMode() == Conversation.MODE_MULTI) {
3494 conversation.getMucOptions().resetChatState();
3495 } else {
3496 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
3497 }
3498 }
3499 for (Account account : getAccounts()) {
3500 if (account.getStatus() == Account.State.ONLINE) {
3501 account.deactivateGracePeriod();
3502 final XmppConnection connection = account.getXmppConnection();
3503 if (connection != null) {
3504 if (connection.getFeatures().csi()) {
3505 connection.sendActive();
3506 }
3507 if (broadcastLastActivity) {
3508 sendPresence(
3509 account,
3510 false); // send new presence but don't include idle because we are
3511 // not
3512 }
3513 }
3514 }
3515 }
3516 Log.d(Config.LOGTAG, "app switched into foreground");
3517 }
3518
3519 private void switchToBackground() {
3520 final boolean broadcastLastActivity = broadcastLastActivity();
3521 if (broadcastLastActivity) {
3522 mLastActivity = System.currentTimeMillis();
3523 final SharedPreferences.Editor editor = getPreferences().edit();
3524 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3525 editor.apply();
3526 }
3527 for (Account account : getAccounts()) {
3528 if (account.getStatus() == Account.State.ONLINE) {
3529 XmppConnection connection = account.getXmppConnection();
3530 if (connection != null) {
3531 if (broadcastLastActivity) {
3532 sendPresence(account, true);
3533 }
3534 if (connection.getFeatures().csi()) {
3535 connection.sendInactive();
3536 }
3537 }
3538 }
3539 }
3540 this.mNotificationService.setIsInForeground(false);
3541 Log.d(Config.LOGTAG, "app switched into background");
3542 }
3543
3544 public void connectMultiModeConversations(Account account) {
3545 List<Conversation> conversations = getConversations();
3546 for (Conversation conversation : conversations) {
3547 if (conversation.getMode() == Conversation.MODE_MULTI
3548 && conversation.getAccount() == account) {
3549 joinMuc(conversation);
3550 }
3551 }
3552 }
3553
3554 public void mucSelfPingAndRejoin(final Conversation conversation) {
3555 final Account account = conversation.getAccount();
3556 synchronized (account.inProgressConferenceJoins) {
3557 if (account.inProgressConferenceJoins.contains(conversation)) {
3558 Log.d(
3559 Config.LOGTAG,
3560 account.getJid().asBareJid()
3561 + ": canceling muc self ping because join is already under way");
3562 return;
3563 }
3564 }
3565 synchronized (account.inProgressConferencePings) {
3566 if (!account.inProgressConferencePings.add(conversation)) {
3567 Log.d(
3568 Config.LOGTAG,
3569 account.getJid().asBareJid()
3570 + ": canceling muc self ping because ping is already under way");
3571 return;
3572 }
3573 }
3574 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3575 final Iq ping = new Iq(Iq.Type.GET);
3576 ping.setTo(self);
3577 ping.addChild("ping", Namespace.PING);
3578 sendIqPacket(
3579 conversation.getAccount(),
3580 ping,
3581 (response) -> {
3582 if (response.getType() == Iq.Type.ERROR) {
3583 final var error = response.getError();
3584 if (error == null
3585 || error.hasChild("service-unavailable")
3586 || error.hasChild("feature-not-implemented")
3587 || error.hasChild("item-not-found")) {
3588 Log.d(
3589 Config.LOGTAG,
3590 account.getJid().asBareJid()
3591 + ": ping to "
3592 + self
3593 + " came back as ignorable error");
3594 } else {
3595 Log.d(
3596 Config.LOGTAG,
3597 account.getJid().asBareJid()
3598 + ": ping to "
3599 + self
3600 + " failed. attempting rejoin");
3601 joinMuc(conversation);
3602 }
3603 } else if (response.getType() == Iq.Type.RESULT) {
3604 Log.d(
3605 Config.LOGTAG,
3606 account.getJid().asBareJid()
3607 + ": ping to "
3608 + self
3609 + " came back fine");
3610 }
3611 synchronized (account.inProgressConferencePings) {
3612 account.inProgressConferencePings.remove(conversation);
3613 }
3614 });
3615 }
3616
3617 public void joinMuc(Conversation conversation) {
3618 joinMuc(conversation, null, false);
3619 }
3620
3621 public void joinMuc(Conversation conversation, boolean followedInvite) {
3622 joinMuc(conversation, null, followedInvite);
3623 }
3624
3625 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3626 joinMuc(conversation, onConferenceJoined, false);
3627 }
3628
3629 private void joinMuc(
3630 final Conversation conversation,
3631 final OnConferenceJoined onConferenceJoined,
3632 final boolean followedInvite) {
3633 final Account account = conversation.getAccount();
3634 synchronized (account.pendingConferenceJoins) {
3635 account.pendingConferenceJoins.remove(conversation);
3636 }
3637 synchronized (account.pendingConferenceLeaves) {
3638 account.pendingConferenceLeaves.remove(conversation);
3639 }
3640 if (account.getStatus() == Account.State.ONLINE) {
3641 synchronized (account.inProgressConferenceJoins) {
3642 account.inProgressConferenceJoins.add(conversation);
3643 }
3644 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3645 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3646 }
3647 conversation.resetMucOptions();
3648 if (onConferenceJoined != null) {
3649 conversation.getMucOptions().flagNoAutoPushConfiguration();
3650 }
3651 conversation.setHasMessagesLeftOnServer(false);
3652 fetchConferenceConfiguration(
3653 conversation,
3654 new OnConferenceConfigurationFetched() {
3655
3656 private void join(Conversation conversation) {
3657 Account account = conversation.getAccount();
3658 final MucOptions mucOptions = conversation.getMucOptions();
3659
3660 if (mucOptions.nonanonymous()
3661 && !mucOptions.membersOnly()
3662 && !conversation.getBooleanAttribute(
3663 "accept_non_anonymous", false)) {
3664 synchronized (account.inProgressConferenceJoins) {
3665 account.inProgressConferenceJoins.remove(conversation);
3666 }
3667 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3668 updateConversationUi();
3669 if (onConferenceJoined != null) {
3670 onConferenceJoined.onConferenceJoined(conversation);
3671 }
3672 return;
3673 }
3674
3675 final Jid joinJid = mucOptions.getSelf().getFullJid();
3676 Log.d(
3677 Config.LOGTAG,
3678 account.getJid().asBareJid().toString()
3679 + ": joining conversation "
3680 + joinJid.toString());
3681 final var packet =
3682 mPresenceGenerator.selfPresence(
3683 account,
3684 Presence.Status.ONLINE,
3685 mucOptions.nonanonymous()
3686 || onConferenceJoined != null);
3687 packet.setTo(joinJid);
3688 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3689 if (conversation.getMucOptions().getPassword() != null) {
3690 x.addChild("password").setContent(mucOptions.getPassword());
3691 }
3692
3693 if (mucOptions.mamSupport()) {
3694 // Use MAM instead of the limited muc history to get history
3695 x.addChild("history").setAttribute("maxchars", "0");
3696 } else {
3697 // Fallback to muc history
3698 x.addChild("history")
3699 .setAttribute(
3700 "since",
3701 PresenceGenerator.getTimestamp(
3702 conversation
3703 .getLastMessageTransmitted()
3704 .getTimestamp()));
3705 }
3706 sendPresencePacket(account, packet);
3707 if (onConferenceJoined != null) {
3708 onConferenceJoined.onConferenceJoined(conversation);
3709 }
3710 if (!joinJid.equals(conversation.getJid())) {
3711 conversation.setContactJid(joinJid);
3712 databaseBackend.updateConversation(conversation);
3713 }
3714
3715 if (mucOptions.mamSupport()) {
3716 getMessageArchiveService().catchupMUC(conversation);
3717 }
3718 if (mucOptions.isPrivateAndNonAnonymous()) {
3719 fetchConferenceMembers(conversation);
3720
3721 if (followedInvite) {
3722 final Bookmark bookmark = conversation.getBookmark();
3723 if (bookmark != null) {
3724 if (!bookmark.autojoin()) {
3725 bookmark.setAutojoin(true);
3726 createBookmark(account, bookmark);
3727 }
3728 } else {
3729 saveConversationAsBookmark(conversation, null);
3730 }
3731 }
3732 }
3733 synchronized (account.inProgressConferenceJoins) {
3734 account.inProgressConferenceJoins.remove(conversation);
3735 sendUnsentMessages(conversation);
3736 }
3737 }
3738
3739 @Override
3740 public void onConferenceConfigurationFetched(Conversation conversation) {
3741 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3742 Log.d(
3743 Config.LOGTAG,
3744 account.getJid().asBareJid()
3745 + ": conversation ("
3746 + conversation.getJid()
3747 + ") got archived before IQ result");
3748 return;
3749 }
3750 join(conversation);
3751 }
3752
3753 @Override
3754 public void onFetchFailed(
3755 final Conversation conversation, final String errorCondition) {
3756 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3757 Log.d(
3758 Config.LOGTAG,
3759 account.getJid().asBareJid()
3760 + ": conversation ("
3761 + conversation.getJid()
3762 + ") got archived before IQ result");
3763 return;
3764 }
3765 if ("remote-server-not-found".equals(errorCondition)) {
3766 synchronized (account.inProgressConferenceJoins) {
3767 account.inProgressConferenceJoins.remove(conversation);
3768 }
3769 conversation
3770 .getMucOptions()
3771 .setError(MucOptions.Error.SERVER_NOT_FOUND);
3772 updateConversationUi();
3773 } else {
3774 join(conversation);
3775 fetchConferenceConfiguration(conversation);
3776 }
3777 }
3778 });
3779 updateConversationUi();
3780 } else {
3781 synchronized (account.pendingConferenceJoins) {
3782 account.pendingConferenceJoins.add(conversation);
3783 }
3784 conversation.resetMucOptions();
3785 conversation.setHasMessagesLeftOnServer(false);
3786 updateConversationUi();
3787 }
3788 }
3789
3790 private void fetchConferenceMembers(final Conversation conversation) {
3791 final Account account = conversation.getAccount();
3792 final AxolotlService axolotlService = account.getAxolotlService();
3793 final String[] affiliations = {"member", "admin", "owner"};
3794 final Consumer<Iq> callback =
3795 new Consumer<Iq>() {
3796
3797 private int i = 0;
3798 private boolean success = true;
3799
3800 @Override
3801 public void accept(Iq response) {
3802 final boolean omemoEnabled =
3803 conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3804 Element query = response.query("http://jabber.org/protocol/muc#admin");
3805 if (response.getType() == Iq.Type.RESULT && query != null) {
3806 for (Element child : query.getChildren()) {
3807 if ("item".equals(child.getName())) {
3808 MucOptions.User user =
3809 AbstractParser.parseItem(conversation, child);
3810 if (!user.realJidMatchesAccount()) {
3811 boolean isNew =
3812 conversation.getMucOptions().updateUser(user);
3813 Contact contact = user.getContact();
3814 if (omemoEnabled
3815 && isNew
3816 && user.getRealJid() != null
3817 && (contact == null
3818 || !contact.mutualPresenceSubscription())
3819 && axolotlService.hasEmptyDeviceList(
3820 user.getRealJid())) {
3821 axolotlService.fetchDeviceIds(user.getRealJid());
3822 }
3823 }
3824 }
3825 }
3826 } else {
3827 success = false;
3828 Log.d(
3829 Config.LOGTAG,
3830 account.getJid().asBareJid()
3831 + ": could not request affiliation "
3832 + affiliations[i]
3833 + " in "
3834 + conversation.getJid().asBareJid());
3835 }
3836 ++i;
3837 if (i >= affiliations.length) {
3838 final var mucOptions = conversation.getMucOptions();
3839 final var members = mucOptions.getMembers(true);
3840 if (success) {
3841 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3842 boolean changed = false;
3843 for (ListIterator<Jid> iterator = cryptoTargets.listIterator();
3844 iterator.hasNext(); ) {
3845 Jid jid = iterator.next();
3846 if (!members.contains(jid)
3847 && !members.contains(jid.getDomain())) {
3848 iterator.remove();
3849 Log.d(
3850 Config.LOGTAG,
3851 account.getJid().asBareJid()
3852 + ": removed "
3853 + jid
3854 + " from crypto targets of "
3855 + conversation.getName());
3856 changed = true;
3857 }
3858 }
3859 if (changed) {
3860 conversation.setAcceptedCryptoTargets(cryptoTargets);
3861 updateConversation(conversation);
3862 }
3863 }
3864 getAvatarService().clear(mucOptions);
3865 updateMucRosterUi();
3866 updateConversationUi();
3867 }
3868 }
3869 };
3870 for (String affiliation : affiliations) {
3871 sendIqPacket(
3872 account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3873 }
3874 Log.d(
3875 Config.LOGTAG,
3876 account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3877 }
3878
3879 public void providePasswordForMuc(final Conversation conversation, final String password) {
3880 if (conversation.getMode() == Conversation.MODE_MULTI) {
3881 conversation.getMucOptions().setPassword(password);
3882 if (conversation.getBookmark() != null) {
3883 final Bookmark bookmark = conversation.getBookmark();
3884 bookmark.setAutojoin(true);
3885 createBookmark(conversation.getAccount(), bookmark);
3886 }
3887 updateConversation(conversation);
3888 joinMuc(conversation);
3889 }
3890 }
3891
3892 public void deleteAvatar(final Account account) {
3893 final AtomicBoolean executed = new AtomicBoolean(false);
3894 final Runnable onDeleted =
3895 () -> {
3896 if (executed.compareAndSet(false, true)) {
3897 account.setAvatar(null);
3898 databaseBackend.updateAccount(account);
3899 getAvatarService().clear(account);
3900 updateAccountUi();
3901 }
3902 };
3903 deleteVcardAvatar(account, onDeleted);
3904 deletePepNode(account, Namespace.AVATAR_DATA);
3905 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3906 }
3907
3908 public void deletePepNode(final Account account, final String node) {
3909 deletePepNode(account, node, null);
3910 }
3911
3912 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3913 final Iq request = mIqGenerator.deleteNode(node);
3914 sendIqPacket(
3915 account,
3916 request,
3917 (packet) -> {
3918 if (packet.getType() == Iq.Type.RESULT) {
3919 Log.d(
3920 Config.LOGTAG,
3921 account.getJid().asBareJid()
3922 + ": successfully deleted pep node "
3923 + node);
3924 if (runnable != null) {
3925 runnable.run();
3926 }
3927 } else {
3928 Log.d(
3929 Config.LOGTAG,
3930 account.getJid().asBareJid() + ": failed to delete " + packet);
3931 }
3932 });
3933 }
3934
3935 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3936 final Iq retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3937 sendIqPacket(
3938 account,
3939 retrieveVcard,
3940 (response) -> {
3941 if (response.getType() != Iq.Type.RESULT) {
3942 Log.d(
3943 Config.LOGTAG,
3944 account.getJid().asBareJid() + ": no vCard set. nothing to do");
3945 return;
3946 }
3947 final Element vcard = response.findChild("vCard", "vcard-temp");
3948 if (vcard == null) {
3949 Log.d(
3950 Config.LOGTAG,
3951 account.getJid().asBareJid() + ": no vCard set. nothing to do");
3952 return;
3953 }
3954 Element photo = vcard.findChild("PHOTO");
3955 if (photo == null) {
3956 photo = vcard.addChild("PHOTO");
3957 }
3958 photo.clearChildren();
3959 final Iq publication = new Iq(Iq.Type.SET);
3960 publication.setTo(account.getJid().asBareJid());
3961 publication.addChild(vcard);
3962 sendIqPacket(
3963 account,
3964 publication,
3965 (publicationResponse) -> {
3966 if (publicationResponse.getType() == Iq.Type.RESULT) {
3967 Log.d(
3968 Config.LOGTAG,
3969 account.getJid().asBareJid()
3970 + ": successfully deleted vcard avatar");
3971 runnable.run();
3972 } else {
3973 Log.d(
3974 Config.LOGTAG,
3975 "failed to publish vcard "
3976 + publicationResponse.getErrorCondition());
3977 }
3978 });
3979 });
3980 }
3981
3982 private boolean hasEnabledAccounts() {
3983 if (this.accounts == null) {
3984 return false;
3985 }
3986 for (final Account account : this.accounts) {
3987 if (account.isConnectionEnabled()) {
3988 return true;
3989 }
3990 }
3991 return false;
3992 }
3993
3994 public void getAttachments(
3995 final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3996 getAttachments(
3997 conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3998 }
3999
4000 public void getAttachments(
4001 final Account account,
4002 final Jid jid,
4003 final int limit,
4004 final OnMediaLoaded onMediaLoaded) {
4005 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
4006 }
4007
4008 public void getAttachments(
4009 final String account,
4010 final Jid jid,
4011 final int limit,
4012 final OnMediaLoaded onMediaLoaded) {
4013 new Thread(
4014 () ->
4015 onMediaLoaded.onMediaLoaded(
4016 fileBackend.convertToAttachments(
4017 databaseBackend.getRelativeFilePaths(
4018 account, jid, limit))))
4019 .start();
4020 }
4021
4022 public void persistSelfNick(final MucOptions.User self, final boolean modified) {
4023 final Conversation conversation = self.getConversation();
4024 final Account account = conversation.getAccount();
4025 final Jid full = self.getFullJid();
4026 if (!full.equals(conversation.getJid())) {
4027 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisting full jid " + full);
4028 conversation.setContactJid(full);
4029 databaseBackend.updateConversation(conversation);
4030 }
4031
4032 final Bookmark bookmark = conversation.getBookmark();
4033 if (bookmark == null || !modified) {
4034 return;
4035 }
4036 final var nick = full.getResource();
4037 final String defaultNick = MucOptions.defaultNick(account);
4038 if (nick.equals(defaultNick) || nick.equals(bookmark.getNick())) {
4039 return;
4040 }
4041 Log.d(
4042 Config.LOGTAG,
4043 account.getJid().asBareJid()
4044 + ": persist nick '"
4045 + full.getResource()
4046 + "' into bookmark for "
4047 + conversation.getJid().asBareJid());
4048 bookmark.setNick(nick);
4049 createBookmark(bookmark.getAccount(), bookmark);
4050 }
4051
4052 public boolean renameInMuc(
4053 final Conversation conversation,
4054 final String nick,
4055 final UiCallback<Conversation> callback) {
4056 final Account account = conversation.getAccount();
4057 final Bookmark bookmark = conversation.getBookmark();
4058 final MucOptions options = conversation.getMucOptions();
4059 final Jid joinJid = options.createJoinJid(nick);
4060 if (joinJid == null) {
4061 return false;
4062 }
4063 if (options.online()) {
4064 options.setOnRenameListener(
4065 new OnRenameListener() {
4066
4067 @Override
4068 public void onSuccess() {
4069 callback.success(conversation);
4070 }
4071
4072 @Override
4073 public void onFailure() {
4074 callback.error(R.string.nick_in_use, conversation);
4075 }
4076 });
4077
4078 final var packet =
4079 mPresenceGenerator.selfPresence(
4080 account, Presence.Status.ONLINE, options.nonanonymous());
4081 packet.setTo(joinJid);
4082 sendPresencePacket(account, packet);
4083 if (nick.equals(MucOptions.defaultNick(account))
4084 && bookmark != null
4085 && bookmark.getNick() != null) {
4086 Log.d(
4087 Config.LOGTAG,
4088 account.getJid().asBareJid()
4089 + ": removing nick from bookmark for "
4090 + bookmark.getJid());
4091 bookmark.setNick(null);
4092 createBookmark(account, bookmark);
4093 }
4094 } else {
4095 conversation.setContactJid(joinJid);
4096 databaseBackend.updateConversation(conversation);
4097 if (account.getStatus() == Account.State.ONLINE) {
4098 if (bookmark != null) {
4099 bookmark.setNick(nick);
4100 createBookmark(account, bookmark);
4101 }
4102 joinMuc(conversation);
4103 }
4104 }
4105 return true;
4106 }
4107
4108 public void checkMucRequiresRename() {
4109 synchronized (this.conversations) {
4110 for (final Conversation conversation : this.conversations) {
4111 if (conversation.getMode() == Conversational.MODE_MULTI) {
4112 checkMucRequiresRename(conversation);
4113 }
4114 }
4115 }
4116 }
4117
4118 private void checkMucRequiresRename(final Conversation conversation) {
4119 final var options = conversation.getMucOptions();
4120 if (!options.online()) {
4121 return;
4122 }
4123 final var account = conversation.getAccount();
4124 final String current = options.getActualNick();
4125 final String proposed = options.getProposedNickPure();
4126 if (current == null || current.equals(proposed)) {
4127 return;
4128 }
4129 final Jid joinJid = options.createJoinJid(proposed);
4130 Log.d(
4131 Config.LOGTAG,
4132 String.format(
4133 "%s: muc rename required %s (was: %s)",
4134 account.getJid().asBareJid(), joinJid, current));
4135 final var packet =
4136 mPresenceGenerator.selfPresence(
4137 account, Presence.Status.ONLINE, options.nonanonymous());
4138 packet.setTo(joinJid);
4139 sendPresencePacket(account, packet);
4140 }
4141
4142 public void leaveMuc(Conversation conversation) {
4143 leaveMuc(conversation, false);
4144 }
4145
4146 private void leaveMuc(Conversation conversation, boolean now) {
4147 final Account account = conversation.getAccount();
4148 synchronized (account.pendingConferenceJoins) {
4149 account.pendingConferenceJoins.remove(conversation);
4150 }
4151 synchronized (account.pendingConferenceLeaves) {
4152 account.pendingConferenceLeaves.remove(conversation);
4153 }
4154 if (account.getStatus() == Account.State.ONLINE || now) {
4155 sendPresencePacket(
4156 conversation.getAccount(),
4157 mPresenceGenerator.leave(conversation.getMucOptions()));
4158 conversation.getMucOptions().setOffline();
4159 Bookmark bookmark = conversation.getBookmark();
4160 if (bookmark != null) {
4161 bookmark.setConversation(null);
4162 }
4163 Log.d(
4164 Config.LOGTAG,
4165 conversation.getAccount().getJid().asBareJid()
4166 + ": leaving muc "
4167 + conversation.getJid());
4168 } else {
4169 synchronized (account.pendingConferenceLeaves) {
4170 account.pendingConferenceLeaves.add(conversation);
4171 }
4172 }
4173 }
4174
4175 public String findConferenceServer(final Account account) {
4176 String server;
4177 if (account.getXmppConnection() != null) {
4178 server = account.getXmppConnection().getMucServer();
4179 if (server != null) {
4180 return server;
4181 }
4182 }
4183 for (Account other : getAccounts()) {
4184 if (other != account && other.getXmppConnection() != null) {
4185 server = other.getXmppConnection().getMucServer();
4186 if (server != null) {
4187 return server;
4188 }
4189 }
4190 }
4191 return null;
4192 }
4193
4194 public void createPublicChannel(
4195 final Account account,
4196 final String name,
4197 final Jid address,
4198 final UiCallback<Conversation> callback) {
4199 joinMuc(
4200 findOrCreateConversation(account, address, true, false, true),
4201 conversation -> {
4202 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
4203 if (!TextUtils.isEmpty(name)) {
4204 configuration.putString("muc#roomconfig_roomname", name);
4205 }
4206 pushConferenceConfiguration(
4207 conversation,
4208 configuration,
4209 new OnConfigurationPushed() {
4210 @Override
4211 public void onPushSucceeded() {
4212 saveConversationAsBookmark(conversation, name);
4213 callback.success(conversation);
4214 }
4215
4216 @Override
4217 public void onPushFailed() {
4218 if (conversation
4219 .getMucOptions()
4220 .getSelf()
4221 .getAffiliation()
4222 .ranks(MucOptions.Affiliation.OWNER)) {
4223 callback.error(
4224 R.string.unable_to_set_channel_configuration,
4225 conversation);
4226 } else {
4227 callback.error(
4228 R.string.joined_an_existing_channel, conversation);
4229 }
4230 }
4231 });
4232 });
4233 }
4234
4235 public boolean createAdhocConference(
4236 final Account account,
4237 final String name,
4238 final Iterable<Jid> jids,
4239 final UiCallback<Conversation> callback) {
4240 Log.d(
4241 Config.LOGTAG,
4242 account.getJid().asBareJid().toString()
4243 + ": creating adhoc conference with "
4244 + jids.toString());
4245 if (account.getStatus() == Account.State.ONLINE) {
4246 try {
4247 String server = findConferenceServer(account);
4248 if (server == null) {
4249 if (callback != null) {
4250 callback.error(R.string.no_conference_server_found, null);
4251 }
4252 return false;
4253 }
4254 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
4255 final Conversation conversation =
4256 findOrCreateConversation(account, jid, true, false, true);
4257 joinMuc(
4258 conversation,
4259 new OnConferenceJoined() {
4260 @Override
4261 public void onConferenceJoined(final Conversation conversation) {
4262 final Bundle configuration =
4263 IqGenerator.defaultGroupChatConfiguration();
4264 if (!TextUtils.isEmpty(name)) {
4265 configuration.putString("muc#roomconfig_roomname", name);
4266 }
4267 pushConferenceConfiguration(
4268 conversation,
4269 configuration,
4270 new OnConfigurationPushed() {
4271 @Override
4272 public void onPushSucceeded() {
4273 for (Jid invite : jids) {
4274 invite(conversation, invite);
4275 }
4276 for (String resource :
4277 account.getSelfContact()
4278 .getPresences()
4279 .toResourceArray()) {
4280 Jid other =
4281 account.getJid().withResource(resource);
4282 Log.d(
4283 Config.LOGTAG,
4284 account.getJid().asBareJid()
4285 + ": sending direct invite to "
4286 + other);
4287 directInvite(conversation, other);
4288 }
4289 saveConversationAsBookmark(conversation, name);
4290 if (callback != null) {
4291 callback.success(conversation);
4292 }
4293 }
4294
4295 @Override
4296 public void onPushFailed() {
4297 archiveConversation(conversation);
4298 if (callback != null) {
4299 callback.error(
4300 R.string.conference_creation_failed,
4301 conversation);
4302 }
4303 }
4304 });
4305 }
4306 });
4307 return true;
4308 } catch (IllegalArgumentException e) {
4309 if (callback != null) {
4310 callback.error(R.string.conference_creation_failed, null);
4311 }
4312 return false;
4313 }
4314 } else {
4315 if (callback != null) {
4316 callback.error(R.string.not_connected_try_again, null);
4317 }
4318 return false;
4319 }
4320 }
4321
4322 public void fetchConferenceConfiguration(final Conversation conversation) {
4323 fetchConferenceConfiguration(conversation, null);
4324 }
4325
4326 public void fetchConferenceConfiguration(
4327 final Conversation conversation, final OnConferenceConfigurationFetched callback) {
4328 final Iq request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
4329 final var account = conversation.getAccount();
4330 sendIqPacket(
4331 account,
4332 request,
4333 response -> {
4334 if (response.getType() == Iq.Type.RESULT) {
4335 final MucOptions mucOptions = conversation.getMucOptions();
4336 final Bookmark bookmark = conversation.getBookmark();
4337 final boolean sameBefore =
4338 StringUtils.equals(
4339 bookmark == null ? null : bookmark.getBookmarkName(),
4340 mucOptions.getName());
4341
4342 final var hadOccupantId = mucOptions.occupantId();
4343 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(response))) {
4344 Log.d(
4345 Config.LOGTAG,
4346 account.getJid().asBareJid()
4347 + ": muc configuration changed for "
4348 + conversation.getJid().asBareJid());
4349 updateConversation(conversation);
4350 }
4351
4352 final var hasOccupantId = mucOptions.occupantId();
4353
4354 if (!hadOccupantId && hasOccupantId && mucOptions.online()) {
4355 final var me = mucOptions.getSelf().getFullJid();
4356 Log.d(
4357 Config.LOGTAG,
4358 account.getJid().asBareJid()
4359 + ": gained support for occupant-id in "
4360 + me
4361 + ". resending presence");
4362 final var packet =
4363 mPresenceGenerator.selfPresence(
4364 account,
4365 Presence.Status.ONLINE,
4366 mucOptions.nonanonymous());
4367 packet.setTo(me);
4368 sendPresencePacket(account, packet);
4369 }
4370
4371 if (bookmark != null
4372 && (sameBefore || bookmark.getBookmarkName() == null)) {
4373 if (bookmark.setBookmarkName(
4374 StringUtils.nullOnEmpty(mucOptions.getName()))) {
4375 createBookmark(account, bookmark);
4376 }
4377 }
4378
4379 if (callback != null) {
4380 callback.onConferenceConfigurationFetched(conversation);
4381 }
4382
4383 updateConversationUi();
4384 } else if (response.getType() == Iq.Type.TIMEOUT) {
4385 Log.d(
4386 Config.LOGTAG,
4387 account.getJid().asBareJid()
4388 + ": received timeout waiting for conference configuration"
4389 + " fetch");
4390 } else {
4391 if (callback != null) {
4392 callback.onFetchFailed(conversation, response.getErrorCondition());
4393 }
4394 }
4395 });
4396 }
4397
4398 public void pushNodeConfiguration(
4399 Account account,
4400 final String node,
4401 final Bundle options,
4402 final OnConfigurationPushed callback) {
4403 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
4404 }
4405
4406 public void pushNodeConfiguration(
4407 Account account,
4408 final Jid jid,
4409 final String node,
4410 final Bundle options,
4411 final OnConfigurationPushed callback) {
4412 Log.d(Config.LOGTAG, "pushing node configuration");
4413 sendIqPacket(
4414 account,
4415 mIqGenerator.requestPubsubConfiguration(jid, node),
4416 responseToRequest -> {
4417 if (responseToRequest.getType() == Iq.Type.RESULT) {
4418 Element pubsub =
4419 responseToRequest.findChild(
4420 "pubsub", "http://jabber.org/protocol/pubsub#owner");
4421 Element configuration =
4422 pubsub == null ? null : pubsub.findChild("configure");
4423 Element x =
4424 configuration == null
4425 ? null
4426 : configuration.findChild("x", Namespace.DATA);
4427 if (x != null) {
4428 final Data data = Data.parse(x);
4429 data.submit(options);
4430 sendIqPacket(
4431 account,
4432 mIqGenerator.publishPubsubConfiguration(jid, node, data),
4433 responseToPublish -> {
4434 if (responseToPublish.getType() == Iq.Type.RESULT
4435 && callback != null) {
4436 Log.d(
4437 Config.LOGTAG,
4438 account.getJid().asBareJid()
4439 + ": successfully changed node"
4440 + " configuration for node "
4441 + node);
4442 callback.onPushSucceeded();
4443 } else if (responseToPublish.getType() == Iq.Type.ERROR
4444 && callback != null) {
4445 callback.onPushFailed();
4446 }
4447 });
4448 } else if (callback != null) {
4449 callback.onPushFailed();
4450 }
4451 } else if (responseToRequest.getType() == Iq.Type.ERROR && callback != null) {
4452 callback.onPushFailed();
4453 }
4454 });
4455 }
4456
4457 public void pushConferenceConfiguration(
4458 final Conversation conversation,
4459 final Bundle options,
4460 final OnConfigurationPushed callback) {
4461 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
4462 conversation.setAttribute("accept_non_anonymous", true);
4463 updateConversation(conversation);
4464 }
4465 if (options.containsKey("muc#roomconfig_moderatedroom")) {
4466 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
4467 options.putString("members_by_default", moderated ? "0" : "1");
4468 }
4469 if (options.containsKey("muc#roomconfig_allowpm")) {
4470 // ejabberd :-/
4471 final boolean allow = "anyone".equals(options.getString("muc#roomconfig_allowpm"));
4472 options.putString("allow_private_messages", allow ? "1" : "0");
4473 options.putString("allow_private_messages_from_visitors", allow ? "anyone" : "nobody");
4474 }
4475 final var account = conversation.getAccount();
4476 final Iq request = new Iq(Iq.Type.GET);
4477 request.setTo(conversation.getJid().asBareJid());
4478 request.query("http://jabber.org/protocol/muc#owner");
4479 sendIqPacket(
4480 account,
4481 request,
4482 response -> {
4483 if (response.getType() == Iq.Type.RESULT) {
4484 final Data data =
4485 Data.parse(response.query().findChild("x", Namespace.DATA));
4486 data.submit(options);
4487 final Iq set = new Iq(Iq.Type.SET);
4488 set.setTo(conversation.getJid().asBareJid());
4489 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
4490 sendIqPacket(
4491 account,
4492 set,
4493 packet -> {
4494 if (callback != null) {
4495 if (packet.getType() == Iq.Type.RESULT) {
4496 callback.onPushSucceeded();
4497 } else {
4498 Log.d(Config.LOGTAG, "failed: " + packet.toString());
4499 callback.onPushFailed();
4500 }
4501 }
4502 });
4503 } else {
4504 if (callback != null) {
4505 callback.onPushFailed();
4506 }
4507 }
4508 });
4509 }
4510
4511 public void pushSubjectToConference(final Conversation conference, final String subject) {
4512 final var packet =
4513 this.getMessageGenerator()
4514 .conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4515 this.sendMessagePacket(conference.getAccount(), packet);
4516 }
4517
4518 public void changeAffiliationInConference(
4519 final Conversation conference,
4520 Jid user,
4521 final MucOptions.Affiliation affiliation,
4522 final OnAffiliationChanged callback) {
4523 final Jid jid = user.asBareJid();
4524 final Iq request =
4525 this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4526 sendIqPacket(
4527 conference.getAccount(),
4528 request,
4529 (response) -> {
4530 if (response.getType() == Iq.Type.RESULT) {
4531 final var mucOptions = conference.getMucOptions();
4532 mucOptions.changeAffiliation(jid, affiliation);
4533 getAvatarService().clear(mucOptions);
4534 if (callback != null) {
4535 callback.onAffiliationChangedSuccessful(jid);
4536 } else {
4537 Log.d(
4538 Config.LOGTAG,
4539 "changed affiliation of " + user + " to " + affiliation);
4540 }
4541 } else if (callback != null) {
4542 callback.onAffiliationChangeFailed(
4543 jid, R.string.could_not_change_affiliation);
4544 } else {
4545 Log.d(Config.LOGTAG, "unable to change affiliation");
4546 }
4547 });
4548 }
4549
4550 public void changeRoleInConference(
4551 final Conversation conference, final String nick, MucOptions.Role role) {
4552 final var account = conference.getAccount();
4553 final Iq request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4554 sendIqPacket(
4555 account,
4556 request,
4557 (packet) -> {
4558 if (packet.getType() != Iq.Type.RESULT) {
4559 Log.d(
4560 Config.LOGTAG,
4561 account.getJid().asBareJid() + " unable to change role of " + nick);
4562 }
4563 });
4564 }
4565
4566 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4567 final Iq request = new Iq(Iq.Type.SET);
4568 request.setTo(conversation.getJid().asBareJid());
4569 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4570 sendIqPacket(
4571 conversation.getAccount(),
4572 request,
4573 response -> {
4574 if (response.getType() == Iq.Type.RESULT) {
4575 if (callback != null) {
4576 callback.onRoomDestroySucceeded();
4577 }
4578 } else if (response.getType() == Iq.Type.ERROR) {
4579 if (callback != null) {
4580 callback.onRoomDestroyFailed();
4581 }
4582 }
4583 });
4584 }
4585
4586 private void disconnect(final Account account, boolean force) {
4587 final XmppConnection connection = account.getXmppConnection();
4588 if (connection == null) {
4589 return;
4590 }
4591 if (!force) {
4592 final List<Conversation> conversations = getConversations();
4593 for (Conversation conversation : conversations) {
4594 if (conversation.getAccount() == account) {
4595 if (conversation.getMode() == Conversation.MODE_MULTI) {
4596 leaveMuc(conversation, true);
4597 }
4598 }
4599 }
4600 sendOfflinePresence(account);
4601 }
4602 connection.disconnect(force);
4603 }
4604
4605 @Override
4606 public IBinder onBind(Intent intent) {
4607 return mBinder;
4608 }
4609
4610 public void updateMessage(Message message) {
4611 updateMessage(message, true);
4612 }
4613
4614 public void updateMessage(Message message, boolean includeBody) {
4615 databaseBackend.updateMessage(message, includeBody);
4616 updateConversationUi();
4617 }
4618
4619 public void createMessageAsync(final Message message) {
4620 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4621 }
4622
4623 public void updateMessage(Message message, String uuid) {
4624 if (!databaseBackend.updateMessage(message, uuid)) {
4625 Log.e(Config.LOGTAG, "error updated message in DB after edit");
4626 }
4627 updateConversationUi();
4628 }
4629
4630 public void syncDirtyContacts(Account account) {
4631 for (Contact contact : account.getRoster().getContacts()) {
4632 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
4633 pushContactToServer(contact);
4634 }
4635 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
4636 deleteContactOnServer(contact);
4637 }
4638 }
4639 }
4640
4641 public void createContact(final Contact contact, final boolean autoGrant) {
4642 createContact(contact, autoGrant, null);
4643 }
4644
4645 public void createContact(
4646 final Contact contact, final boolean autoGrant, final String preAuth) {
4647 if (autoGrant) {
4648 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4649 contact.setOption(Contact.Options.ASKING);
4650 }
4651 pushContactToServer(contact, preAuth);
4652 }
4653
4654 public void pushContactToServer(final Contact contact) {
4655 pushContactToServer(contact, null);
4656 }
4657
4658 private void pushContactToServer(final Contact contact, final String preAuth) {
4659 contact.resetOption(Contact.Options.DIRTY_DELETE);
4660 contact.setOption(Contact.Options.DIRTY_PUSH);
4661 final Account account = contact.getAccount();
4662 if (account.getStatus() == Account.State.ONLINE) {
4663 final boolean ask = contact.getOption(Contact.Options.ASKING);
4664 final boolean sendUpdates =
4665 contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
4666 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
4667 final Iq iq = new Iq(Iq.Type.SET);
4668 iq.query(Namespace.ROSTER).addChild(contact.asElement());
4669 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4670 if (sendUpdates) {
4671 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
4672 }
4673 if (ask) {
4674 sendPresencePacket(
4675 account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
4676 }
4677 } else {
4678 syncRoster(contact.getAccount());
4679 }
4680 }
4681
4682 public void publishMucAvatar(
4683 final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4684 new Thread(
4685 () -> {
4686 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4687 final int size = Config.AVATAR_SIZE;
4688 final Avatar avatar =
4689 getFileBackend().getPepAvatar(image, size, format);
4690 if (avatar != null) {
4691 if (!getFileBackend().save(avatar)) {
4692 callback.onAvatarPublicationFailed(
4693 R.string.error_saving_avatar);
4694 return;
4695 }
4696 avatar.owner = conversation.getJid().asBareJid();
4697 publishMucAvatar(conversation, avatar, callback);
4698 } else {
4699 callback.onAvatarPublicationFailed(
4700 R.string.error_publish_avatar_converting);
4701 }
4702 })
4703 .start();
4704 }
4705
4706 public void publishAvatarAsync(
4707 final Account account,
4708 final Uri image,
4709 final boolean open,
4710 final OnAvatarPublication callback) {
4711 new Thread(() -> publishAvatar(account, image, open, callback)).start();
4712 }
4713
4714 private void publishAvatar(
4715 final Account account,
4716 final Uri image,
4717 final boolean open,
4718 final OnAvatarPublication callback) {
4719 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4720 final int size = Config.AVATAR_SIZE;
4721 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4722 if (avatar != null) {
4723 if (!getFileBackend().save(avatar)) {
4724 Log.d(Config.LOGTAG, "unable to save vcard");
4725 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4726 return;
4727 }
4728 publishAvatar(account, avatar, open, callback);
4729 } else {
4730 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4731 }
4732 }
4733
4734 private void publishMucAvatar(
4735 Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4736 final var account = conversation.getAccount();
4737 final Iq retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4738 sendIqPacket(
4739 account,
4740 retrieve,
4741 (response) -> {
4742 boolean itemNotFound =
4743 response.getType() == Iq.Type.ERROR
4744 && response.hasChild("error")
4745 && response.findChild("error").hasChild("item-not-found");
4746 if (response.getType() == Iq.Type.RESULT || itemNotFound) {
4747 Element vcard = response.findChild("vCard", "vcard-temp");
4748 if (vcard == null) {
4749 vcard = new Element("vCard", "vcard-temp");
4750 }
4751 Element photo = vcard.findChild("PHOTO");
4752 if (photo == null) {
4753 photo = vcard.addChild("PHOTO");
4754 }
4755 photo.clearChildren();
4756 photo.addChild("TYPE").setContent(avatar.type);
4757 photo.addChild("BINVAL").setContent(avatar.image);
4758 final Iq publication = new Iq(Iq.Type.SET);
4759 publication.setTo(conversation.getJid().asBareJid());
4760 publication.addChild(vcard);
4761 sendIqPacket(
4762 account,
4763 publication,
4764 (publicationResponse) -> {
4765 if (publicationResponse.getType() == Iq.Type.RESULT) {
4766 callback.onAvatarPublicationSucceeded();
4767 } else {
4768 Log.d(
4769 Config.LOGTAG,
4770 "failed to publish vcard "
4771 + publicationResponse.getErrorCondition());
4772 callback.onAvatarPublicationFailed(
4773 R.string.error_publish_avatar_server_reject);
4774 }
4775 });
4776 } else {
4777 Log.d(Config.LOGTAG, "failed to request vcard " + response);
4778 callback.onAvatarPublicationFailed(
4779 R.string.error_publish_avatar_no_server_support);
4780 }
4781 });
4782 }
4783
4784 public void publishAvatar(
4785 final Account account,
4786 final Avatar avatar,
4787 final boolean open,
4788 final OnAvatarPublication callback) {
4789 final Bundle options;
4790 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4791 options = open ? PublishOptions.openAccess() : PublishOptions.presenceAccess();
4792 } else {
4793 options = null;
4794 }
4795 publishAvatar(account, avatar, options, true, callback);
4796 }
4797
4798 public void publishAvatar(
4799 Account account,
4800 final Avatar avatar,
4801 final Bundle options,
4802 final boolean retry,
4803 final OnAvatarPublication callback) {
4804 Log.d(
4805 Config.LOGTAG,
4806 account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4807 final Iq packet = this.mIqGenerator.publishAvatar(avatar, options);
4808 this.sendIqPacket(
4809 account,
4810 packet,
4811 result -> {
4812 if (result.getType() == Iq.Type.RESULT) {
4813 publishAvatarMetadata(account, avatar, options, true, callback);
4814 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4815 pushNodeConfiguration(
4816 account,
4817 Namespace.AVATAR_DATA,
4818 options,
4819 new OnConfigurationPushed() {
4820 @Override
4821 public void onPushSucceeded() {
4822 Log.d(
4823 Config.LOGTAG,
4824 account.getJid().asBareJid()
4825 + ": changed node configuration for avatar"
4826 + " node");
4827 publishAvatar(account, avatar, options, false, callback);
4828 }
4829
4830 @Override
4831 public void onPushFailed() {
4832 Log.d(
4833 Config.LOGTAG,
4834 account.getJid().asBareJid()
4835 + ": unable to change node configuration"
4836 + " for avatar node");
4837 publishAvatar(account, avatar, null, false, callback);
4838 }
4839 });
4840 } else {
4841 Element error = result.findChild("error");
4842 Log.d(
4843 Config.LOGTAG,
4844 account.getJid().asBareJid()
4845 + ": server rejected avatar "
4846 + (avatar.size / 1024)
4847 + "KiB "
4848 + (error != null ? error.toString() : ""));
4849 if (callback != null) {
4850 callback.onAvatarPublicationFailed(
4851 R.string.error_publish_avatar_server_reject);
4852 }
4853 }
4854 });
4855 }
4856
4857 public void publishAvatarMetadata(
4858 Account account,
4859 final Avatar avatar,
4860 final Bundle options,
4861 final boolean retry,
4862 final OnAvatarPublication callback) {
4863 final Iq packet =
4864 XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4865 sendIqPacket(
4866 account,
4867 packet,
4868 result -> {
4869 if (result.getType() == Iq.Type.RESULT) {
4870 if (account.setAvatar(avatar.getFilename())) {
4871 getAvatarService().clear(account);
4872 databaseBackend.updateAccount(account);
4873 notifyAccountAvatarHasChanged(account);
4874 }
4875 Log.d(
4876 Config.LOGTAG,
4877 account.getJid().asBareJid()
4878 + ": published avatar "
4879 + (avatar.size / 1024)
4880 + "KiB");
4881 if (callback != null) {
4882 callback.onAvatarPublicationSucceeded();
4883 }
4884 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4885 pushNodeConfiguration(
4886 account,
4887 Namespace.AVATAR_METADATA,
4888 options,
4889 new OnConfigurationPushed() {
4890 @Override
4891 public void onPushSucceeded() {
4892 Log.d(
4893 Config.LOGTAG,
4894 account.getJid().asBareJid()
4895 + ": changed node configuration for avatar"
4896 + " meta data node");
4897 publishAvatarMetadata(
4898 account, avatar, options, false, callback);
4899 }
4900
4901 @Override
4902 public void onPushFailed() {
4903 Log.d(
4904 Config.LOGTAG,
4905 account.getJid().asBareJid()
4906 + ": unable to change node configuration"
4907 + " for avatar meta data node");
4908 publishAvatarMetadata(
4909 account, avatar, null, false, callback);
4910 }
4911 });
4912 } else {
4913 if (callback != null) {
4914 callback.onAvatarPublicationFailed(
4915 R.string.error_publish_avatar_server_reject);
4916 }
4917 }
4918 });
4919 }
4920
4921 public void republishAvatarIfNeeded(final Account account) {
4922 if (account.getAxolotlService().isPepBroken()) {
4923 Log.d(
4924 Config.LOGTAG,
4925 account.getJid().asBareJid()
4926 + ": skipping republication of avatar because pep is broken");
4927 return;
4928 }
4929 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4930 this.sendIqPacket(
4931 account,
4932 packet,
4933 new Consumer<Iq>() {
4934
4935 private Avatar parseAvatar(final Iq packet) {
4936 final var pubsub = packet.getExtension(PubSub.class);
4937 if (pubsub == null) {
4938 return null;
4939 }
4940 final var items = pubsub.getItems();
4941 if (items == null) {
4942 return null;
4943 }
4944 final var item = items.getFirstItemWithId(Metadata.class);
4945 if (item == null) {
4946 return null;
4947 }
4948 return Avatar.parseMetadata(item.getKey(), item.getValue());
4949 }
4950
4951 private boolean errorIsItemNotFound(Iq packet) {
4952 Element error = packet.findChild("error");
4953 return packet.getType() == Iq.Type.ERROR
4954 && error != null
4955 && error.hasChild("item-not-found");
4956 }
4957
4958 @Override
4959 public void accept(final Iq packet) {
4960 if (packet.getType() == Iq.Type.RESULT || errorIsItemNotFound(packet)) {
4961 final Avatar serverAvatar = parseAvatar(packet);
4962 if (serverAvatar == null && account.getAvatar() != null) {
4963 final Avatar avatar =
4964 fileBackend.getStoredPepAvatar(account.getAvatar());
4965 if (avatar != null) {
4966 Log.d(
4967 Config.LOGTAG,
4968 account.getJid().asBareJid()
4969 + ": avatar on server was null. republishing");
4970 // publishing as 'open' - old server (that requires
4971 // republication) likely doesn't support access models anyway
4972 publishAvatar(
4973 account,
4974 fileBackend.getStoredPepAvatar(account.getAvatar()),
4975 true,
4976 null);
4977 } else {
4978 Log.e(
4979 Config.LOGTAG,
4980 account.getJid().asBareJid()
4981 + ": error rereading avatar");
4982 }
4983 }
4984 }
4985 }
4986 });
4987 }
4988
4989 public void cancelAvatarFetches(final Account account) {
4990 synchronized (mInProgressAvatarFetches) {
4991 for (final Iterator<String> iterator = mInProgressAvatarFetches.iterator();
4992 iterator.hasNext(); ) {
4993 final String KEY = iterator.next();
4994 if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
4995 iterator.remove();
4996 }
4997 }
4998 }
4999 }
5000
5001 public void fetchAvatar(Account account, Avatar avatar) {
5002 fetchAvatar(account, avatar, null);
5003 }
5004
5005 public void fetchAvatar(
5006 Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
5007 final String KEY = generateFetchKey(account, avatar);
5008 synchronized (this.mInProgressAvatarFetches) {
5009 if (mInProgressAvatarFetches.add(KEY)) {
5010 switch (avatar.origin) {
5011 case PEP:
5012 this.mInProgressAvatarFetches.add(KEY);
5013 fetchAvatarPep(account, avatar, callback);
5014 break;
5015 case VCARD:
5016 this.mInProgressAvatarFetches.add(KEY);
5017 fetchAvatarVcard(account, avatar, callback);
5018 break;
5019 }
5020 } else if (avatar.origin == Avatar.Origin.PEP) {
5021 mOmittedPepAvatarFetches.add(KEY);
5022 } else {
5023 Log.d(
5024 Config.LOGTAG,
5025 account.getJid().asBareJid()
5026 + ": already fetching "
5027 + avatar.origin
5028 + " avatar for "
5029 + avatar.owner);
5030 }
5031 }
5032 }
5033
5034 private void fetchAvatarPep(
5035 final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
5036 final Iq packet = this.mIqGenerator.retrievePepAvatar(avatar);
5037 sendIqPacket(
5038 account,
5039 packet,
5040 (result) -> {
5041 synchronized (mInProgressAvatarFetches) {
5042 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
5043 }
5044 final String ERROR =
5045 account.getJid().asBareJid()
5046 + ": fetching avatar for "
5047 + avatar.owner
5048 + " failed ";
5049 if (result.getType() == Iq.Type.RESULT) {
5050 avatar.image = IqParser.avatarData(result);
5051 if (avatar.image != null) {
5052 if (getFileBackend().save(avatar)) {
5053 if (account.getJid().asBareJid().equals(avatar.owner)) {
5054 if (account.setAvatar(avatar.getFilename())) {
5055 databaseBackend.updateAccount(account);
5056 }
5057 getAvatarService().clear(account);
5058 updateConversationUi();
5059 updateAccountUi();
5060 } else {
5061 final Contact contact =
5062 account.getRoster().getContact(avatar.owner);
5063 contact.setAvatar(avatar);
5064 syncRoster(account);
5065 getAvatarService().clear(contact);
5066 updateConversationUi();
5067 updateRosterUi();
5068 }
5069 if (callback != null) {
5070 callback.success(avatar);
5071 }
5072 Log.d(
5073 Config.LOGTAG,
5074 account.getJid().asBareJid()
5075 + ": successfully fetched pep avatar for "
5076 + avatar.owner);
5077 return;
5078 }
5079 } else {
5080
5081 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
5082 }
5083 } else {
5084 Element error = result.findChild("error");
5085 if (error == null) {
5086 Log.d(Config.LOGTAG, ERROR + "(server error)");
5087 } else {
5088 Log.d(Config.LOGTAG, ERROR + error.toString());
5089 }
5090 }
5091 if (callback != null) {
5092 callback.error(0, null);
5093 }
5094 });
5095 }
5096
5097 private void fetchAvatarVcard(
5098 final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
5099 final Iq packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
5100 this.sendIqPacket(
5101 account,
5102 packet,
5103 response -> {
5104 final boolean previouslyOmittedPepFetch;
5105 synchronized (mInProgressAvatarFetches) {
5106 final String KEY = generateFetchKey(account, avatar);
5107 mInProgressAvatarFetches.remove(KEY);
5108 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
5109 }
5110 if (response.getType() == Iq.Type.RESULT) {
5111 Element vCard = response.findChild("vCard", "vcard-temp");
5112 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
5113 String image = photo != null ? photo.findChildContent("BINVAL") : null;
5114 if (image != null) {
5115 avatar.image = image;
5116 if (getFileBackend().save(avatar)) {
5117 Log.d(
5118 Config.LOGTAG,
5119 account.getJid().asBareJid()
5120 + ": successfully fetched vCard avatar for "
5121 + avatar.owner
5122 + " omittedPep="
5123 + previouslyOmittedPepFetch);
5124 if (avatar.owner.isBareJid()) {
5125 if (account.getJid().asBareJid().equals(avatar.owner)
5126 && account.getAvatar() == null) {
5127 Log.d(
5128 Config.LOGTAG,
5129 account.getJid().asBareJid()
5130 + ": had no avatar. replacing with vcard");
5131 account.setAvatar(avatar.getFilename());
5132 databaseBackend.updateAccount(account);
5133 getAvatarService().clear(account);
5134 updateAccountUi();
5135 } else {
5136 final Contact contact =
5137 account.getRoster().getContact(avatar.owner);
5138 contact.setAvatar(avatar, previouslyOmittedPepFetch);
5139 syncRoster(account);
5140 getAvatarService().clear(contact);
5141 updateRosterUi();
5142 }
5143 updateConversationUi();
5144 } else {
5145 Conversation conversation =
5146 find(account, avatar.owner.asBareJid());
5147 if (conversation != null
5148 && conversation.getMode() == Conversation.MODE_MULTI) {
5149 MucOptions.User user =
5150 conversation
5151 .getMucOptions()
5152 .findUserByFullJid(avatar.owner);
5153 if (user != null) {
5154 if (user.setAvatar(avatar)) {
5155 getAvatarService().clear(user);
5156 updateConversationUi();
5157 updateMucRosterUi();
5158 }
5159 if (user.getRealJid() != null) {
5160 Contact contact =
5161 account.getRoster()
5162 .getContact(user.getRealJid());
5163 contact.setAvatar(avatar);
5164 syncRoster(account);
5165 getAvatarService().clear(contact);
5166 updateRosterUi();
5167 }
5168 }
5169 }
5170 }
5171 }
5172 }
5173 }
5174 });
5175 }
5176
5177 public void checkForAvatar(final Account account, final UiCallback<Avatar> callback) {
5178 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
5179 this.sendIqPacket(
5180 account,
5181 packet,
5182 response -> {
5183 if (response.getType() != Iq.Type.RESULT) {
5184 callback.error(0, null);
5185 }
5186 final var pubsub = packet.getExtension(PubSub.class);
5187 if (pubsub == null) {
5188 callback.error(0, null);
5189 return;
5190 }
5191 final var items = pubsub.getItems();
5192 if (items == null) {
5193 callback.error(0, null);
5194 return;
5195 }
5196 final var item = items.getFirstItemWithId(Metadata.class);
5197 if (item == null) {
5198 callback.error(0, null);
5199 return;
5200 }
5201 final var avatar = Avatar.parseMetadata(item.getKey(), item.getValue());
5202 if (avatar == null) {
5203 callback.error(0, null);
5204 return;
5205 }
5206 avatar.owner = account.getJid().asBareJid();
5207 if (fileBackend.isAvatarCached(avatar)) {
5208 if (account.setAvatar(avatar.getFilename())) {
5209 databaseBackend.updateAccount(account);
5210 }
5211 getAvatarService().clear(account);
5212 callback.success(avatar);
5213 } else {
5214 fetchAvatarPep(account, avatar, callback);
5215 }
5216 });
5217 }
5218
5219 public void notifyAccountAvatarHasChanged(final Account account) {
5220 final XmppConnection connection = account.getXmppConnection();
5221 if (connection != null && connection.getFeatures().bookmarksConversion()) {
5222 Log.d(
5223 Config.LOGTAG,
5224 account.getJid().asBareJid()
5225 + ": avatar changed. resending presence to online group chats");
5226 for (Conversation conversation : conversations) {
5227 if (conversation.getAccount() == account
5228 && conversation.getMode() == Conversational.MODE_MULTI) {
5229 final MucOptions mucOptions = conversation.getMucOptions();
5230 if (mucOptions.online()) {
5231 final var packet =
5232 mPresenceGenerator.selfPresence(
5233 account, Presence.Status.ONLINE, mucOptions.nonanonymous());
5234 packet.setTo(mucOptions.getSelf().getFullJid());
5235 connection.sendPresencePacket(packet);
5236 }
5237 }
5238 }
5239 }
5240 }
5241
5242 public void deleteContactOnServer(Contact contact) {
5243 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
5244 contact.resetOption(Contact.Options.DIRTY_PUSH);
5245 contact.setOption(Contact.Options.DIRTY_DELETE);
5246 Account account = contact.getAccount();
5247 if (account.getStatus() == Account.State.ONLINE) {
5248 final Iq iq = new Iq(Iq.Type.SET);
5249 Element item = iq.query(Namespace.ROSTER).addChild("item");
5250 item.setAttribute("jid", contact.getJid());
5251 item.setAttribute("subscription", "remove");
5252 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
5253 }
5254 }
5255
5256 public void updateConversation(final Conversation conversation) {
5257 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
5258 }
5259
5260 private void reconnectAccount(
5261 final Account account, final boolean force, final boolean interactive) {
5262 synchronized (account) {
5263 final XmppConnection existingConnection = account.getXmppConnection();
5264 final XmppConnection connection;
5265 if (existingConnection != null) {
5266 connection = existingConnection;
5267 } else if (account.isConnectionEnabled()) {
5268 connection = createConnection(account);
5269 account.setXmppConnection(connection);
5270 } else {
5271 return;
5272 }
5273 final boolean hasInternet = hasInternetConnection();
5274 if (account.isConnectionEnabled() && hasInternet) {
5275 if (!force) {
5276 disconnect(account, false);
5277 }
5278 Thread thread = new Thread(connection);
5279 connection.setInteractive(interactive);
5280 connection.prepareNewConnection();
5281 connection.interrupt();
5282 thread.start();
5283 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
5284 } else {
5285 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
5286 account.getRoster().clearPresences();
5287 connection.resetEverything();
5288 final AxolotlService axolotlService = account.getAxolotlService();
5289 if (axolotlService != null) {
5290 axolotlService.resetBrokenness();
5291 }
5292 if (!hasInternet) {
5293 account.setStatus(Account.State.NO_INTERNET);
5294 }
5295 }
5296 }
5297 }
5298
5299 public void reconnectAccountInBackground(final Account account) {
5300 new Thread(() -> reconnectAccount(account, false, true)).start();
5301 }
5302
5303 public void invite(final Conversation conversation, final Jid contact) {
5304 Log.d(
5305 Config.LOGTAG,
5306 conversation.getAccount().getJid().asBareJid()
5307 + ": inviting "
5308 + contact
5309 + " to "
5310 + conversation.getJid().asBareJid());
5311 final MucOptions.User user =
5312 conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
5313 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
5314 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
5315 }
5316 final var packet = mMessageGenerator.invite(conversation, contact);
5317 sendMessagePacket(conversation.getAccount(), packet);
5318 }
5319
5320 public void directInvite(Conversation conversation, Jid jid) {
5321 final var packet = mMessageGenerator.directInvite(conversation, jid);
5322 sendMessagePacket(conversation.getAccount(), packet);
5323 }
5324
5325 public void resetSendingToWaiting(Account account) {
5326 for (Conversation conversation : getConversations()) {
5327 if (conversation.getAccount() == account) {
5328 conversation.findUnsentTextMessages(
5329 message -> markMessage(message, Message.STATUS_WAITING));
5330 }
5331 }
5332 }
5333
5334 public Message markMessage(
5335 final Account account, final Jid recipient, final String uuid, final int status) {
5336 return markMessage(account, recipient, uuid, status, null);
5337 }
5338
5339 public Message markMessage(
5340 final Account account,
5341 final Jid recipient,
5342 final String uuid,
5343 final int status,
5344 String errorMessage) {
5345 if (uuid == null) {
5346 return null;
5347 }
5348 for (Conversation conversation : getConversations()) {
5349 if (conversation.getJid().asBareJid().equals(recipient)
5350 && conversation.getAccount() == account) {
5351 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
5352 if (message != null) {
5353 markMessage(message, status, errorMessage);
5354 }
5355 return message;
5356 }
5357 }
5358 return null;
5359 }
5360
5361 public boolean markMessage(
5362 final Conversation conversation,
5363 final String uuid,
5364 final int status,
5365 final String serverMessageId) {
5366 return markMessage(conversation, uuid, status, serverMessageId, null);
5367 }
5368
5369 public boolean markMessage(
5370 final Conversation conversation,
5371 final String uuid,
5372 final int status,
5373 final String serverMessageId,
5374 final LocalizedContent body) {
5375 if (uuid == null) {
5376 return false;
5377 } else {
5378 final Message message = conversation.findSentMessageWithUuid(uuid);
5379 if (message != null) {
5380 if (message.getServerMsgId() == null) {
5381 message.setServerMsgId(serverMessageId);
5382 }
5383 if (message.getEncryption() == Message.ENCRYPTION_NONE
5384 && message.isTypeText()
5385 && isBodyModified(message, body)) {
5386 message.setBody(body.content);
5387 if (body.count > 1) {
5388 message.setBodyLanguage(body.language);
5389 }
5390 markMessage(message, status, null, true);
5391 } else {
5392 markMessage(message, status);
5393 }
5394 return true;
5395 } else {
5396 return false;
5397 }
5398 }
5399 }
5400
5401 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
5402 if (body == null || body.content == null) {
5403 return false;
5404 }
5405 return !body.content.equals(message.getBody());
5406 }
5407
5408 public void markMessage(Message message, int status) {
5409 markMessage(message, status, null);
5410 }
5411
5412 public void markMessage(final Message message, final int status, final String errorMessage) {
5413 markMessage(message, status, errorMessage, false);
5414 }
5415
5416 public void markMessage(
5417 final Message message,
5418 final int status,
5419 final String errorMessage,
5420 final boolean includeBody) {
5421 final int oldStatus = message.getStatus();
5422 if (status == Message.STATUS_SEND_FAILED
5423 && (oldStatus == Message.STATUS_SEND_RECEIVED
5424 || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
5425 return;
5426 }
5427 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
5428 return;
5429 }
5430 message.setErrorMessage(errorMessage);
5431 message.setStatus(status);
5432 databaseBackend.updateMessage(message, includeBody);
5433 updateConversationUi();
5434 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
5435 mNotificationService.pushFailedDelivery(message);
5436 }
5437 }
5438
5439 private SharedPreferences getPreferences() {
5440 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
5441 }
5442
5443 public long getAutomaticMessageDeletionDate() {
5444 final long timeout =
5445 getLongPreference(
5446 AppSettings.AUTOMATIC_MESSAGE_DELETION,
5447 R.integer.automatic_message_deletion);
5448 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
5449 }
5450
5451 public long getLongPreference(String name, @IntegerRes int res) {
5452 long defaultValue = getResources().getInteger(res);
5453 try {
5454 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
5455 } catch (NumberFormatException e) {
5456 return defaultValue;
5457 }
5458 }
5459
5460 public boolean getBooleanPreference(String name, @BoolRes int res) {
5461 return getPreferences().getBoolean(name, getResources().getBoolean(res));
5462 }
5463
5464 public boolean confirmMessages() {
5465 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
5466 }
5467
5468 public boolean allowMessageCorrection() {
5469 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
5470 }
5471
5472 public boolean sendChatStates() {
5473 return getBooleanPreference("chat_states", R.bool.chat_states);
5474 }
5475
5476 public boolean useTorToConnect() {
5477 return QuickConversationsService.isConversations()
5478 && getBooleanPreference("use_tor", R.bool.use_tor);
5479 }
5480
5481 public boolean broadcastLastActivity() {
5482 return getBooleanPreference(AppSettings.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
5483 }
5484
5485 public int unreadCount() {
5486 int count = 0;
5487 for (Conversation conversation : getConversations()) {
5488 count += conversation.unreadCount();
5489 }
5490 return count;
5491 }
5492
5493 private <T> List<T> threadSafeList(Set<T> set) {
5494 synchronized (LISTENER_LOCK) {
5495 return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
5496 }
5497 }
5498
5499 public void showErrorToastInUi(int resId) {
5500 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
5501 listener.onShowErrorToast(resId);
5502 }
5503 }
5504
5505 public void updateConversationUi() {
5506 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
5507 listener.onConversationUpdate();
5508 }
5509 }
5510
5511 public void notifyJingleRtpConnectionUpdate(
5512 final Account account,
5513 final Jid with,
5514 final String sessionId,
5515 final RtpEndUserState state) {
5516 for (OnJingleRtpConnectionUpdate listener :
5517 threadSafeList(this.onJingleRtpConnectionUpdate)) {
5518 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
5519 }
5520 }
5521
5522 public void notifyJingleRtpConnectionUpdate(
5523 CallIntegration.AudioDevice selectedAudioDevice,
5524 Set<CallIntegration.AudioDevice> availableAudioDevices) {
5525 for (OnJingleRtpConnectionUpdate listener :
5526 threadSafeList(this.onJingleRtpConnectionUpdate)) {
5527 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
5528 }
5529 }
5530
5531 public void updateAccountUi() {
5532 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
5533 listener.onAccountUpdate();
5534 }
5535 }
5536
5537 public void updateRosterUi() {
5538 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
5539 listener.onRosterUpdate();
5540 }
5541 }
5542
5543 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
5544 if (mOnCaptchaRequested.size() > 0) {
5545 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
5546 Bitmap scaled =
5547 Bitmap.createScaledBitmap(
5548 captcha,
5549 (int) (captcha.getWidth() * metrics.scaledDensity),
5550 (int) (captcha.getHeight() * metrics.scaledDensity),
5551 false);
5552 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
5553 listener.onCaptchaRequested(account, id, data, scaled);
5554 }
5555 return true;
5556 }
5557 return false;
5558 }
5559
5560 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
5561 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
5562 listener.OnUpdateBlocklist(status);
5563 }
5564 }
5565
5566 public void updateMucRosterUi() {
5567 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
5568 listener.onMucRosterUpdate();
5569 }
5570 }
5571
5572 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
5573 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
5574 listener.onKeyStatusUpdated(report);
5575 }
5576 }
5577
5578 public Account findAccountByJid(final Jid jid) {
5579 for (final Account account : this.accounts) {
5580 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
5581 return account;
5582 }
5583 }
5584 return null;
5585 }
5586
5587 public Account findAccountByUuid(final String uuid) {
5588 for (Account account : this.accounts) {
5589 if (account.getUuid().equals(uuid)) {
5590 return account;
5591 }
5592 }
5593 return null;
5594 }
5595
5596 public Conversation findConversationByUuid(String uuid) {
5597 for (Conversation conversation : getConversations()) {
5598 if (conversation.getUuid().equals(uuid)) {
5599 return conversation;
5600 }
5601 }
5602 return null;
5603 }
5604
5605 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
5606 List<Conversation> findings = new ArrayList<>();
5607 for (Conversation c : getConversations()) {
5608 if (c.getAccount().isEnabled()
5609 && c.getJid().asBareJid().equals(xmppUri.getJid())
5610 && ((c.getMode() == Conversational.MODE_MULTI)
5611 == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
5612 findings.add(c);
5613 }
5614 }
5615 return findings.size() == 1 ? findings.get(0) : null;
5616 }
5617
5618 public boolean markRead(final Conversation conversation, boolean dismiss) {
5619 return markRead(conversation, null, dismiss).size() > 0;
5620 }
5621
5622 public void markRead(final Conversation conversation) {
5623 markRead(conversation, null, true);
5624 }
5625
5626 public List<Message> markRead(
5627 final Conversation conversation, String upToUuid, boolean dismiss) {
5628 if (dismiss) {
5629 mNotificationService.clear(conversation);
5630 }
5631 final List<Message> readMessages = conversation.markRead(upToUuid);
5632 if (readMessages.size() > 0) {
5633 Runnable runnable =
5634 () -> {
5635 for (Message message : readMessages) {
5636 databaseBackend.updateMessage(message, false);
5637 }
5638 };
5639 mDatabaseWriterExecutor.execute(runnable);
5640 updateConversationUi();
5641 updateUnreadCountBadge();
5642 return readMessages;
5643 } else {
5644 return readMessages;
5645 }
5646 }
5647
5648 public synchronized void updateUnreadCountBadge() {
5649 int count = unreadCount();
5650 if (unreadCount != count) {
5651 Log.d(Config.LOGTAG, "update unread count to " + count);
5652 if (count > 0) {
5653 ShortcutBadger.applyCount(getApplicationContext(), count);
5654 } else {
5655 ShortcutBadger.removeCount(getApplicationContext());
5656 }
5657 unreadCount = count;
5658 }
5659 }
5660
5661 public void sendReadMarker(final Conversation conversation, final String upToUuid) {
5662 final boolean isPrivateAndNonAnonymousMuc =
5663 conversation.getMode() == Conversation.MODE_MULTI
5664 && conversation.isPrivateAndNonAnonymous();
5665 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
5666 if (readMessages.isEmpty()) {
5667 return;
5668 }
5669 final var account = conversation.getAccount();
5670 final var connection = account.getXmppConnection();
5671 updateConversationUi();
5672 final var last =
5673 Iterables.getLast(
5674 Collections2.filter(
5675 readMessages,
5676 m ->
5677 !m.isPrivateMessage()
5678 && m.getStatus() == Message.STATUS_RECEIVED),
5679 null);
5680 if (last == null) {
5681 return;
5682 }
5683
5684 final boolean sendDisplayedMarker =
5685 confirmMessages()
5686 && (last.trusted() || isPrivateAndNonAnonymousMuc)
5687 && last.getRemoteMsgId() != null
5688 && (last.markable || isPrivateAndNonAnonymousMuc);
5689 final boolean serverAssist =
5690 connection != null && connection.getFeatures().mdsServerAssist();
5691
5692 final String stanzaId = last.getServerMsgId();
5693
5694 if (sendDisplayedMarker && serverAssist) {
5695 final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5696 final var packet = mMessageGenerator.confirm(last);
5697 packet.addChild(mdsDisplayed);
5698 if (!last.isPrivateMessage()) {
5699 packet.setTo(packet.getTo().asBareJid());
5700 }
5701 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server assisted " + packet);
5702 this.sendMessagePacket(account, packet);
5703 } else {
5704 publishMds(last);
5705 // read markers will be sent after MDS to flush the CSI stanza queue
5706 if (sendDisplayedMarker) {
5707 Log.d(
5708 Config.LOGTAG,
5709 conversation.getAccount().getJid().asBareJid()
5710 + ": sending displayed marker to "
5711 + last.getCounterpart().toString());
5712 final var packet = mMessageGenerator.confirm(last);
5713 this.sendMessagePacket(account, packet);
5714 }
5715 }
5716 }
5717
5718 private void publishMds(@Nullable final Message message) {
5719 final String stanzaId = message == null ? null : message.getServerMsgId();
5720 if (Strings.isNullOrEmpty(stanzaId)) {
5721 return;
5722 }
5723 final Conversation conversation;
5724 final var conversational = message.getConversation();
5725 if (conversational instanceof Conversation c) {
5726 conversation = c;
5727 } else {
5728 return;
5729 }
5730 final var account = conversation.getAccount();
5731 final var connection = account.getXmppConnection();
5732 if (connection == null || !connection.getFeatures().mds()) {
5733 return;
5734 }
5735 final Jid itemId;
5736 if (message.isPrivateMessage()) {
5737 itemId = message.getCounterpart();
5738 } else {
5739 itemId = conversation.getJid().asBareJid();
5740 }
5741 Log.d(Config.LOGTAG, "publishing mds for " + itemId + "/" + stanzaId);
5742 publishMds(account, itemId, stanzaId, conversation);
5743 }
5744
5745 private void publishMds(
5746 final Account account,
5747 final Jid itemId,
5748 final String stanzaId,
5749 final Conversation conversation) {
5750 final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5751 pushNodeAndEnforcePublishOptions(
5752 account,
5753 Namespace.MDS_DISPLAYED,
5754 item,
5755 itemId.toString(),
5756 PublishOptions.persistentWhitelistAccessMaxItems());
5757 }
5758
5759 public boolean sendReactions(final Message message, final Collection<String> reactions) {
5760 if (message.getConversation() instanceof Conversation conversation) {
5761 final var isPrivateMessage = message.isPrivateMessage();
5762 final Jid reactTo;
5763 final boolean typeGroupChat;
5764 final String reactToId;
5765 final Collection<Reaction> combinedReactions;
5766 if (conversation.getMode() == Conversational.MODE_MULTI && !isPrivateMessage) {
5767 final var mucOptions = conversation.getMucOptions();
5768 if (!mucOptions.participating()) {
5769 Log.e(Config.LOGTAG, "not participating in MUC");
5770 return false;
5771 }
5772 final var self = mucOptions.getSelf();
5773 final String occupantId = self.getOccupantId();
5774 if (Strings.isNullOrEmpty(occupantId)) {
5775 Log.e(Config.LOGTAG, "occupant id not found for reaction in MUC");
5776 return false;
5777 }
5778 final var existingRaw =
5779 ImmutableSet.copyOf(
5780 Collections2.transform(message.getReactions(), r -> r.reaction));
5781 final var reactionsAsExistingVariants =
5782 ImmutableSet.copyOf(
5783 Collections2.transform(
5784 reactions, r -> Emoticons.existingVariant(r, existingRaw)));
5785 if (!reactions.equals(reactionsAsExistingVariants)) {
5786 Log.d(Config.LOGTAG, "modified reactions to existing variants");
5787 }
5788 reactToId = message.getServerMsgId();
5789 reactTo = conversation.getJid().asBareJid();
5790 typeGroupChat = true;
5791 combinedReactions =
5792 Reaction.withOccupantId(
5793 message.getReactions(),
5794 reactionsAsExistingVariants,
5795 false,
5796 self.getFullJid(),
5797 conversation.getAccount().getJid(),
5798 occupantId);
5799 } else {
5800 if (message.isCarbon() || message.getStatus() == Message.STATUS_RECEIVED) {
5801 reactToId = message.getRemoteMsgId();
5802 } else {
5803 reactToId = message.getUuid();
5804 }
5805 typeGroupChat = false;
5806 if (isPrivateMessage) {
5807 reactTo = message.getCounterpart();
5808 } else {
5809 reactTo = conversation.getJid().asBareJid();
5810 }
5811 combinedReactions =
5812 Reaction.withFrom(
5813 message.getReactions(),
5814 reactions,
5815 false,
5816 conversation.getAccount().getJid());
5817 }
5818 if (reactTo == null || Strings.isNullOrEmpty(reactToId)) {
5819 Log.e(Config.LOGTAG, "could not find id to react to");
5820 return false;
5821 }
5822 final var reactionMessage =
5823 mMessageGenerator.reaction(reactTo, typeGroupChat, reactToId, reactions);
5824 sendMessagePacket(conversation.getAccount(), reactionMessage);
5825 message.setReactions(combinedReactions);
5826 updateMessage(message, false);
5827 return true;
5828 } else {
5829 return false;
5830 }
5831 }
5832
5833 public MemorizingTrustManager getMemorizingTrustManager() {
5834 return this.mMemorizingTrustManager;
5835 }
5836
5837 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
5838 this.mMemorizingTrustManager = trustManager;
5839 }
5840
5841 public void updateMemorizingTrustManager() {
5842 final MemorizingTrustManager trustManager;
5843 if (appSettings.isTrustSystemCAStore()) {
5844 trustManager = new MemorizingTrustManager(getApplicationContext());
5845 } else {
5846 trustManager = new MemorizingTrustManager(getApplicationContext(), null);
5847 }
5848 setMemorizingTrustManager(trustManager);
5849 }
5850
5851 public LruCache<String, Bitmap> getBitmapCache() {
5852 return this.mBitmapCache;
5853 }
5854
5855 public Collection<String> getKnownHosts() {
5856 final Set<String> hosts = new HashSet<>();
5857 for (final Account account : getAccounts()) {
5858 hosts.add(account.getServer());
5859 for (final Contact contact : account.getRoster().getContacts()) {
5860 if (contact.showInRoster()) {
5861 final String server = contact.getServer();
5862 if (server != null) {
5863 hosts.add(server);
5864 }
5865 }
5866 }
5867 }
5868 if (Config.QUICKSY_DOMAIN != null) {
5869 hosts.remove(
5870 Config.QUICKSY_DOMAIN
5871 .toString()); // we only want to show this when we type a e164
5872 // number
5873 }
5874 if (Config.MAGIC_CREATE_DOMAIN != null) {
5875 hosts.add(Config.MAGIC_CREATE_DOMAIN);
5876 }
5877 return hosts;
5878 }
5879
5880 public Collection<String> getKnownConferenceHosts() {
5881 final Set<String> mucServers = new HashSet<>();
5882 for (final Account account : accounts) {
5883 if (account.getXmppConnection() != null) {
5884 mucServers.addAll(account.getXmppConnection().getMucServers());
5885 for (final Bookmark bookmark : account.getBookmarks()) {
5886 final Jid jid = bookmark.getJid();
5887 final String s = jid == null ? null : jid.getDomain().toString();
5888 if (s != null) {
5889 mucServers.add(s);
5890 }
5891 }
5892 }
5893 }
5894 return mucServers;
5895 }
5896
5897 public void sendMessagePacket(
5898 final Account account,
5899 final im.conversations.android.xmpp.model.stanza.Message packet) {
5900 final XmppConnection connection = account.getXmppConnection();
5901 if (connection != null) {
5902 connection.sendMessagePacket(packet);
5903 }
5904 }
5905
5906 public void sendPresencePacket(
5907 final Account account,
5908 final im.conversations.android.xmpp.model.stanza.Presence packet) {
5909 final XmppConnection connection = account.getXmppConnection();
5910 if (connection != null) {
5911 connection.sendPresencePacket(packet);
5912 }
5913 }
5914
5915 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5916 final XmppConnection connection = account.getXmppConnection();
5917 if (connection == null) {
5918 return;
5919 }
5920 connection.sendCreateAccountWithCaptchaPacket(id, data);
5921 }
5922
5923 public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback) {
5924 final XmppConnection connection = account.getXmppConnection();
5925 if (connection != null) {
5926 connection.sendIqPacket(packet, callback);
5927 } else if (callback != null) {
5928 callback.accept(Iq.TIMEOUT);
5929 }
5930 }
5931
5932 public void sendPresence(final Account account) {
5933 sendPresence(account, checkListeners() && broadcastLastActivity());
5934 }
5935
5936 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
5937 final Presence.Status status;
5938 if (manuallyChangePresence()) {
5939 status = account.getPresenceStatus();
5940 } else {
5941 status = getTargetPresence();
5942 }
5943 final var packet = mPresenceGenerator.selfPresence(account, status);
5944 if (mLastActivity > 0 && includeIdleTimestamp) {
5945 long since =
5946 Math.min(mLastActivity, System.currentTimeMillis()); // don't send future dates
5947 packet.addChild("idle", Namespace.IDLE)
5948 .setAttribute("since", AbstractGenerator.getTimestamp(since));
5949 }
5950 sendPresencePacket(account, packet);
5951 }
5952
5953 private void deactivateGracePeriod() {
5954 for (Account account : getAccounts()) {
5955 account.deactivateGracePeriod();
5956 }
5957 }
5958
5959 public void refreshAllPresences() {
5960 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
5961 for (Account account : getAccounts()) {
5962 if (account.isConnectionEnabled()) {
5963 sendPresence(account, includeIdleTimestamp);
5964 }
5965 }
5966 }
5967
5968 private void refreshAllFcmTokens() {
5969 for (Account account : getAccounts()) {
5970 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
5971 mPushManagementService.registerPushTokenOnServer(account);
5972 }
5973 }
5974 }
5975
5976 private void sendOfflinePresence(final Account account) {
5977 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
5978 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
5979 }
5980
5981 public MessageGenerator getMessageGenerator() {
5982 return this.mMessageGenerator;
5983 }
5984
5985 public PresenceGenerator getPresenceGenerator() {
5986 return this.mPresenceGenerator;
5987 }
5988
5989 public IqGenerator getIqGenerator() {
5990 return this.mIqGenerator;
5991 }
5992
5993 public JingleConnectionManager getJingleConnectionManager() {
5994 return this.mJingleConnectionManager;
5995 }
5996
5997 private boolean hasJingleRtpConnection(final Account account) {
5998 return this.mJingleConnectionManager.hasJingleRtpConnection(account);
5999 }
6000
6001 public MessageArchiveService getMessageArchiveService() {
6002 return this.mMessageArchiveService;
6003 }
6004
6005 public QuickConversationsService getQuickConversationsService() {
6006 return this.mQuickConversationsService;
6007 }
6008
6009 public List<Contact> findContacts(Jid jid, String accountJid) {
6010 ArrayList<Contact> contacts = new ArrayList<>();
6011 for (Account account : getAccounts()) {
6012 if ((account.isEnabled() || accountJid != null)
6013 && (accountJid == null
6014 || accountJid.equals(account.getJid().asBareJid().toString()))) {
6015 Contact contact = account.getRoster().getContactFromContactList(jid);
6016 if (contact != null) {
6017 contacts.add(contact);
6018 }
6019 }
6020 }
6021 return contacts;
6022 }
6023
6024 public Conversation findFirstMuc(Jid jid) {
6025 for (Conversation conversation : getConversations()) {
6026 if (conversation.getAccount().isEnabled()
6027 && conversation.getJid().asBareJid().equals(jid.asBareJid())
6028 && conversation.getMode() == Conversation.MODE_MULTI) {
6029 return conversation;
6030 }
6031 }
6032 return null;
6033 }
6034
6035 public NotificationService getNotificationService() {
6036 return this.mNotificationService;
6037 }
6038
6039 public HttpConnectionManager getHttpConnectionManager() {
6040 return this.mHttpConnectionManager;
6041 }
6042
6043 public void resendFailedMessages(final Message message, final boolean forceP2P) {
6044 message.setTime(System.currentTimeMillis());
6045 markMessage(message, Message.STATUS_WAITING);
6046 this.sendMessage(message, true, false, forceP2P);
6047 if (message.getConversation() instanceof Conversation c) {
6048 c.sort();
6049 }
6050 updateConversationUi();
6051 }
6052
6053 public void clearConversationHistory(final Conversation conversation) {
6054 final long clearDate;
6055 final String reference;
6056 if (conversation.countMessages() > 0) {
6057 Message latestMessage = conversation.getLatestMessage();
6058 clearDate = latestMessage.getTimeSent() + 1000;
6059 reference = latestMessage.getServerMsgId();
6060 } else {
6061 clearDate = System.currentTimeMillis();
6062 reference = null;
6063 }
6064 conversation.clearMessages();
6065 conversation.setHasMessagesLeftOnServer(false); // avoid messages getting loaded through mam
6066 conversation.setLastClearHistory(clearDate, reference);
6067 Runnable runnable =
6068 () -> {
6069 databaseBackend.deleteMessagesInConversation(conversation);
6070 databaseBackend.updateConversation(conversation);
6071 };
6072 mDatabaseWriterExecutor.execute(runnable);
6073 }
6074
6075 public boolean sendBlockRequest(
6076 final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
6077 if (blockable != null && blockable.getBlockedJid() != null) {
6078 final var account = blockable.getAccount();
6079 final Jid jid = blockable.getBlockedJid();
6080 this.sendIqPacket(
6081 account,
6082 getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId),
6083 (response) -> {
6084 if (response.getType() == Iq.Type.RESULT) {
6085 account.getBlocklist().add(jid);
6086 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
6087 }
6088 });
6089 if (blockable.getBlockedJid().isFullJid()) {
6090 return false;
6091 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
6092 updateConversationUi();
6093 return true;
6094 } else {
6095 return false;
6096 }
6097 } else {
6098 return false;
6099 }
6100 }
6101
6102 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
6103 boolean removed = false;
6104 synchronized (this.conversations) {
6105 boolean domainJid = blockedJid.getLocal() == null;
6106 for (Conversation conversation : this.conversations) {
6107 boolean jidMatches =
6108 (domainJid
6109 && blockedJid
6110 .getDomain()
6111 .equals(conversation.getJid().getDomain()))
6112 || blockedJid.equals(conversation.getJid().asBareJid());
6113 if (conversation.getAccount() == account
6114 && conversation.getMode() == Conversation.MODE_SINGLE
6115 && jidMatches) {
6116 this.conversations.remove(conversation);
6117 markRead(conversation);
6118 conversation.setStatus(Conversation.STATUS_ARCHIVED);
6119 Log.d(
6120 Config.LOGTAG,
6121 account.getJid().asBareJid()
6122 + ": archiving conversation "
6123 + conversation.getJid().asBareJid()
6124 + " because jid was blocked");
6125 updateConversation(conversation);
6126 removed = true;
6127 }
6128 }
6129 }
6130 return removed;
6131 }
6132
6133 public void sendUnblockRequest(final Blockable blockable) {
6134 if (blockable != null && blockable.getJid() != null) {
6135 final var account = blockable.getAccount();
6136 final Jid jid = blockable.getBlockedJid();
6137 this.sendIqPacket(
6138 account,
6139 getIqGenerator().generateSetUnblockRequest(jid),
6140 response -> {
6141 if (response.getType() == Iq.Type.RESULT) {
6142 account.getBlocklist().remove(jid);
6143 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
6144 }
6145 });
6146 }
6147 }
6148
6149 public void publishDisplayName(final Account account) {
6150 String displayName = account.getDisplayName();
6151 final Iq request;
6152 if (TextUtils.isEmpty(displayName)) {
6153 request = mIqGenerator.deleteNode(Namespace.NICK);
6154 } else {
6155 request = mIqGenerator.publishNick(displayName);
6156 }
6157 mAvatarService.clear(account);
6158 sendIqPacket(
6159 account,
6160 request,
6161 (packet) -> {
6162 if (packet.getType() == Iq.Type.ERROR) {
6163 Log.d(
6164 Config.LOGTAG,
6165 account.getJid().asBareJid()
6166 + ": unable to modify nick name "
6167 + packet);
6168 }
6169 });
6170 }
6171
6172 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
6173 ServiceDiscoveryResult result = discoCache.get(key);
6174 if (result != null) {
6175 return result;
6176 } else {
6177 result = databaseBackend.findDiscoveryResult(key.first, key.second);
6178 if (result != null) {
6179 discoCache.put(key, result);
6180 }
6181 return result;
6182 }
6183 }
6184
6185 public void fetchCaps(final Account account, final Jid jid, final Presence presence) {
6186 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
6187 final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
6188 if (disco != null) {
6189 presence.setServiceDiscoveryResult(disco);
6190 final Contact contact = account.getRoster().getContact(jid);
6191 if (contact.refreshRtpCapability()) {
6192 syncRoster(account);
6193 }
6194 } else {
6195 final Iq request = new Iq(Iq.Type.GET);
6196 request.setTo(jid);
6197 final String node = presence.getNode();
6198 final String ver = presence.getVer();
6199 final Element query = request.query(Namespace.DISCO_INFO);
6200 if (node != null && ver != null) {
6201 query.setAttribute("node", node + "#" + ver);
6202 }
6203 Log.d(
6204 Config.LOGTAG,
6205 account.getJid().asBareJid()
6206 + ": making disco request for "
6207 + key.second
6208 + " to "
6209 + jid);
6210 sendIqPacket(
6211 account,
6212 request,
6213 (response) -> {
6214 if (response.getType() == Iq.Type.RESULT) {
6215 final ServiceDiscoveryResult discoveryResult =
6216 new ServiceDiscoveryResult(response);
6217 if (presence.getVer().equals(discoveryResult.getVer())) {
6218 databaseBackend.insertDiscoveryResult(discoveryResult);
6219 injectServiceDiscoveryResult(
6220 account.getRoster(),
6221 presence.getHash(),
6222 presence.getVer(),
6223 discoveryResult);
6224 } else {
6225 Log.d(
6226 Config.LOGTAG,
6227 account.getJid().asBareJid()
6228 + ": mismatch in caps for contact "
6229 + jid
6230 + " "
6231 + presence.getVer()
6232 + " vs "
6233 + discoveryResult.getVer());
6234 }
6235 } else {
6236 Log.d(
6237 Config.LOGTAG,
6238 account.getJid().asBareJid()
6239 + ": unable to fetch caps from "
6240 + jid);
6241 }
6242 });
6243 }
6244 }
6245
6246 private void injectServiceDiscoveryResult(
6247 Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
6248 boolean rosterNeedsSync = false;
6249 for (final Contact contact : roster.getContacts()) {
6250 boolean serviceDiscoverySet = false;
6251 for (final Presence presence : contact.getPresences().getPresences()) {
6252 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
6253 presence.setServiceDiscoveryResult(disco);
6254 serviceDiscoverySet = true;
6255 }
6256 }
6257 if (serviceDiscoverySet) {
6258 rosterNeedsSync |= contact.refreshRtpCapability();
6259 }
6260 }
6261 if (rosterNeedsSync) {
6262 syncRoster(roster.getAccount());
6263 }
6264 }
6265
6266 public void fetchMamPreferences(final Account account, final OnMamPreferencesFetched callback) {
6267 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
6268 final Iq request = new Iq(Iq.Type.GET);
6269 request.addChild("prefs", version.namespace);
6270 sendIqPacket(
6271 account,
6272 request,
6273 (packet) -> {
6274 final Element prefs = packet.findChild("prefs", version.namespace);
6275 if (packet.getType() == Iq.Type.RESULT && prefs != null) {
6276 callback.onPreferencesFetched(prefs);
6277 } else {
6278 callback.onPreferencesFetchFailed();
6279 }
6280 });
6281 }
6282
6283 public PushManagementService getPushManagementService() {
6284 return mPushManagementService;
6285 }
6286
6287 public void changeStatus(Account account, PresenceTemplate template, String signature) {
6288 if (!template.getStatusMessage().isEmpty()) {
6289 databaseBackend.insertPresenceTemplate(template);
6290 }
6291 account.setPgpSignature(signature);
6292 account.setPresenceStatus(template.getStatus());
6293 account.setPresenceStatusMessage(template.getStatusMessage());
6294 databaseBackend.updateAccount(account);
6295 sendPresence(account);
6296 }
6297
6298 public List<PresenceTemplate> getPresenceTemplates(Account account) {
6299 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
6300 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
6301 if (!templates.contains(template)) {
6302 templates.add(0, template);
6303 }
6304 }
6305 return templates;
6306 }
6307
6308 public void saveConversationAsBookmark(final Conversation conversation, final String name) {
6309 final Account account = conversation.getAccount();
6310 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
6311 final String nick = conversation.getJid().getResource();
6312 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
6313 bookmark.setNick(nick);
6314 }
6315 if (!TextUtils.isEmpty(name)) {
6316 bookmark.setBookmarkName(name);
6317 }
6318 bookmark.setAutojoin(true);
6319 createBookmark(account, bookmark);
6320 bookmark.setConversation(conversation);
6321 }
6322
6323 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
6324 boolean performedVerification = false;
6325 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
6326 for (XmppUri.Fingerprint fp : fingerprints) {
6327 if (fp.type == XmppUri.FingerprintType.OMEMO) {
6328 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
6329 FingerprintStatus fingerprintStatus =
6330 axolotlService.getFingerprintTrust(fingerprint);
6331 if (fingerprintStatus != null) {
6332 if (!fingerprintStatus.isVerified()) {
6333 performedVerification = true;
6334 axolotlService.setFingerprintTrust(
6335 fingerprint, fingerprintStatus.toVerified());
6336 }
6337 } else {
6338 axolotlService.preVerifyFingerprint(contact, fingerprint);
6339 }
6340 }
6341 }
6342 return performedVerification;
6343 }
6344
6345 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
6346 final AxolotlService axolotlService = account.getAxolotlService();
6347 boolean verifiedSomething = false;
6348 for (XmppUri.Fingerprint fp : fingerprints) {
6349 if (fp.type == XmppUri.FingerprintType.OMEMO) {
6350 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
6351 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
6352 FingerprintStatus fingerprintStatus =
6353 axolotlService.getFingerprintTrust(fingerprint);
6354 if (fingerprintStatus != null) {
6355 if (!fingerprintStatus.isVerified()) {
6356 axolotlService.setFingerprintTrust(
6357 fingerprint, fingerprintStatus.toVerified());
6358 verifiedSomething = true;
6359 }
6360 } else {
6361 axolotlService.preVerifyFingerprint(account, fingerprint);
6362 verifiedSomething = true;
6363 }
6364 }
6365 }
6366 return verifiedSomething;
6367 }
6368
6369 public ShortcutService getShortcutService() {
6370 return mShortcutService;
6371 }
6372
6373 public void pushMamPreferences(Account account, Element prefs) {
6374 final Iq set = new Iq(Iq.Type.SET);
6375 set.addChild(prefs);
6376 sendIqPacket(account, set, null);
6377 }
6378
6379 public void evictPreview(String uuid) {
6380 if (mBitmapCache.remove(uuid) != null) {
6381 Log.d(Config.LOGTAG, "deleted cached preview");
6382 }
6383 }
6384
6385 public interface OnMamPreferencesFetched {
6386 void onPreferencesFetched(Element prefs);
6387
6388 void onPreferencesFetchFailed();
6389 }
6390
6391 public interface OnAccountCreated {
6392 void onAccountCreated(Account account);
6393
6394 void informUser(int r);
6395 }
6396
6397 public interface OnMoreMessagesLoaded {
6398 void onMoreMessagesLoaded(int count, Conversation conversation);
6399
6400 void informUser(int r);
6401 }
6402
6403 public interface OnAccountPasswordChanged {
6404 void onPasswordChangeSucceeded();
6405
6406 void onPasswordChangeFailed();
6407 }
6408
6409 public interface OnRoomDestroy {
6410 void onRoomDestroySucceeded();
6411
6412 void onRoomDestroyFailed();
6413 }
6414
6415 public interface OnAffiliationChanged {
6416 void onAffiliationChangedSuccessful(Jid jid);
6417
6418 void onAffiliationChangeFailed(Jid jid, int resId);
6419 }
6420
6421 public interface OnConversationUpdate {
6422 void onConversationUpdate();
6423 }
6424
6425 public interface OnJingleRtpConnectionUpdate {
6426 void onJingleRtpConnectionUpdate(
6427 final Account account,
6428 final Jid with,
6429 final String sessionId,
6430 final RtpEndUserState state);
6431
6432 void onAudioDeviceChanged(
6433 CallIntegration.AudioDevice selectedAudioDevice,
6434 Set<CallIntegration.AudioDevice> availableAudioDevices);
6435 }
6436
6437 public interface OnAccountUpdate {
6438 void onAccountUpdate();
6439 }
6440
6441 public interface OnCaptchaRequested {
6442 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
6443 }
6444
6445 public interface OnRosterUpdate {
6446 void onRosterUpdate();
6447 }
6448
6449 public interface OnMucRosterUpdate {
6450 void onMucRosterUpdate();
6451 }
6452
6453 public interface OnConferenceConfigurationFetched {
6454 void onConferenceConfigurationFetched(Conversation conversation);
6455
6456 void onFetchFailed(Conversation conversation, String errorCondition);
6457 }
6458
6459 public interface OnConferenceJoined {
6460 void onConferenceJoined(Conversation conversation);
6461 }
6462
6463 public interface OnConfigurationPushed {
6464 void onPushSucceeded();
6465
6466 void onPushFailed();
6467 }
6468
6469 public interface OnShowErrorToast {
6470 void onShowErrorToast(int resId);
6471 }
6472
6473 public class XmppConnectionBinder extends Binder {
6474 public XmppConnectionService getService() {
6475 return XmppConnectionService.this;
6476 }
6477 }
6478
6479 private class InternalEventReceiver extends BroadcastReceiver {
6480
6481 @Override
6482 public void onReceive(final Context context, final Intent intent) {
6483 onStartCommand(intent, 0, 0);
6484 }
6485 }
6486
6487 private class RestrictedEventReceiver extends BroadcastReceiver {
6488
6489 private final Collection<String> allowedActions;
6490
6491 private RestrictedEventReceiver(final Collection<String> allowedActions) {
6492 this.allowedActions = allowedActions;
6493 }
6494
6495 @Override
6496 public void onReceive(final Context context, final Intent intent) {
6497 final String action = intent == null ? null : intent.getAction();
6498 if (allowedActions.contains(action)) {
6499 onStartCommand(intent, 0, 0);
6500 } else {
6501 Log.e(Config.LOGTAG, "restricting broadcast of event " + action);
6502 }
6503 }
6504 }
6505
6506 public static class OngoingCall {
6507 public final AbstractJingleConnection.Id id;
6508 public final Set<Media> media;
6509 public final boolean reconnecting;
6510
6511 public OngoingCall(
6512 AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
6513 this.id = id;
6514 this.media = media;
6515 this.reconnecting = reconnecting;
6516 }
6517
6518 @Override
6519 public boolean equals(Object o) {
6520 if (this == o) return true;
6521 if (o == null || getClass() != o.getClass()) return false;
6522 OngoingCall that = (OngoingCall) o;
6523 return reconnecting == that.reconnecting
6524 && Objects.equal(id, that.id)
6525 && Objects.equal(media, that.media);
6526 }
6527
6528 @Override
6529 public int hashCode() {
6530 return Objects.hashCode(id, media, reconnecting);
6531 }
6532 }
6533
6534 public static void toggleForegroundService(final XmppConnectionService service) {
6535 if (service == null) {
6536 return;
6537 }
6538 service.toggleForegroundService();
6539 }
6540
6541 public static void toggleForegroundService(final ConversationsActivity activity) {
6542 if (activity == null) {
6543 return;
6544 }
6545 toggleForegroundService(activity.xmppConnectionService);
6546 }
6547}