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