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