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