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 createBookmark(final Account account, final Bookmark bookmark) {
2294 account.putBookmark(bookmark);
2295 final XmppConnection connection = account.getXmppConnection();
2296 if (connection == null) {
2297 Log.d(
2298 Config.LOGTAG,
2299 account.getJid().asBareJid() + ": no connection. ignoring bookmark creation");
2300 } else if (connection.getFeatures().bookmarks2()) {
2301 Log.d(
2302 Config.LOGTAG,
2303 account.getJid().asBareJid() + ": pushing bookmark via Bookmarks 2");
2304 final Element item = mIqGenerator.publishBookmarkItem(bookmark);
2305 pushNodeAndEnforcePublishOptions(
2306 account,
2307 Namespace.BOOKMARKS2,
2308 item,
2309 bookmark.getJid().asBareJid().toEscapedString(),
2310 PublishOptions.persistentWhitelistAccessMaxItems());
2311 } else if (connection.getFeatures().bookmarksConversion()) {
2312 pushBookmarksPep(account);
2313 } else {
2314 pushBookmarksPrivateXml(account);
2315 }
2316 }
2317
2318 public void deleteBookmark(final Account account, final Bookmark bookmark) {
2319 account.removeBookmark(bookmark);
2320 final XmppConnection connection = account.getXmppConnection();
2321 if (connection.getFeatures().bookmarks2()) {
2322 final Iq request =
2323 mIqGenerator.deleteItem(
2324 Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
2325 Log.d(
2326 Config.LOGTAG,
2327 account.getJid().asBareJid() + ": removing bookmark via Bookmarks 2");
2328 sendIqPacket(
2329 account,
2330 request,
2331 (response) -> {
2332 if (response.getType() == Iq.Type.ERROR) {
2333 Log.d(
2334 Config.LOGTAG,
2335 account.getJid().asBareJid()
2336 + ": unable to delete bookmark "
2337 + response.getErrorCondition());
2338 }
2339 });
2340 } else if (connection.getFeatures().bookmarksConversion()) {
2341 pushBookmarksPep(account);
2342 } else {
2343 pushBookmarksPrivateXml(account);
2344 }
2345 }
2346
2347 private void pushBookmarksPrivateXml(Account account) {
2348 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
2349 final Iq iqPacket = new Iq(Iq.Type.SET);
2350 Element query = iqPacket.query("jabber:iq:private");
2351 Element storage = query.addChild("storage", "storage:bookmarks");
2352 for (final Bookmark bookmark : account.getBookmarks()) {
2353 storage.addChild(bookmark);
2354 }
2355 sendIqPacket(account, iqPacket, mDefaultIqHandler);
2356 }
2357
2358 private void pushBookmarksPep(Account account) {
2359 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
2360 final Element storage = new Element("storage", "storage:bookmarks");
2361 for (final Bookmark bookmark : account.getBookmarks()) {
2362 storage.addChild(bookmark);
2363 }
2364 pushNodeAndEnforcePublishOptions(
2365 account,
2366 Namespace.BOOKMARKS,
2367 storage,
2368 "current",
2369 PublishOptions.persistentWhitelistAccess());
2370 }
2371
2372 private void pushNodeAndEnforcePublishOptions(
2373 final Account account,
2374 final String node,
2375 final Element element,
2376 final String id,
2377 final Bundle options) {
2378 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2379 }
2380
2381 private void pushNodeAndEnforcePublishOptions(
2382 final Account account,
2383 final String node,
2384 final Element element,
2385 final String id,
2386 final Bundle options,
2387 final boolean retry) {
2388 final Iq packet = mIqGenerator.publishElement(node, element, id, options);
2389 sendIqPacket(
2390 account,
2391 packet,
2392 (response) -> {
2393 if (response.getType() == Iq.Type.RESULT) {
2394 return;
2395 }
2396 if (retry && PublishOptions.preconditionNotMet(response)) {
2397 pushNodeConfiguration(
2398 account,
2399 node,
2400 options,
2401 new OnConfigurationPushed() {
2402 @Override
2403 public void onPushSucceeded() {
2404 pushNodeAndEnforcePublishOptions(
2405 account, node, element, id, options, false);
2406 }
2407
2408 @Override
2409 public void onPushFailed() {
2410 Log.d(
2411 Config.LOGTAG,
2412 account.getJid().asBareJid()
2413 + ": unable to push node configuration ("
2414 + node
2415 + ")");
2416 }
2417 });
2418 } else {
2419 Log.d(
2420 Config.LOGTAG,
2421 account.getJid().asBareJid()
2422 + ": error publishing "
2423 + node
2424 + " (retry="
2425 + retry
2426 + ") "
2427 + response);
2428 }
2429 });
2430 }
2431
2432 private void restoreFromDatabase() {
2433 synchronized (this.conversations) {
2434 final Map<String, Account> accountLookupTable =
2435 ImmutableMap.copyOf(Maps.uniqueIndex(this.accounts, Account::getUuid));
2436 Log.d(Config.LOGTAG, "restoring conversations...");
2437 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2438 this.conversations.addAll(
2439 databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2440 for (Iterator<Conversation> iterator = conversations.listIterator();
2441 iterator.hasNext(); ) {
2442 Conversation conversation = iterator.next();
2443 Account account = accountLookupTable.get(conversation.getAccountUuid());
2444 if (account != null) {
2445 conversation.setAccount(account);
2446 } else {
2447 Log.e(
2448 Config.LOGTAG,
2449 "unable to restore Conversations with " + conversation.getJid());
2450 iterator.remove();
2451 }
2452 }
2453 long diffConversationsRestore =
2454 SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2455 Log.d(
2456 Config.LOGTAG,
2457 "finished restoring conversations in " + diffConversationsRestore + "ms");
2458 Runnable runnable =
2459 () -> {
2460 if (DatabaseBackend.requiresMessageIndexRebuild()) {
2461 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2462 }
2463 final long deletionDate = getAutomaticMessageDeletionDate();
2464 mLastExpiryRun.set(SystemClock.elapsedRealtime());
2465 if (deletionDate > 0) {
2466 Log.d(
2467 Config.LOGTAG,
2468 "deleting messages that are older than "
2469 + AbstractGenerator.getTimestamp(deletionDate));
2470 databaseBackend.expireOldMessages(deletionDate);
2471 }
2472 Log.d(Config.LOGTAG, "restoring roster...");
2473 for (final Account account : accounts) {
2474 databaseBackend.readRoster(account.getRoster());
2475 account.initAccountServices(
2476 XmppConnectionService
2477 .this); // roster needs to be loaded at this stage
2478 }
2479 getBitmapCache().evictAll();
2480 loadPhoneContacts();
2481 Log.d(Config.LOGTAG, "restoring messages...");
2482 final long startMessageRestore = SystemClock.elapsedRealtime();
2483 final Conversation quickLoad = QuickLoader.get(this.conversations);
2484 if (quickLoad != null) {
2485 restoreMessages(quickLoad);
2486 updateConversationUi();
2487 final long diffMessageRestore =
2488 SystemClock.elapsedRealtime() - startMessageRestore;
2489 Log.d(
2490 Config.LOGTAG,
2491 "quickly restored "
2492 + quickLoad.getName()
2493 + " after "
2494 + diffMessageRestore
2495 + "ms");
2496 }
2497 for (Conversation conversation : this.conversations) {
2498 if (quickLoad != conversation) {
2499 restoreMessages(conversation);
2500 }
2501 }
2502 mNotificationService.finishBacklog();
2503 restoredFromDatabaseLatch.countDown();
2504 final long diffMessageRestore =
2505 SystemClock.elapsedRealtime() - startMessageRestore;
2506 Log.d(
2507 Config.LOGTAG,
2508 "finished restoring messages in " + diffMessageRestore + "ms");
2509 updateConversationUi();
2510 };
2511 mDatabaseReaderExecutor.execute(
2512 runnable); // will contain one write command (expiry) but that's fine
2513 }
2514 }
2515
2516 private void restoreMessages(Conversation conversation) {
2517 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2518 conversation.findUnsentTextMessages(
2519 message -> markMessage(message, Message.STATUS_WAITING));
2520 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2521 }
2522
2523 public void loadPhoneContacts() {
2524 mContactMergerExecutor.execute(
2525 () -> {
2526 final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2527 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2528 for (final Account account : accounts) {
2529 final List<Contact> withSystemAccounts =
2530 account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2531 for (final JabberIdContact jidContact : contacts.values()) {
2532 final Contact contact =
2533 account.getRoster().getContact(jidContact.getJid());
2534 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2535 if (needsCacheClean) {
2536 getAvatarService().clear(contact);
2537 }
2538 withSystemAccounts.remove(contact);
2539 }
2540 for (final Contact contact : withSystemAccounts) {
2541 boolean needsCacheClean =
2542 contact.unsetPhoneContact(JabberIdContact.class);
2543 if (needsCacheClean) {
2544 getAvatarService().clear(contact);
2545 }
2546 }
2547 }
2548 Log.d(Config.LOGTAG, "finished merging phone contacts");
2549 mShortcutService.refresh(
2550 mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2551 updateRosterUi();
2552 mQuickConversationsService.considerSync();
2553 });
2554 }
2555
2556 public void syncRoster(final Account account) {
2557 mRosterSyncTaskManager.execute(
2558 account, () -> databaseBackend.writeRoster(account.getRoster()));
2559 }
2560
2561 public List<Conversation> getConversations() {
2562 return this.conversations;
2563 }
2564
2565 private void markFileDeleted(final File file) {
2566 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2567 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2568 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2569 return;
2570 }
2571 }
2572 final boolean isInternalFile = fileBackend.isInternalFile(file);
2573 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2574 Log.d(
2575 Config.LOGTAG,
2576 "deleted file "
2577 + file.getAbsolutePath()
2578 + " internal="
2579 + isInternalFile
2580 + ", database hits="
2581 + uuids.size());
2582 markUuidsAsDeletedFiles(uuids);
2583 }
2584
2585 private void markUuidsAsDeletedFiles(List<String> uuids) {
2586 boolean deleted = false;
2587 for (Conversation conversation : getConversations()) {
2588 deleted |= conversation.markAsDeleted(uuids);
2589 }
2590 for (final String uuid : uuids) {
2591 evictPreview(uuid);
2592 }
2593 if (deleted) {
2594 updateConversationUi();
2595 }
2596 }
2597
2598 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2599 boolean changed = false;
2600 for (Conversation conversation : getConversations()) {
2601 changed |= conversation.markAsChanged(infos);
2602 }
2603 if (changed) {
2604 updateConversationUi();
2605 }
2606 }
2607
2608 public void populateWithOrderedConversations(final List<Conversation> list) {
2609 populateWithOrderedConversations(list, true, true);
2610 }
2611
2612 public void populateWithOrderedConversations(
2613 final List<Conversation> list, final boolean includeNoFileUpload) {
2614 populateWithOrderedConversations(list, includeNoFileUpload, true);
2615 }
2616
2617 public void populateWithOrderedConversations(
2618 final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2619 final List<String> orderedUuids;
2620 if (sort) {
2621 orderedUuids = null;
2622 } else {
2623 orderedUuids = new ArrayList<>();
2624 for (Conversation conversation : list) {
2625 orderedUuids.add(conversation.getUuid());
2626 }
2627 }
2628 list.clear();
2629 if (includeNoFileUpload) {
2630 list.addAll(getConversations());
2631 } else {
2632 for (Conversation conversation : getConversations()) {
2633 if (conversation.getMode() == Conversation.MODE_SINGLE
2634 || (conversation.getAccount().httpUploadAvailable()
2635 && conversation.getMucOptions().participating())) {
2636 list.add(conversation);
2637 }
2638 }
2639 }
2640 try {
2641 if (orderedUuids != null) {
2642 Collections.sort(
2643 list,
2644 (a, b) -> {
2645 final int indexA = orderedUuids.indexOf(a.getUuid());
2646 final int indexB = orderedUuids.indexOf(b.getUuid());
2647 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2648 return a.compareTo(b);
2649 }
2650 return indexA - indexB;
2651 });
2652 } else {
2653 Collections.sort(list);
2654 }
2655 } catch (IllegalArgumentException e) {
2656 // ignore
2657 }
2658 }
2659
2660 public void loadMoreMessages(
2661 final Conversation conversation,
2662 final long timestamp,
2663 final OnMoreMessagesLoaded callback) {
2664 if (XmppConnectionService.this
2665 .getMessageArchiveService()
2666 .queryInProgress(conversation, callback)) {
2667 return;
2668 } else if (timestamp == 0) {
2669 return;
2670 }
2671 Log.d(
2672 Config.LOGTAG,
2673 "load more messages for "
2674 + conversation.getName()
2675 + " prior to "
2676 + MessageGenerator.getTimestamp(timestamp));
2677 final Runnable runnable =
2678 () -> {
2679 final Account account = conversation.getAccount();
2680 List<Message> messages =
2681 databaseBackend.getMessages(conversation, 50, timestamp);
2682 if (messages.size() > 0) {
2683 conversation.addAll(0, messages);
2684 callback.onMoreMessagesLoaded(messages.size(), conversation);
2685 } else if (conversation.hasMessagesLeftOnServer()
2686 && account.isOnlineAndConnected()
2687 && conversation.getLastClearHistory().getTimestamp() == 0) {
2688 final boolean mamAvailable;
2689 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2690 mamAvailable =
2691 account.getXmppConnection().getFeatures().mam()
2692 && !conversation.getContact().isBlocked();
2693 } else {
2694 mamAvailable = conversation.getMucOptions().mamSupport();
2695 }
2696 if (mamAvailable) {
2697 MessageArchiveService.Query query =
2698 getMessageArchiveService()
2699 .query(
2700 conversation,
2701 new MamReference(0),
2702 timestamp,
2703 false);
2704 if (query != null) {
2705 query.setCallback(callback);
2706 callback.informUser(R.string.fetching_history_from_server);
2707 } else {
2708 callback.informUser(R.string.not_fetching_history_retention_period);
2709 }
2710 }
2711 }
2712 };
2713 mDatabaseReaderExecutor.execute(runnable);
2714 }
2715
2716 public List<Account> getAccounts() {
2717 return this.accounts;
2718 }
2719
2720 /**
2721 * This will find all conferences with the contact as member and also the conference that is the
2722 * contact (that 'fake' contact is used to store the avatar)
2723 */
2724 public List<Conversation> findAllConferencesWith(Contact contact) {
2725 final ArrayList<Conversation> results = new ArrayList<>();
2726 for (final Conversation c : conversations) {
2727 if (c.getMode() != Conversation.MODE_MULTI) {
2728 continue;
2729 }
2730 final MucOptions mucOptions = c.getMucOptions();
2731 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid())
2732 || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2733 results.add(c);
2734 }
2735 }
2736 return results;
2737 }
2738
2739 public Conversation find(final Contact contact) {
2740 for (final Conversation conversation : this.conversations) {
2741 if (conversation.getContact() == contact) {
2742 return conversation;
2743 }
2744 }
2745 return null;
2746 }
2747
2748 public Conversation find(
2749 final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2750 if (jid == null) {
2751 return null;
2752 }
2753 for (final Conversation conversation : haystack) {
2754 if ((account == null || conversation.getAccount() == account)
2755 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2756 return conversation;
2757 }
2758 }
2759 return null;
2760 }
2761
2762 public boolean isConversationsListEmpty(final Conversation ignore) {
2763 synchronized (this.conversations) {
2764 final int size = this.conversations.size();
2765 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2766 }
2767 }
2768
2769 public boolean isConversationStillOpen(final Conversation conversation) {
2770 synchronized (this.conversations) {
2771 for (Conversation current : this.conversations) {
2772 if (current == conversation) {
2773 return true;
2774 }
2775 }
2776 }
2777 return false;
2778 }
2779
2780 public Conversation findOrCreateConversation(
2781 Account account, Jid jid, boolean muc, final boolean async) {
2782 return this.findOrCreateConversation(account, jid, muc, false, async);
2783 }
2784
2785 public Conversation findOrCreateConversation(
2786 final Account account,
2787 final Jid jid,
2788 final boolean muc,
2789 final boolean joinAfterCreate,
2790 final boolean async) {
2791 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2792 }
2793
2794 public Conversation findOrCreateConversation(
2795 final Account account,
2796 final Jid jid,
2797 final boolean muc,
2798 final boolean joinAfterCreate,
2799 final MessageArchiveService.Query query,
2800 final boolean async) {
2801 synchronized (this.conversations) {
2802 final var cached = find(account, jid);
2803 if (cached != null) {
2804 return cached;
2805 }
2806 final var existing = databaseBackend.findConversation(account, jid);
2807 final Conversation conversation;
2808 final boolean loadMessagesFromDb;
2809 if (existing != null) {
2810 conversation = existing;
2811 loadMessagesFromDb = restoreFromArchive(conversation, jid, muc);
2812 } else {
2813 String conversationName;
2814 final Contact contact = account.getRoster().getContact(jid);
2815 if (contact != null) {
2816 conversationName = contact.getDisplayName();
2817 } else {
2818 conversationName = jid.getLocal();
2819 }
2820 if (muc) {
2821 conversation =
2822 new Conversation(
2823 conversationName, account, jid, Conversation.MODE_MULTI);
2824 } else {
2825 conversation =
2826 new Conversation(
2827 conversationName,
2828 account,
2829 jid.asBareJid(),
2830 Conversation.MODE_SINGLE);
2831 }
2832 this.databaseBackend.createConversation(conversation);
2833 loadMessagesFromDb = false;
2834 }
2835 if (async) {
2836 mDatabaseReaderExecutor.execute(
2837 () ->
2838 postProcessConversation(
2839 conversation, loadMessagesFromDb, joinAfterCreate, query));
2840 } else {
2841 postProcessConversation(conversation, loadMessagesFromDb, joinAfterCreate, query);
2842 }
2843 this.conversations.add(conversation);
2844 updateConversationUi();
2845 return conversation;
2846 }
2847 }
2848
2849 public Conversation findConversationByUuidReliable(final String uuid) {
2850 final var cached = findConversationByUuid(uuid);
2851 if (cached != null) {
2852 return cached;
2853 }
2854 final var existing = databaseBackend.findConversation(uuid);
2855 if (existing == null) {
2856 return null;
2857 }
2858 Log.d(
2859 Config.LOGTAG,
2860 existing.getJid().asBareJid()
2861 + ": restoring conversation with "
2862 + existing.getJid()
2863 + " from DB");
2864 final Map<String, Account> accounts =
2865 ImmutableMap.copyOf(Maps.uniqueIndex(this.accounts, Account::getUuid));
2866 existing.setAccount(accounts.get(existing.getAccountUuid()));
2867 final var loadMessagesFromDb = restoreFromArchive(existing);
2868 mDatabaseReaderExecutor.execute(
2869 () ->
2870 postProcessConversation(
2871 existing,
2872 loadMessagesFromDb,
2873 existing.getMode() == Conversational.MODE_MULTI,
2874 null));
2875 this.conversations.add(existing);
2876 updateConversationUi();
2877 return existing;
2878 }
2879
2880 private boolean restoreFromArchive(
2881 final Conversation conversation, final Jid jid, final boolean muc) {
2882 if (muc) {
2883 conversation.setMode(Conversation.MODE_MULTI);
2884 conversation.setContactJid(jid);
2885 } else {
2886 conversation.setMode(Conversation.MODE_SINGLE);
2887 conversation.setContactJid(jid.asBareJid());
2888 }
2889 return restoreFromArchive(conversation);
2890 }
2891
2892 private boolean restoreFromArchive(final Conversation conversation) {
2893 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2894 databaseBackend.updateConversation(conversation);
2895 return conversation.messagesLoaded.compareAndSet(true, false);
2896 }
2897
2898 private void postProcessConversation(
2899 final Conversation c,
2900 final boolean loadMessagesFromDb,
2901 final boolean joinAfterCreate,
2902 final MessageArchiveService.Query query) {
2903 final var singleMode = c.getMode() == Conversational.MODE_SINGLE;
2904 final var account = c.getAccount();
2905 if (loadMessagesFromDb) {
2906 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2907 updateConversationUi();
2908 c.messagesLoaded.set(true);
2909 }
2910 if (account.getXmppConnection() != null
2911 && !c.getContact().isBlocked()
2912 && account.getXmppConnection().getFeatures().mam()
2913 && singleMode) {
2914 if (query == null) {
2915 mMessageArchiveService.query(c);
2916 } else {
2917 if (query.getConversation() == null) {
2918 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2919 }
2920 }
2921 }
2922 if (joinAfterCreate) {
2923 joinMuc(c);
2924 }
2925 }
2926
2927 public void archiveConversation(Conversation conversation) {
2928 archiveConversation(conversation, true);
2929 }
2930
2931 private void archiveConversation(
2932 Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2933 getNotificationService().clear(conversation);
2934 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2935 conversation.setNextMessage(null);
2936 synchronized (this.conversations) {
2937 getMessageArchiveService().kill(conversation);
2938 if (conversation.getMode() == Conversation.MODE_MULTI) {
2939 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2940 final Bookmark bookmark = conversation.getBookmark();
2941 if (maySynchronizeWithBookmarks && bookmark != null) {
2942 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2943 Account account = bookmark.getAccount();
2944 bookmark.setConversation(null);
2945 deleteBookmark(account, bookmark);
2946 } else if (bookmark.autojoin()) {
2947 bookmark.setAutojoin(false);
2948 createBookmark(bookmark.getAccount(), bookmark);
2949 }
2950 }
2951 }
2952 leaveMuc(conversation);
2953 } else {
2954 if (conversation
2955 .getContact()
2956 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2957 stopPresenceUpdatesTo(conversation.getContact());
2958 }
2959 }
2960 updateConversation(conversation);
2961 this.conversations.remove(conversation);
2962 updateConversationUi();
2963 }
2964 }
2965
2966 public void stopPresenceUpdatesTo(Contact contact) {
2967 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2968 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2969 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2970 }
2971
2972 public void createAccount(final Account account) {
2973 account.initAccountServices(this);
2974 databaseBackend.createAccount(account);
2975 if (CallIntegration.hasSystemFeature(this)) {
2976 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2977 }
2978 this.accounts.add(account);
2979 this.reconnectAccountInBackground(account);
2980 updateAccountUi();
2981 syncEnabledAccountSetting();
2982 toggleForegroundService();
2983 }
2984
2985 private void syncEnabledAccountSetting() {
2986 final boolean hasEnabledAccounts = hasEnabledAccounts();
2987 getPreferences()
2988 .edit()
2989 .putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts)
2990 .apply();
2991 toggleSetProfilePictureActivity(hasEnabledAccounts);
2992 }
2993
2994 private void toggleSetProfilePictureActivity(final boolean enabled) {
2995 try {
2996 final ComponentName name =
2997 new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2998 final int targetState =
2999 enabled
3000 ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
3001 : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
3002 getPackageManager()
3003 .setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
3004 } catch (IllegalStateException e) {
3005 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
3006 }
3007 }
3008
3009 public boolean reconfigurePushDistributor() {
3010 return this.unifiedPushBroker.reconfigurePushDistributor();
3011 }
3012
3013 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(
3014 final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
3015 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
3016 }
3017
3018 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
3019 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
3020 }
3021
3022 public UnifiedPushBroker getUnifiedPushBroker() {
3023 return this.unifiedPushBroker;
3024 }
3025
3026 private void provisionAccount(final String address, final String password) {
3027 final Jid jid = Jid.ofEscaped(address);
3028 final Account account = new Account(jid, password);
3029 account.setOption(Account.OPTION_DISABLED, true);
3030 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
3031 createAccount(account);
3032 }
3033
3034 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
3035 new Thread(
3036 () -> {
3037 try {
3038 final X509Certificate[] chain =
3039 KeyChain.getCertificateChain(this, alias);
3040 final X509Certificate cert =
3041 chain != null && chain.length > 0 ? chain[0] : null;
3042 if (cert == null) {
3043 callback.informUser(R.string.unable_to_parse_certificate);
3044 return;
3045 }
3046 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
3047 if (info == null) {
3048 callback.informUser(R.string.certificate_does_not_contain_jid);
3049 return;
3050 }
3051 if (findAccountByJid(info.first) == null) {
3052 final Account account = new Account(info.first, "");
3053 account.setPrivateKeyAlias(alias);
3054 account.setOption(Account.OPTION_DISABLED, true);
3055 account.setOption(Account.OPTION_FIXED_USERNAME, true);
3056 account.setDisplayName(info.second);
3057 createAccount(account);
3058 callback.onAccountCreated(account);
3059 if (Config.X509_VERIFICATION) {
3060 try {
3061 getMemorizingTrustManager()
3062 .getNonInteractive(account.getServer())
3063 .checkClientTrusted(chain, "RSA");
3064 } catch (CertificateException e) {
3065 callback.informUser(
3066 R.string.certificate_chain_is_not_trusted);
3067 }
3068 }
3069 } else {
3070 callback.informUser(R.string.account_already_exists);
3071 }
3072 } catch (Exception e) {
3073 callback.informUser(R.string.unable_to_parse_certificate);
3074 }
3075 })
3076 .start();
3077 }
3078
3079 public void updateKeyInAccount(final Account account, final String alias) {
3080 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
3081 try {
3082 X509Certificate[] chain =
3083 KeyChain.getCertificateChain(XmppConnectionService.this, alias);
3084 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
3085 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
3086 if (info == null) {
3087 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
3088 return;
3089 }
3090 if (account.getJid().asBareJid().equals(info.first)) {
3091 account.setPrivateKeyAlias(alias);
3092 account.setDisplayName(info.second);
3093 databaseBackend.updateAccount(account);
3094 if (Config.X509_VERIFICATION) {
3095 try {
3096 getMemorizingTrustManager()
3097 .getNonInteractive()
3098 .checkClientTrusted(chain, "RSA");
3099 } catch (CertificateException e) {
3100 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
3101 }
3102 account.getAxolotlService().regenerateKeys(true);
3103 }
3104 } else {
3105 showErrorToastInUi(R.string.jid_does_not_match_certificate);
3106 }
3107 } catch (Exception e) {
3108 e.printStackTrace();
3109 }
3110 }
3111
3112 public boolean updateAccount(final Account account) {
3113 if (databaseBackend.updateAccount(account)) {
3114 account.setShowErrorNotification(true);
3115 this.statusListener.onStatusChanged(account);
3116 databaseBackend.updateAccount(account);
3117 reconnectAccountInBackground(account);
3118 updateAccountUi();
3119 getNotificationService().updateErrorNotification();
3120 toggleForegroundService();
3121 syncEnabledAccountSetting();
3122 mChannelDiscoveryService.cleanCache();
3123 if (CallIntegration.hasSystemFeature(this)) {
3124 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
3125 }
3126 return true;
3127 } else {
3128 return false;
3129 }
3130 }
3131
3132 public void updateAccountPasswordOnServer(
3133 final Account account,
3134 final String newPassword,
3135 final OnAccountPasswordChanged callback) {
3136 final Iq iq = getIqGenerator().generateSetPassword(account, newPassword);
3137 sendIqPacket(
3138 account,
3139 iq,
3140 (packet) -> {
3141 if (packet.getType() == Iq.Type.RESULT) {
3142 account.setPassword(newPassword);
3143 account.setOption(Account.OPTION_MAGIC_CREATE, false);
3144 databaseBackend.updateAccount(account);
3145 callback.onPasswordChangeSucceeded();
3146 } else {
3147 callback.onPasswordChangeFailed();
3148 }
3149 });
3150 }
3151
3152 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
3153 final Iq iqPacket = new Iq(Iq.Type.SET);
3154 final Element query = iqPacket.addChild("query", Namespace.REGISTER);
3155 query.addChild("remove");
3156 sendIqPacket(
3157 account,
3158 iqPacket,
3159 (response) -> {
3160 if (response.getType() == Iq.Type.RESULT) {
3161 deleteAccount(account);
3162 callback.accept(true);
3163 } else {
3164 callback.accept(false);
3165 }
3166 });
3167 }
3168
3169 public void deleteAccount(final Account account) {
3170 final boolean connected = account.getStatus() == Account.State.ONLINE;
3171 synchronized (this.conversations) {
3172 if (connected) {
3173 account.getAxolotlService().deleteOmemoIdentity();
3174 }
3175 for (final Conversation conversation : conversations) {
3176 if (conversation.getAccount() == account) {
3177 if (conversation.getMode() == Conversation.MODE_MULTI) {
3178 if (connected) {
3179 leaveMuc(conversation);
3180 }
3181 }
3182 conversations.remove(conversation);
3183 mNotificationService.clear(conversation);
3184 }
3185 }
3186 if (account.getXmppConnection() != null) {
3187 new Thread(() -> disconnect(account, !connected)).start();
3188 }
3189 final Runnable runnable =
3190 () -> {
3191 if (!databaseBackend.deleteAccount(account)) {
3192 Log.d(
3193 Config.LOGTAG,
3194 account.getJid().asBareJid() + ": unable to delete account");
3195 }
3196 };
3197 mDatabaseWriterExecutor.execute(runnable);
3198 this.accounts.remove(account);
3199 if (CallIntegration.hasSystemFeature(this)) {
3200 CallIntegrationConnectionService.unregisterPhoneAccount(this, account);
3201 }
3202 this.mRosterSyncTaskManager.clear(account);
3203 updateAccountUi();
3204 mNotificationService.updateErrorNotification();
3205 syncEnabledAccountSetting();
3206 toggleForegroundService();
3207 }
3208 }
3209
3210 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
3211 final boolean remainingListeners;
3212 synchronized (LISTENER_LOCK) {
3213 remainingListeners = checkListeners();
3214 if (!this.mOnConversationUpdates.add(listener)) {
3215 Log.w(
3216 Config.LOGTAG,
3217 listener.getClass().getName()
3218 + " is already registered as ConversationListChangedListener");
3219 }
3220 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3221 }
3222 if (remainingListeners) {
3223 switchToForeground();
3224 }
3225 }
3226
3227 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
3228 final boolean remainingListeners;
3229 synchronized (LISTENER_LOCK) {
3230 this.mOnConversationUpdates.remove(listener);
3231 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3232 remainingListeners = checkListeners();
3233 }
3234 if (remainingListeners) {
3235 switchToBackground();
3236 }
3237 }
3238
3239 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
3240 final boolean remainingListeners;
3241 synchronized (LISTENER_LOCK) {
3242 remainingListeners = checkListeners();
3243 if (!this.mOnShowErrorToasts.add(listener)) {
3244 Log.w(
3245 Config.LOGTAG,
3246 listener.getClass().getName()
3247 + " is already registered as OnShowErrorToastListener");
3248 }
3249 }
3250 if (remainingListeners) {
3251 switchToForeground();
3252 }
3253 }
3254
3255 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
3256 final boolean remainingListeners;
3257 synchronized (LISTENER_LOCK) {
3258 this.mOnShowErrorToasts.remove(onShowErrorToast);
3259 remainingListeners = checkListeners();
3260 }
3261 if (remainingListeners) {
3262 switchToBackground();
3263 }
3264 }
3265
3266 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
3267 final boolean remainingListeners;
3268 synchronized (LISTENER_LOCK) {
3269 remainingListeners = checkListeners();
3270 if (!this.mOnAccountUpdates.add(listener)) {
3271 Log.w(
3272 Config.LOGTAG,
3273 listener.getClass().getName()
3274 + " is already registered as OnAccountListChangedtListener");
3275 }
3276 }
3277 if (remainingListeners) {
3278 switchToForeground();
3279 }
3280 }
3281
3282 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
3283 final boolean remainingListeners;
3284 synchronized (LISTENER_LOCK) {
3285 this.mOnAccountUpdates.remove(listener);
3286 remainingListeners = checkListeners();
3287 }
3288 if (remainingListeners) {
3289 switchToBackground();
3290 }
3291 }
3292
3293 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3294 final boolean remainingListeners;
3295 synchronized (LISTENER_LOCK) {
3296 remainingListeners = checkListeners();
3297 if (!this.mOnCaptchaRequested.add(listener)) {
3298 Log.w(
3299 Config.LOGTAG,
3300 listener.getClass().getName()
3301 + " is already registered as OnCaptchaRequestListener");
3302 }
3303 }
3304 if (remainingListeners) {
3305 switchToForeground();
3306 }
3307 }
3308
3309 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3310 final boolean remainingListeners;
3311 synchronized (LISTENER_LOCK) {
3312 this.mOnCaptchaRequested.remove(listener);
3313 remainingListeners = checkListeners();
3314 }
3315 if (remainingListeners) {
3316 switchToBackground();
3317 }
3318 }
3319
3320 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
3321 final boolean remainingListeners;
3322 synchronized (LISTENER_LOCK) {
3323 remainingListeners = checkListeners();
3324 if (!this.mOnRosterUpdates.add(listener)) {
3325 Log.w(
3326 Config.LOGTAG,
3327 listener.getClass().getName()
3328 + " is already registered as OnRosterUpdateListener");
3329 }
3330 }
3331 if (remainingListeners) {
3332 switchToForeground();
3333 }
3334 }
3335
3336 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
3337 final boolean remainingListeners;
3338 synchronized (LISTENER_LOCK) {
3339 this.mOnRosterUpdates.remove(listener);
3340 remainingListeners = checkListeners();
3341 }
3342 if (remainingListeners) {
3343 switchToBackground();
3344 }
3345 }
3346
3347 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3348 final boolean remainingListeners;
3349 synchronized (LISTENER_LOCK) {
3350 remainingListeners = checkListeners();
3351 if (!this.mOnUpdateBlocklist.add(listener)) {
3352 Log.w(
3353 Config.LOGTAG,
3354 listener.getClass().getName()
3355 + " is already registered as OnUpdateBlocklistListener");
3356 }
3357 }
3358 if (remainingListeners) {
3359 switchToForeground();
3360 }
3361 }
3362
3363 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3364 final boolean remainingListeners;
3365 synchronized (LISTENER_LOCK) {
3366 this.mOnUpdateBlocklist.remove(listener);
3367 remainingListeners = checkListeners();
3368 }
3369 if (remainingListeners) {
3370 switchToBackground();
3371 }
3372 }
3373
3374 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
3375 final boolean remainingListeners;
3376 synchronized (LISTENER_LOCK) {
3377 remainingListeners = checkListeners();
3378 if (!this.mOnKeyStatusUpdated.add(listener)) {
3379 Log.w(
3380 Config.LOGTAG,
3381 listener.getClass().getName()
3382 + " is already registered as OnKeyStatusUpdateListener");
3383 }
3384 }
3385 if (remainingListeners) {
3386 switchToForeground();
3387 }
3388 }
3389
3390 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
3391 final boolean remainingListeners;
3392 synchronized (LISTENER_LOCK) {
3393 this.mOnKeyStatusUpdated.remove(listener);
3394 remainingListeners = checkListeners();
3395 }
3396 if (remainingListeners) {
3397 switchToBackground();
3398 }
3399 }
3400
3401 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3402 final boolean remainingListeners;
3403 synchronized (LISTENER_LOCK) {
3404 remainingListeners = checkListeners();
3405 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
3406 Log.w(
3407 Config.LOGTAG,
3408 listener.getClass().getName()
3409 + " is already registered as OnJingleRtpConnectionUpdate");
3410 }
3411 }
3412 if (remainingListeners) {
3413 switchToForeground();
3414 }
3415 }
3416
3417 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3418 final boolean remainingListeners;
3419 synchronized (LISTENER_LOCK) {
3420 this.onJingleRtpConnectionUpdate.remove(listener);
3421 remainingListeners = checkListeners();
3422 }
3423 if (remainingListeners) {
3424 switchToBackground();
3425 }
3426 }
3427
3428 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
3429 final boolean remainingListeners;
3430 synchronized (LISTENER_LOCK) {
3431 remainingListeners = checkListeners();
3432 if (!this.mOnMucRosterUpdate.add(listener)) {
3433 Log.w(
3434 Config.LOGTAG,
3435 listener.getClass().getName()
3436 + " is already registered as OnMucRosterListener");
3437 }
3438 }
3439 if (remainingListeners) {
3440 switchToForeground();
3441 }
3442 }
3443
3444 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
3445 final boolean remainingListeners;
3446 synchronized (LISTENER_LOCK) {
3447 this.mOnMucRosterUpdate.remove(listener);
3448 remainingListeners = checkListeners();
3449 }
3450 if (remainingListeners) {
3451 switchToBackground();
3452 }
3453 }
3454
3455 public boolean checkListeners() {
3456 return (this.mOnAccountUpdates.size() == 0
3457 && this.mOnConversationUpdates.size() == 0
3458 && this.mOnRosterUpdates.size() == 0
3459 && this.mOnCaptchaRequested.size() == 0
3460 && this.mOnMucRosterUpdate.size() == 0
3461 && this.mOnUpdateBlocklist.size() == 0
3462 && this.mOnShowErrorToasts.size() == 0
3463 && this.onJingleRtpConnectionUpdate.size() == 0
3464 && this.mOnKeyStatusUpdated.size() == 0);
3465 }
3466
3467 private void switchToForeground() {
3468 toggleSoftDisabled(false);
3469 final boolean broadcastLastActivity = broadcastLastActivity();
3470 for (Conversation conversation : getConversations()) {
3471 if (conversation.getMode() == Conversation.MODE_MULTI) {
3472 conversation.getMucOptions().resetChatState();
3473 } else {
3474 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
3475 }
3476 }
3477 for (Account account : getAccounts()) {
3478 if (account.getStatus() == Account.State.ONLINE) {
3479 account.deactivateGracePeriod();
3480 final XmppConnection connection = account.getXmppConnection();
3481 if (connection != null) {
3482 if (connection.getFeatures().csi()) {
3483 connection.sendActive();
3484 }
3485 if (broadcastLastActivity) {
3486 sendPresence(
3487 account,
3488 false); // send new presence but don't include idle because we are
3489 // not
3490 }
3491 }
3492 }
3493 }
3494 Log.d(Config.LOGTAG, "app switched into foreground");
3495 }
3496
3497 private void switchToBackground() {
3498 final boolean broadcastLastActivity = broadcastLastActivity();
3499 if (broadcastLastActivity) {
3500 mLastActivity = System.currentTimeMillis();
3501 final SharedPreferences.Editor editor = getPreferences().edit();
3502 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3503 editor.apply();
3504 }
3505 for (Account account : getAccounts()) {
3506 if (account.getStatus() == Account.State.ONLINE) {
3507 XmppConnection connection = account.getXmppConnection();
3508 if (connection != null) {
3509 if (broadcastLastActivity) {
3510 sendPresence(account, true);
3511 }
3512 if (connection.getFeatures().csi()) {
3513 connection.sendInactive();
3514 }
3515 }
3516 }
3517 }
3518 this.mNotificationService.setIsInForeground(false);
3519 Log.d(Config.LOGTAG, "app switched into background");
3520 }
3521
3522 public void connectMultiModeConversations(Account account) {
3523 List<Conversation> conversations = getConversations();
3524 for (Conversation conversation : conversations) {
3525 if (conversation.getMode() == Conversation.MODE_MULTI
3526 && conversation.getAccount() == account) {
3527 joinMuc(conversation);
3528 }
3529 }
3530 }
3531
3532 public void mucSelfPingAndRejoin(final Conversation conversation) {
3533 final Account account = conversation.getAccount();
3534 synchronized (account.inProgressConferenceJoins) {
3535 if (account.inProgressConferenceJoins.contains(conversation)) {
3536 Log.d(
3537 Config.LOGTAG,
3538 account.getJid().asBareJid()
3539 + ": canceling muc self ping because join is already under way");
3540 return;
3541 }
3542 }
3543 synchronized (account.inProgressConferencePings) {
3544 if (!account.inProgressConferencePings.add(conversation)) {
3545 Log.d(
3546 Config.LOGTAG,
3547 account.getJid().asBareJid()
3548 + ": canceling muc self ping because ping is already under way");
3549 return;
3550 }
3551 }
3552 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3553 final Iq ping = new Iq(Iq.Type.GET);
3554 ping.setTo(self);
3555 ping.addChild("ping", Namespace.PING);
3556 sendIqPacket(
3557 conversation.getAccount(),
3558 ping,
3559 (response) -> {
3560 if (response.getType() == Iq.Type.ERROR) {
3561 final var error = response.getError();
3562 if (error == null
3563 || error.hasChild("service-unavailable")
3564 || error.hasChild("feature-not-implemented")
3565 || error.hasChild("item-not-found")) {
3566 Log.d(
3567 Config.LOGTAG,
3568 account.getJid().asBareJid()
3569 + ": ping to "
3570 + self
3571 + " came back as ignorable error");
3572 } else {
3573 Log.d(
3574 Config.LOGTAG,
3575 account.getJid().asBareJid()
3576 + ": ping to "
3577 + self
3578 + " failed. attempting rejoin");
3579 joinMuc(conversation);
3580 }
3581 } else if (response.getType() == Iq.Type.RESULT) {
3582 Log.d(
3583 Config.LOGTAG,
3584 account.getJid().asBareJid()
3585 + ": ping to "
3586 + self
3587 + " came back fine");
3588 }
3589 synchronized (account.inProgressConferencePings) {
3590 account.inProgressConferencePings.remove(conversation);
3591 }
3592 });
3593 }
3594
3595 public void joinMuc(Conversation conversation) {
3596 joinMuc(conversation, null, false);
3597 }
3598
3599 public void joinMuc(Conversation conversation, boolean followedInvite) {
3600 joinMuc(conversation, null, followedInvite);
3601 }
3602
3603 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3604 joinMuc(conversation, onConferenceJoined, false);
3605 }
3606
3607 private void joinMuc(
3608 Conversation conversation,
3609 final OnConferenceJoined onConferenceJoined,
3610 final boolean followedInvite) {
3611 final Account account = conversation.getAccount();
3612 synchronized (account.pendingConferenceJoins) {
3613 account.pendingConferenceJoins.remove(conversation);
3614 }
3615 synchronized (account.pendingConferenceLeaves) {
3616 account.pendingConferenceLeaves.remove(conversation);
3617 }
3618 if (account.getStatus() == Account.State.ONLINE) {
3619 synchronized (account.inProgressConferenceJoins) {
3620 account.inProgressConferenceJoins.add(conversation);
3621 }
3622 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3623 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3624 }
3625 conversation.resetMucOptions();
3626 if (onConferenceJoined != null) {
3627 conversation.getMucOptions().flagNoAutoPushConfiguration();
3628 }
3629 conversation.setHasMessagesLeftOnServer(false);
3630 fetchConferenceConfiguration(
3631 conversation,
3632 new OnConferenceConfigurationFetched() {
3633
3634 private void join(Conversation conversation) {
3635 Account account = conversation.getAccount();
3636 final MucOptions mucOptions = conversation.getMucOptions();
3637
3638 if (mucOptions.nonanonymous()
3639 && !mucOptions.membersOnly()
3640 && !conversation.getBooleanAttribute(
3641 "accept_non_anonymous", false)) {
3642 synchronized (account.inProgressConferenceJoins) {
3643 account.inProgressConferenceJoins.remove(conversation);
3644 }
3645 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3646 updateConversationUi();
3647 if (onConferenceJoined != null) {
3648 onConferenceJoined.onConferenceJoined(conversation);
3649 }
3650 return;
3651 }
3652
3653 final Jid joinJid = mucOptions.getSelf().getFullJid();
3654 Log.d(
3655 Config.LOGTAG,
3656 account.getJid().asBareJid().toString()
3657 + ": joining conversation "
3658 + joinJid.toString());
3659 final var packet =
3660 mPresenceGenerator.selfPresence(
3661 account,
3662 Presence.Status.ONLINE,
3663 mucOptions.nonanonymous()
3664 || onConferenceJoined != null);
3665 packet.setTo(joinJid);
3666 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3667 if (conversation.getMucOptions().getPassword() != null) {
3668 x.addChild("password").setContent(mucOptions.getPassword());
3669 }
3670
3671 if (mucOptions.mamSupport()) {
3672 // Use MAM instead of the limited muc history to get history
3673 x.addChild("history").setAttribute("maxchars", "0");
3674 } else {
3675 // Fallback to muc history
3676 x.addChild("history")
3677 .setAttribute(
3678 "since",
3679 PresenceGenerator.getTimestamp(
3680 conversation
3681 .getLastMessageTransmitted()
3682 .getTimestamp()));
3683 }
3684 sendPresencePacket(account, packet);
3685 if (onConferenceJoined != null) {
3686 onConferenceJoined.onConferenceJoined(conversation);
3687 }
3688 if (!joinJid.equals(conversation.getJid())) {
3689 conversation.setContactJid(joinJid);
3690 databaseBackend.updateConversation(conversation);
3691 }
3692
3693 if (mucOptions.mamSupport()) {
3694 getMessageArchiveService().catchupMUC(conversation);
3695 }
3696 if (mucOptions.isPrivateAndNonAnonymous()) {
3697 fetchConferenceMembers(conversation);
3698
3699 if (followedInvite) {
3700 final Bookmark bookmark = conversation.getBookmark();
3701 if (bookmark != null) {
3702 if (!bookmark.autojoin()) {
3703 bookmark.setAutojoin(true);
3704 createBookmark(account, bookmark);
3705 }
3706 } else {
3707 saveConversationAsBookmark(conversation, null);
3708 }
3709 }
3710 }
3711 synchronized (account.inProgressConferenceJoins) {
3712 account.inProgressConferenceJoins.remove(conversation);
3713 sendUnsentMessages(conversation);
3714 }
3715 }
3716
3717 @Override
3718 public void onConferenceConfigurationFetched(Conversation conversation) {
3719 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3720 Log.d(
3721 Config.LOGTAG,
3722 account.getJid().asBareJid()
3723 + ": conversation ("
3724 + conversation.getJid()
3725 + ") got archived before IQ result");
3726 return;
3727 }
3728 join(conversation);
3729 }
3730
3731 @Override
3732 public void onFetchFailed(
3733 final Conversation conversation, final String errorCondition) {
3734 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3735 Log.d(
3736 Config.LOGTAG,
3737 account.getJid().asBareJid()
3738 + ": conversation ("
3739 + conversation.getJid()
3740 + ") got archived before IQ result");
3741 return;
3742 }
3743 if ("remote-server-not-found".equals(errorCondition)) {
3744 synchronized (account.inProgressConferenceJoins) {
3745 account.inProgressConferenceJoins.remove(conversation);
3746 }
3747 conversation
3748 .getMucOptions()
3749 .setError(MucOptions.Error.SERVER_NOT_FOUND);
3750 updateConversationUi();
3751 } else {
3752 join(conversation);
3753 fetchConferenceConfiguration(conversation);
3754 }
3755 }
3756 });
3757 updateConversationUi();
3758 } else {
3759 synchronized (account.pendingConferenceJoins) {
3760 account.pendingConferenceJoins.add(conversation);
3761 }
3762 conversation.resetMucOptions();
3763 conversation.setHasMessagesLeftOnServer(false);
3764 updateConversationUi();
3765 }
3766 }
3767
3768 private void fetchConferenceMembers(final Conversation conversation) {
3769 final Account account = conversation.getAccount();
3770 final AxolotlService axolotlService = account.getAxolotlService();
3771 final String[] affiliations = {"member", "admin", "owner"};
3772 final Consumer<Iq> callback =
3773 new Consumer<Iq>() {
3774
3775 private int i = 0;
3776 private boolean success = true;
3777
3778 @Override
3779 public void accept(Iq response) {
3780 final boolean omemoEnabled =
3781 conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3782 Element query = response.query("http://jabber.org/protocol/muc#admin");
3783 if (response.getType() == Iq.Type.RESULT && query != null) {
3784 for (Element child : query.getChildren()) {
3785 if ("item".equals(child.getName())) {
3786 MucOptions.User user =
3787 AbstractParser.parseItem(conversation, child);
3788 if (!user.realJidMatchesAccount()) {
3789 boolean isNew =
3790 conversation.getMucOptions().updateUser(user);
3791 Contact contact = user.getContact();
3792 if (omemoEnabled
3793 && isNew
3794 && user.getRealJid() != null
3795 && (contact == null
3796 || !contact.mutualPresenceSubscription())
3797 && axolotlService.hasEmptyDeviceList(
3798 user.getRealJid())) {
3799 axolotlService.fetchDeviceIds(user.getRealJid());
3800 }
3801 }
3802 }
3803 }
3804 } else {
3805 success = false;
3806 Log.d(
3807 Config.LOGTAG,
3808 account.getJid().asBareJid()
3809 + ": could not request affiliation "
3810 + affiliations[i]
3811 + " in "
3812 + conversation.getJid().asBareJid());
3813 }
3814 ++i;
3815 if (i >= affiliations.length) {
3816 List<Jid> members = conversation.getMucOptions().getMembers(true);
3817 if (success) {
3818 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3819 boolean changed = false;
3820 for (ListIterator<Jid> iterator = cryptoTargets.listIterator();
3821 iterator.hasNext(); ) {
3822 Jid jid = iterator.next();
3823 if (!members.contains(jid)
3824 && !members.contains(jid.getDomain())) {
3825 iterator.remove();
3826 Log.d(
3827 Config.LOGTAG,
3828 account.getJid().asBareJid()
3829 + ": removed "
3830 + jid
3831 + " from crypto targets of "
3832 + conversation.getName());
3833 changed = true;
3834 }
3835 }
3836 if (changed) {
3837 conversation.setAcceptedCryptoTargets(cryptoTargets);
3838 updateConversation(conversation);
3839 }
3840 }
3841 getAvatarService().clear(conversation);
3842 updateMucRosterUi();
3843 updateConversationUi();
3844 }
3845 }
3846 };
3847 for (String affiliation : affiliations) {
3848 sendIqPacket(
3849 account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3850 }
3851 Log.d(
3852 Config.LOGTAG,
3853 account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3854 }
3855
3856 public void providePasswordForMuc(final Conversation conversation, final String password) {
3857 if (conversation.getMode() == Conversation.MODE_MULTI) {
3858 conversation.getMucOptions().setPassword(password);
3859 if (conversation.getBookmark() != null) {
3860 final Bookmark bookmark = conversation.getBookmark();
3861 bookmark.setAutojoin(true);
3862 createBookmark(conversation.getAccount(), bookmark);
3863 }
3864 updateConversation(conversation);
3865 joinMuc(conversation);
3866 }
3867 }
3868
3869 public void deleteAvatar(final Account account) {
3870 final AtomicBoolean executed = new AtomicBoolean(false);
3871 final Runnable onDeleted =
3872 () -> {
3873 if (executed.compareAndSet(false, true)) {
3874 account.setAvatar(null);
3875 databaseBackend.updateAccount(account);
3876 getAvatarService().clear(account);
3877 updateAccountUi();
3878 }
3879 };
3880 deleteVcardAvatar(account, onDeleted);
3881 deletePepNode(account, Namespace.AVATAR_DATA);
3882 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3883 }
3884
3885 public void deletePepNode(final Account account, final String node) {
3886 deletePepNode(account, node, null);
3887 }
3888
3889 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3890 final Iq request = mIqGenerator.deleteNode(node);
3891 sendIqPacket(
3892 account,
3893 request,
3894 (packet) -> {
3895 if (packet.getType() == Iq.Type.RESULT) {
3896 Log.d(
3897 Config.LOGTAG,
3898 account.getJid().asBareJid()
3899 + ": successfully deleted pep node "
3900 + node);
3901 if (runnable != null) {
3902 runnable.run();
3903 }
3904 } else {
3905 Log.d(
3906 Config.LOGTAG,
3907 account.getJid().asBareJid() + ": failed to delete " + packet);
3908 }
3909 });
3910 }
3911
3912 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3913 final Iq retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3914 sendIqPacket(
3915 account,
3916 retrieveVcard,
3917 (response) -> {
3918 if (response.getType() != Iq.Type.RESULT) {
3919 Log.d(
3920 Config.LOGTAG,
3921 account.getJid().asBareJid() + ": no vCard set. nothing to do");
3922 return;
3923 }
3924 final Element vcard = response.findChild("vCard", "vcard-temp");
3925 if (vcard == null) {
3926 Log.d(
3927 Config.LOGTAG,
3928 account.getJid().asBareJid() + ": no vCard set. nothing to do");
3929 return;
3930 }
3931 Element photo = vcard.findChild("PHOTO");
3932 if (photo == null) {
3933 photo = vcard.addChild("PHOTO");
3934 }
3935 photo.clearChildren();
3936 final Iq publication = new Iq(Iq.Type.SET);
3937 publication.setTo(account.getJid().asBareJid());
3938 publication.addChild(vcard);
3939 sendIqPacket(
3940 account,
3941 publication,
3942 (publicationResponse) -> {
3943 if (publicationResponse.getType() == Iq.Type.RESULT) {
3944 Log.d(
3945 Config.LOGTAG,
3946 account.getJid().asBareJid()
3947 + ": successfully deleted vcard avatar");
3948 runnable.run();
3949 } else {
3950 Log.d(
3951 Config.LOGTAG,
3952 "failed to publish vcard "
3953 + publicationResponse.getErrorCondition());
3954 }
3955 });
3956 });
3957 }
3958
3959 private boolean hasEnabledAccounts() {
3960 if (this.accounts == null) {
3961 return false;
3962 }
3963 for (final Account account : this.accounts) {
3964 if (account.isConnectionEnabled()) {
3965 return true;
3966 }
3967 }
3968 return false;
3969 }
3970
3971 public void getAttachments(
3972 final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3973 getAttachments(
3974 conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3975 }
3976
3977 public void getAttachments(
3978 final Account account,
3979 final Jid jid,
3980 final int limit,
3981 final OnMediaLoaded onMediaLoaded) {
3982 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3983 }
3984
3985 public void getAttachments(
3986 final String account,
3987 final Jid jid,
3988 final int limit,
3989 final OnMediaLoaded onMediaLoaded) {
3990 new Thread(
3991 () ->
3992 onMediaLoaded.onMediaLoaded(
3993 fileBackend.convertToAttachments(
3994 databaseBackend.getRelativeFilePaths(
3995 account, jid, limit))))
3996 .start();
3997 }
3998
3999 public void persistSelfNick(final MucOptions.User self, final boolean modified) {
4000 final Conversation conversation = self.getConversation();
4001 final Account account = conversation.getAccount();
4002 final Jid full = self.getFullJid();
4003 if (!full.equals(conversation.getJid())) {
4004 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisting full jid " + full);
4005 conversation.setContactJid(full);
4006 databaseBackend.updateConversation(conversation);
4007 }
4008
4009 final Bookmark bookmark = conversation.getBookmark();
4010 if (bookmark == null || !modified) {
4011 return;
4012 }
4013 final var nick = full.getResource();
4014 final String defaultNick = MucOptions.defaultNick(account);
4015 if (nick.equals(defaultNick) || nick.equals(bookmark.getNick())) {
4016 return;
4017 }
4018 Log.d(
4019 Config.LOGTAG,
4020 account.getJid().asBareJid()
4021 + ": persist nick '"
4022 + full.getResource()
4023 + "' into bookmark for "
4024 + conversation.getJid().asBareJid());
4025 bookmark.setNick(nick);
4026 createBookmark(bookmark.getAccount(), bookmark);
4027 }
4028
4029 public boolean renameInMuc(
4030 final Conversation conversation,
4031 final String nick,
4032 final UiCallback<Conversation> callback) {
4033 final Account account = conversation.getAccount();
4034 final Bookmark bookmark = conversation.getBookmark();
4035 final MucOptions options = conversation.getMucOptions();
4036 final Jid joinJid = options.createJoinJid(nick);
4037 if (joinJid == null) {
4038 return false;
4039 }
4040 if (options.online()) {
4041 options.setOnRenameListener(
4042 new OnRenameListener() {
4043
4044 @Override
4045 public void onSuccess() {
4046 callback.success(conversation);
4047 }
4048
4049 @Override
4050 public void onFailure() {
4051 callback.error(R.string.nick_in_use, conversation);
4052 }
4053 });
4054
4055 final var packet =
4056 mPresenceGenerator.selfPresence(
4057 account, Presence.Status.ONLINE, options.nonanonymous());
4058 packet.setTo(joinJid);
4059 sendPresencePacket(account, packet);
4060 if (nick.equals(MucOptions.defaultNick(account))
4061 && bookmark != null
4062 && bookmark.getNick() != null) {
4063 Log.d(
4064 Config.LOGTAG,
4065 account.getJid().asBareJid()
4066 + ": removing nick from bookmark for "
4067 + bookmark.getJid());
4068 bookmark.setNick(null);
4069 createBookmark(account, bookmark);
4070 }
4071 } else {
4072 conversation.setContactJid(joinJid);
4073 databaseBackend.updateConversation(conversation);
4074 if (account.getStatus() == Account.State.ONLINE) {
4075 if (bookmark != null) {
4076 bookmark.setNick(nick);
4077 createBookmark(account, bookmark);
4078 }
4079 joinMuc(conversation);
4080 }
4081 }
4082 return true;
4083 }
4084
4085 public void checkMucRequiresRename() {
4086 synchronized (this.conversations) {
4087 for (final Conversation conversation : this.conversations) {
4088 if (conversation.getMode() == Conversational.MODE_MULTI) {
4089 checkMucRequiresRename(conversation);
4090 }
4091 }
4092 }
4093 }
4094
4095 private void checkMucRequiresRename(final Conversation conversation) {
4096 final var options = conversation.getMucOptions();
4097 if (!options.online()) {
4098 return;
4099 }
4100 final var account = conversation.getAccount();
4101 final String current = options.getActualNick();
4102 final String proposed = options.getProposedNickPure();
4103 if (current == null || current.equals(proposed)) {
4104 return;
4105 }
4106 final Jid joinJid = options.createJoinJid(proposed);
4107 Log.d(
4108 Config.LOGTAG,
4109 String.format(
4110 "%s: muc rename required %s (was: %s)",
4111 account.getJid().asBareJid(), joinJid, current));
4112 final var packet =
4113 mPresenceGenerator.selfPresence(
4114 account, Presence.Status.ONLINE, options.nonanonymous());
4115 packet.setTo(joinJid);
4116 sendPresencePacket(account, packet);
4117 }
4118
4119 public void leaveMuc(Conversation conversation) {
4120 leaveMuc(conversation, false);
4121 }
4122
4123 private void leaveMuc(Conversation conversation, boolean now) {
4124 final Account account = conversation.getAccount();
4125 synchronized (account.pendingConferenceJoins) {
4126 account.pendingConferenceJoins.remove(conversation);
4127 }
4128 synchronized (account.pendingConferenceLeaves) {
4129 account.pendingConferenceLeaves.remove(conversation);
4130 }
4131 if (account.getStatus() == Account.State.ONLINE || now) {
4132 sendPresencePacket(
4133 conversation.getAccount(),
4134 mPresenceGenerator.leave(conversation.getMucOptions()));
4135 conversation.getMucOptions().setOffline();
4136 Bookmark bookmark = conversation.getBookmark();
4137 if (bookmark != null) {
4138 bookmark.setConversation(null);
4139 }
4140 Log.d(
4141 Config.LOGTAG,
4142 conversation.getAccount().getJid().asBareJid()
4143 + ": leaving muc "
4144 + conversation.getJid());
4145 } else {
4146 synchronized (account.pendingConferenceLeaves) {
4147 account.pendingConferenceLeaves.add(conversation);
4148 }
4149 }
4150 }
4151
4152 public String findConferenceServer(final Account account) {
4153 String server;
4154 if (account.getXmppConnection() != null) {
4155 server = account.getXmppConnection().getMucServer();
4156 if (server != null) {
4157 return server;
4158 }
4159 }
4160 for (Account other : getAccounts()) {
4161 if (other != account && other.getXmppConnection() != null) {
4162 server = other.getXmppConnection().getMucServer();
4163 if (server != null) {
4164 return server;
4165 }
4166 }
4167 }
4168 return null;
4169 }
4170
4171 public void createPublicChannel(
4172 final Account account,
4173 final String name,
4174 final Jid address,
4175 final UiCallback<Conversation> callback) {
4176 joinMuc(
4177 findOrCreateConversation(account, address, true, false, true),
4178 conversation -> {
4179 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
4180 if (!TextUtils.isEmpty(name)) {
4181 configuration.putString("muc#roomconfig_roomname", name);
4182 }
4183 pushConferenceConfiguration(
4184 conversation,
4185 configuration,
4186 new OnConfigurationPushed() {
4187 @Override
4188 public void onPushSucceeded() {
4189 saveConversationAsBookmark(conversation, name);
4190 callback.success(conversation);
4191 }
4192
4193 @Override
4194 public void onPushFailed() {
4195 if (conversation
4196 .getMucOptions()
4197 .getSelf()
4198 .getAffiliation()
4199 .ranks(MucOptions.Affiliation.OWNER)) {
4200 callback.error(
4201 R.string.unable_to_set_channel_configuration,
4202 conversation);
4203 } else {
4204 callback.error(
4205 R.string.joined_an_existing_channel, conversation);
4206 }
4207 }
4208 });
4209 });
4210 }
4211
4212 public boolean createAdhocConference(
4213 final Account account,
4214 final String name,
4215 final Iterable<Jid> jids,
4216 final UiCallback<Conversation> callback) {
4217 Log.d(
4218 Config.LOGTAG,
4219 account.getJid().asBareJid().toString()
4220 + ": creating adhoc conference with "
4221 + jids.toString());
4222 if (account.getStatus() == Account.State.ONLINE) {
4223 try {
4224 String server = findConferenceServer(account);
4225 if (server == null) {
4226 if (callback != null) {
4227 callback.error(R.string.no_conference_server_found, null);
4228 }
4229 return false;
4230 }
4231 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
4232 final Conversation conversation =
4233 findOrCreateConversation(account, jid, true, false, true);
4234 joinMuc(
4235 conversation,
4236 new OnConferenceJoined() {
4237 @Override
4238 public void onConferenceJoined(final Conversation conversation) {
4239 final Bundle configuration =
4240 IqGenerator.defaultGroupChatConfiguration();
4241 if (!TextUtils.isEmpty(name)) {
4242 configuration.putString("muc#roomconfig_roomname", name);
4243 }
4244 pushConferenceConfiguration(
4245 conversation,
4246 configuration,
4247 new OnConfigurationPushed() {
4248 @Override
4249 public void onPushSucceeded() {
4250 for (Jid invite : jids) {
4251 invite(conversation, invite);
4252 }
4253 for (String resource :
4254 account.getSelfContact()
4255 .getPresences()
4256 .toResourceArray()) {
4257 Jid other =
4258 account.getJid().withResource(resource);
4259 Log.d(
4260 Config.LOGTAG,
4261 account.getJid().asBareJid()
4262 + ": sending direct invite to "
4263 + other);
4264 directInvite(conversation, other);
4265 }
4266 saveConversationAsBookmark(conversation, name);
4267 if (callback != null) {
4268 callback.success(conversation);
4269 }
4270 }
4271
4272 @Override
4273 public void onPushFailed() {
4274 archiveConversation(conversation);
4275 if (callback != null) {
4276 callback.error(
4277 R.string.conference_creation_failed,
4278 conversation);
4279 }
4280 }
4281 });
4282 }
4283 });
4284 return true;
4285 } catch (IllegalArgumentException e) {
4286 if (callback != null) {
4287 callback.error(R.string.conference_creation_failed, null);
4288 }
4289 return false;
4290 }
4291 } else {
4292 if (callback != null) {
4293 callback.error(R.string.not_connected_try_again, null);
4294 }
4295 return false;
4296 }
4297 }
4298
4299 public void fetchConferenceConfiguration(final Conversation conversation) {
4300 fetchConferenceConfiguration(conversation, null);
4301 }
4302
4303 public void fetchConferenceConfiguration(
4304 final Conversation conversation, final OnConferenceConfigurationFetched callback) {
4305 final Iq request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
4306 final var account = conversation.getAccount();
4307 sendIqPacket(
4308 account,
4309 request,
4310 response -> {
4311 if (response.getType() == Iq.Type.RESULT) {
4312 final MucOptions mucOptions = conversation.getMucOptions();
4313 final Bookmark bookmark = conversation.getBookmark();
4314 final boolean sameBefore =
4315 StringUtils.equals(
4316 bookmark == null ? null : bookmark.getBookmarkName(),
4317 mucOptions.getName());
4318
4319 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(response))) {
4320 Log.d(
4321 Config.LOGTAG,
4322 account.getJid().asBareJid()
4323 + ": muc configuration changed for "
4324 + conversation.getJid().asBareJid());
4325 updateConversation(conversation);
4326 }
4327
4328 if (bookmark != null
4329 && (sameBefore || bookmark.getBookmarkName() == null)) {
4330 if (bookmark.setBookmarkName(
4331 StringUtils.nullOnEmpty(mucOptions.getName()))) {
4332 createBookmark(account, bookmark);
4333 }
4334 }
4335
4336 if (callback != null) {
4337 callback.onConferenceConfigurationFetched(conversation);
4338 }
4339
4340 updateConversationUi();
4341 } else if (response.getType() == Iq.Type.TIMEOUT) {
4342 Log.d(
4343 Config.LOGTAG,
4344 account.getJid().asBareJid()
4345 + ": received timeout waiting for conference configuration"
4346 + " fetch");
4347 } else {
4348 if (callback != null) {
4349 callback.onFetchFailed(conversation, response.getErrorCondition());
4350 }
4351 }
4352 });
4353 }
4354
4355 public void pushNodeConfiguration(
4356 Account account,
4357 final String node,
4358 final Bundle options,
4359 final OnConfigurationPushed callback) {
4360 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
4361 }
4362
4363 public void pushNodeConfiguration(
4364 Account account,
4365 final Jid jid,
4366 final String node,
4367 final Bundle options,
4368 final OnConfigurationPushed callback) {
4369 Log.d(Config.LOGTAG, "pushing node configuration");
4370 sendIqPacket(
4371 account,
4372 mIqGenerator.requestPubsubConfiguration(jid, node),
4373 responseToRequest -> {
4374 if (responseToRequest.getType() == Iq.Type.RESULT) {
4375 Element pubsub =
4376 responseToRequest.findChild(
4377 "pubsub", "http://jabber.org/protocol/pubsub#owner");
4378 Element configuration =
4379 pubsub == null ? null : pubsub.findChild("configure");
4380 Element x =
4381 configuration == null
4382 ? null
4383 : configuration.findChild("x", Namespace.DATA);
4384 if (x != null) {
4385 final Data data = Data.parse(x);
4386 data.submit(options);
4387 sendIqPacket(
4388 account,
4389 mIqGenerator.publishPubsubConfiguration(jid, node, data),
4390 responseToPublish -> {
4391 if (responseToPublish.getType() == Iq.Type.RESULT
4392 && callback != null) {
4393 Log.d(
4394 Config.LOGTAG,
4395 account.getJid().asBareJid()
4396 + ": successfully changed node"
4397 + " configuration for node "
4398 + node);
4399 callback.onPushSucceeded();
4400 } else if (responseToPublish.getType() == Iq.Type.ERROR
4401 && callback != null) {
4402 callback.onPushFailed();
4403 }
4404 });
4405 } else if (callback != null) {
4406 callback.onPushFailed();
4407 }
4408 } else if (responseToRequest.getType() == Iq.Type.ERROR && callback != null) {
4409 callback.onPushFailed();
4410 }
4411 });
4412 }
4413
4414 public void pushConferenceConfiguration(
4415 final Conversation conversation,
4416 final Bundle options,
4417 final OnConfigurationPushed callback) {
4418 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
4419 conversation.setAttribute("accept_non_anonymous", true);
4420 updateConversation(conversation);
4421 }
4422 if (options.containsKey("muc#roomconfig_moderatedroom")) {
4423 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
4424 options.putString("members_by_default", moderated ? "0" : "1");
4425 }
4426 if (options.containsKey("muc#roomconfig_allowpm")) {
4427 // ejabberd :-/
4428 final boolean allow = "anyone".equals(options.getString("muc#roomconfig_allowpm"));
4429 options.putString("allow_private_messages", allow ? "1" : "0");
4430 options.putString("allow_private_messages_from_visitors", allow ? "anyone" : "nobody");
4431 }
4432 final var account = conversation.getAccount();
4433 final Iq request = new Iq(Iq.Type.GET);
4434 request.setTo(conversation.getJid().asBareJid());
4435 request.query("http://jabber.org/protocol/muc#owner");
4436 sendIqPacket(
4437 account,
4438 request,
4439 response -> {
4440 if (response.getType() == Iq.Type.RESULT) {
4441 final Data data =
4442 Data.parse(response.query().findChild("x", Namespace.DATA));
4443 data.submit(options);
4444 final Iq set = new Iq(Iq.Type.SET);
4445 set.setTo(conversation.getJid().asBareJid());
4446 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
4447 sendIqPacket(
4448 account,
4449 set,
4450 packet -> {
4451 if (callback != null) {
4452 if (packet.getType() == Iq.Type.RESULT) {
4453 callback.onPushSucceeded();
4454 } else {
4455 Log.d(Config.LOGTAG, "failed: " + packet.toString());
4456 callback.onPushFailed();
4457 }
4458 }
4459 });
4460 } else {
4461 if (callback != null) {
4462 callback.onPushFailed();
4463 }
4464 }
4465 });
4466 }
4467
4468 public void pushSubjectToConference(final Conversation conference, final String subject) {
4469 final var packet =
4470 this.getMessageGenerator()
4471 .conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4472 this.sendMessagePacket(conference.getAccount(), packet);
4473 }
4474
4475 public void changeAffiliationInConference(
4476 final Conversation conference,
4477 Jid user,
4478 final MucOptions.Affiliation affiliation,
4479 final OnAffiliationChanged callback) {
4480 final Jid jid = user.asBareJid();
4481 final Iq request =
4482 this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4483 sendIqPacket(
4484 conference.getAccount(),
4485 request,
4486 (response) -> {
4487 if (response.getType() == Iq.Type.RESULT) {
4488 conference.getMucOptions().changeAffiliation(jid, affiliation);
4489 getAvatarService().clear(conference);
4490 if (callback != null) {
4491 callback.onAffiliationChangedSuccessful(jid);
4492 } else {
4493 Log.d(
4494 Config.LOGTAG,
4495 "changed affiliation of " + user + " to " + affiliation);
4496 }
4497 } else if (callback != null) {
4498 callback.onAffiliationChangeFailed(
4499 jid, R.string.could_not_change_affiliation);
4500 } else {
4501 Log.d(Config.LOGTAG, "unable to change affiliation");
4502 }
4503 });
4504 }
4505
4506 public void changeRoleInConference(
4507 final Conversation conference, final String nick, MucOptions.Role role) {
4508 final var account = conference.getAccount();
4509 final Iq request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4510 sendIqPacket(
4511 account,
4512 request,
4513 (packet) -> {
4514 if (packet.getType() != Iq.Type.RESULT) {
4515 Log.d(
4516 Config.LOGTAG,
4517 account.getJid().asBareJid() + " unable to change role of " + nick);
4518 }
4519 });
4520 }
4521
4522 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4523 final Iq request = new Iq(Iq.Type.SET);
4524 request.setTo(conversation.getJid().asBareJid());
4525 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4526 sendIqPacket(
4527 conversation.getAccount(),
4528 request,
4529 response -> {
4530 if (response.getType() == Iq.Type.RESULT) {
4531 if (callback != null) {
4532 callback.onRoomDestroySucceeded();
4533 }
4534 } else if (response.getType() == Iq.Type.ERROR) {
4535 if (callback != null) {
4536 callback.onRoomDestroyFailed();
4537 }
4538 }
4539 });
4540 }
4541
4542 private void disconnect(final Account account, boolean force) {
4543 final XmppConnection connection = account.getXmppConnection();
4544 if (connection == null) {
4545 return;
4546 }
4547 if (!force) {
4548 final List<Conversation> conversations = getConversations();
4549 for (Conversation conversation : conversations) {
4550 if (conversation.getAccount() == account) {
4551 if (conversation.getMode() == Conversation.MODE_MULTI) {
4552 leaveMuc(conversation, true);
4553 }
4554 }
4555 }
4556 sendOfflinePresence(account);
4557 }
4558 connection.disconnect(force);
4559 }
4560
4561 @Override
4562 public IBinder onBind(Intent intent) {
4563 return mBinder;
4564 }
4565
4566 public void updateMessage(Message message) {
4567 updateMessage(message, true);
4568 }
4569
4570 public void updateMessage(Message message, boolean includeBody) {
4571 databaseBackend.updateMessage(message, includeBody);
4572 updateConversationUi();
4573 }
4574
4575 public void createMessageAsync(final Message message) {
4576 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4577 }
4578
4579 public void updateMessage(Message message, String uuid) {
4580 if (!databaseBackend.updateMessage(message, uuid)) {
4581 Log.e(Config.LOGTAG, "error updated message in DB after edit");
4582 }
4583 updateConversationUi();
4584 }
4585
4586 public void syncDirtyContacts(Account account) {
4587 for (Contact contact : account.getRoster().getContacts()) {
4588 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
4589 pushContactToServer(contact);
4590 }
4591 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
4592 deleteContactOnServer(contact);
4593 }
4594 }
4595 }
4596
4597 public void createContact(final Contact contact, final boolean autoGrant) {
4598 createContact(contact, autoGrant, null);
4599 }
4600
4601 public void createContact(
4602 final Contact contact, final boolean autoGrant, final String preAuth) {
4603 if (autoGrant) {
4604 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4605 contact.setOption(Contact.Options.ASKING);
4606 }
4607 pushContactToServer(contact, preAuth);
4608 }
4609
4610 public void pushContactToServer(final Contact contact) {
4611 pushContactToServer(contact, null);
4612 }
4613
4614 private void pushContactToServer(final Contact contact, final String preAuth) {
4615 contact.resetOption(Contact.Options.DIRTY_DELETE);
4616 contact.setOption(Contact.Options.DIRTY_PUSH);
4617 final Account account = contact.getAccount();
4618 if (account.getStatus() == Account.State.ONLINE) {
4619 final boolean ask = contact.getOption(Contact.Options.ASKING);
4620 final boolean sendUpdates =
4621 contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
4622 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
4623 final Iq iq = new Iq(Iq.Type.SET);
4624 iq.query(Namespace.ROSTER).addChild(contact.asElement());
4625 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4626 if (sendUpdates) {
4627 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
4628 }
4629 if (ask) {
4630 sendPresencePacket(
4631 account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
4632 }
4633 } else {
4634 syncRoster(contact.getAccount());
4635 }
4636 }
4637
4638 public void publishMucAvatar(
4639 final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4640 new Thread(
4641 () -> {
4642 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4643 final int size = Config.AVATAR_SIZE;
4644 final Avatar avatar =
4645 getFileBackend().getPepAvatar(image, size, format);
4646 if (avatar != null) {
4647 if (!getFileBackend().save(avatar)) {
4648 callback.onAvatarPublicationFailed(
4649 R.string.error_saving_avatar);
4650 return;
4651 }
4652 avatar.owner = conversation.getJid().asBareJid();
4653 publishMucAvatar(conversation, avatar, callback);
4654 } else {
4655 callback.onAvatarPublicationFailed(
4656 R.string.error_publish_avatar_converting);
4657 }
4658 })
4659 .start();
4660 }
4661
4662 public void publishAvatar(
4663 final Account account, final Uri image, final OnAvatarPublication callback) {
4664 new Thread(
4665 () -> {
4666 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4667 final int size = Config.AVATAR_SIZE;
4668 final Avatar avatar =
4669 getFileBackend().getPepAvatar(image, size, format);
4670 if (avatar != null) {
4671 if (!getFileBackend().save(avatar)) {
4672 Log.d(Config.LOGTAG, "unable to save vcard");
4673 callback.onAvatarPublicationFailed(
4674 R.string.error_saving_avatar);
4675 return;
4676 }
4677 publishAvatar(account, avatar, callback);
4678 } else {
4679 callback.onAvatarPublicationFailed(
4680 R.string.error_publish_avatar_converting);
4681 }
4682 })
4683 .start();
4684 }
4685
4686 private void publishMucAvatar(
4687 Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4688 final var account = conversation.getAccount();
4689 final Iq retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4690 sendIqPacket(
4691 account,
4692 retrieve,
4693 (response) -> {
4694 boolean itemNotFound =
4695 response.getType() == Iq.Type.ERROR
4696 && response.hasChild("error")
4697 && response.findChild("error").hasChild("item-not-found");
4698 if (response.getType() == Iq.Type.RESULT || itemNotFound) {
4699 Element vcard = response.findChild("vCard", "vcard-temp");
4700 if (vcard == null) {
4701 vcard = new Element("vCard", "vcard-temp");
4702 }
4703 Element photo = vcard.findChild("PHOTO");
4704 if (photo == null) {
4705 photo = vcard.addChild("PHOTO");
4706 }
4707 photo.clearChildren();
4708 photo.addChild("TYPE").setContent(avatar.type);
4709 photo.addChild("BINVAL").setContent(avatar.image);
4710 final Iq publication = new Iq(Iq.Type.SET);
4711 publication.setTo(conversation.getJid().asBareJid());
4712 publication.addChild(vcard);
4713 sendIqPacket(
4714 account,
4715 publication,
4716 (publicationResponse) -> {
4717 if (publicationResponse.getType() == Iq.Type.RESULT) {
4718 callback.onAvatarPublicationSucceeded();
4719 } else {
4720 Log.d(
4721 Config.LOGTAG,
4722 "failed to publish vcard "
4723 + publicationResponse.getErrorCondition());
4724 callback.onAvatarPublicationFailed(
4725 R.string.error_publish_avatar_server_reject);
4726 }
4727 });
4728 } else {
4729 Log.d(Config.LOGTAG, "failed to request vcard " + response);
4730 callback.onAvatarPublicationFailed(
4731 R.string.error_publish_avatar_no_server_support);
4732 }
4733 });
4734 }
4735
4736 public void publishAvatar(
4737 Account account, final Avatar avatar, final OnAvatarPublication callback) {
4738 final Bundle options;
4739 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4740 options = PublishOptions.openAccess();
4741 } else {
4742 options = null;
4743 }
4744 publishAvatar(account, avatar, options, true, callback);
4745 }
4746
4747 public void publishAvatar(
4748 Account account,
4749 final Avatar avatar,
4750 final Bundle options,
4751 final boolean retry,
4752 final OnAvatarPublication callback) {
4753 Log.d(
4754 Config.LOGTAG,
4755 account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4756 final Iq packet = this.mIqGenerator.publishAvatar(avatar, options);
4757 this.sendIqPacket(
4758 account,
4759 packet,
4760 result -> {
4761 if (result.getType() == Iq.Type.RESULT) {
4762 publishAvatarMetadata(account, avatar, options, true, callback);
4763 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4764 pushNodeConfiguration(
4765 account,
4766 Namespace.AVATAR_DATA,
4767 options,
4768 new OnConfigurationPushed() {
4769 @Override
4770 public void onPushSucceeded() {
4771 Log.d(
4772 Config.LOGTAG,
4773 account.getJid().asBareJid()
4774 + ": changed node configuration for avatar"
4775 + " node");
4776 publishAvatar(account, avatar, options, false, callback);
4777 }
4778
4779 @Override
4780 public void onPushFailed() {
4781 Log.d(
4782 Config.LOGTAG,
4783 account.getJid().asBareJid()
4784 + ": unable to change node configuration"
4785 + " for avatar node");
4786 publishAvatar(account, avatar, null, false, callback);
4787 }
4788 });
4789 } else {
4790 Element error = result.findChild("error");
4791 Log.d(
4792 Config.LOGTAG,
4793 account.getJid().asBareJid()
4794 + ": server rejected avatar "
4795 + (avatar.size / 1024)
4796 + "KiB "
4797 + (error != null ? error.toString() : ""));
4798 if (callback != null) {
4799 callback.onAvatarPublicationFailed(
4800 R.string.error_publish_avatar_server_reject);
4801 }
4802 }
4803 });
4804 }
4805
4806 public void publishAvatarMetadata(
4807 Account account,
4808 final Avatar avatar,
4809 final Bundle options,
4810 final boolean retry,
4811 final OnAvatarPublication callback) {
4812 final Iq packet =
4813 XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4814 sendIqPacket(
4815 account,
4816 packet,
4817 result -> {
4818 if (result.getType() == Iq.Type.RESULT) {
4819 if (account.setAvatar(avatar.getFilename())) {
4820 getAvatarService().clear(account);
4821 databaseBackend.updateAccount(account);
4822 notifyAccountAvatarHasChanged(account);
4823 }
4824 Log.d(
4825 Config.LOGTAG,
4826 account.getJid().asBareJid()
4827 + ": published avatar "
4828 + (avatar.size / 1024)
4829 + "KiB");
4830 if (callback != null) {
4831 callback.onAvatarPublicationSucceeded();
4832 }
4833 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4834 pushNodeConfiguration(
4835 account,
4836 Namespace.AVATAR_METADATA,
4837 options,
4838 new OnConfigurationPushed() {
4839 @Override
4840 public void onPushSucceeded() {
4841 Log.d(
4842 Config.LOGTAG,
4843 account.getJid().asBareJid()
4844 + ": changed node configuration for avatar"
4845 + " meta data node");
4846 publishAvatarMetadata(
4847 account, avatar, options, false, callback);
4848 }
4849
4850 @Override
4851 public void onPushFailed() {
4852 Log.d(
4853 Config.LOGTAG,
4854 account.getJid().asBareJid()
4855 + ": unable to change node configuration"
4856 + " for avatar meta data node");
4857 publishAvatarMetadata(
4858 account, avatar, null, false, callback);
4859 }
4860 });
4861 } else {
4862 if (callback != null) {
4863 callback.onAvatarPublicationFailed(
4864 R.string.error_publish_avatar_server_reject);
4865 }
4866 }
4867 });
4868 }
4869
4870 public void republishAvatarIfNeeded(Account account) {
4871 if (account.getAxolotlService().isPepBroken()) {
4872 Log.d(
4873 Config.LOGTAG,
4874 account.getJid().asBareJid()
4875 + ": skipping republication of avatar because pep is broken");
4876 return;
4877 }
4878 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4879 this.sendIqPacket(
4880 account,
4881 packet,
4882 new Consumer<Iq>() {
4883
4884 private Avatar parseAvatar(Iq packet) {
4885 Element pubsub =
4886 packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4887 if (pubsub != null) {
4888 Element items = pubsub.findChild("items");
4889 if (items != null) {
4890 return Avatar.parseMetadata(items);
4891 }
4892 }
4893 return null;
4894 }
4895
4896 private boolean errorIsItemNotFound(Iq packet) {
4897 Element error = packet.findChild("error");
4898 return packet.getType() == Iq.Type.ERROR
4899 && error != null
4900 && error.hasChild("item-not-found");
4901 }
4902
4903 @Override
4904 public void accept(final Iq packet) {
4905 if (packet.getType() == Iq.Type.RESULT || errorIsItemNotFound(packet)) {
4906 Avatar serverAvatar = parseAvatar(packet);
4907 if (serverAvatar == null && account.getAvatar() != null) {
4908 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4909 if (avatar != null) {
4910 Log.d(
4911 Config.LOGTAG,
4912 account.getJid().asBareJid()
4913 + ": avatar on server was null. republishing");
4914 publishAvatar(
4915 account,
4916 fileBackend.getStoredPepAvatar(account.getAvatar()),
4917 null);
4918 } else {
4919 Log.e(
4920 Config.LOGTAG,
4921 account.getJid().asBareJid()
4922 + ": error rereading avatar");
4923 }
4924 }
4925 }
4926 }
4927 });
4928 }
4929
4930 public void cancelAvatarFetches(final Account account) {
4931 synchronized (mInProgressAvatarFetches) {
4932 for (final Iterator<String> iterator = mInProgressAvatarFetches.iterator();
4933 iterator.hasNext(); ) {
4934 final String KEY = iterator.next();
4935 if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
4936 iterator.remove();
4937 }
4938 }
4939 }
4940 }
4941
4942 public void fetchAvatar(Account account, Avatar avatar) {
4943 fetchAvatar(account, avatar, null);
4944 }
4945
4946 public void fetchAvatar(
4947 Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4948 final String KEY = generateFetchKey(account, avatar);
4949 synchronized (this.mInProgressAvatarFetches) {
4950 if (mInProgressAvatarFetches.add(KEY)) {
4951 switch (avatar.origin) {
4952 case PEP:
4953 this.mInProgressAvatarFetches.add(KEY);
4954 fetchAvatarPep(account, avatar, callback);
4955 break;
4956 case VCARD:
4957 this.mInProgressAvatarFetches.add(KEY);
4958 fetchAvatarVcard(account, avatar, callback);
4959 break;
4960 }
4961 } else if (avatar.origin == Avatar.Origin.PEP) {
4962 mOmittedPepAvatarFetches.add(KEY);
4963 } else {
4964 Log.d(
4965 Config.LOGTAG,
4966 account.getJid().asBareJid()
4967 + ": already fetching "
4968 + avatar.origin
4969 + " avatar for "
4970 + avatar.owner);
4971 }
4972 }
4973 }
4974
4975 private void fetchAvatarPep(
4976 final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4977 final Iq packet = this.mIqGenerator.retrievePepAvatar(avatar);
4978 sendIqPacket(
4979 account,
4980 packet,
4981 (result) -> {
4982 synchronized (mInProgressAvatarFetches) {
4983 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
4984 }
4985 final String ERROR =
4986 account.getJid().asBareJid()
4987 + ": fetching avatar for "
4988 + avatar.owner
4989 + " failed ";
4990 if (result.getType() == Iq.Type.RESULT) {
4991 avatar.image = IqParser.avatarData(result);
4992 if (avatar.image != null) {
4993 if (getFileBackend().save(avatar)) {
4994 if (account.getJid().asBareJid().equals(avatar.owner)) {
4995 if (account.setAvatar(avatar.getFilename())) {
4996 databaseBackend.updateAccount(account);
4997 }
4998 getAvatarService().clear(account);
4999 updateConversationUi();
5000 updateAccountUi();
5001 } else {
5002 final Contact contact =
5003 account.getRoster().getContact(avatar.owner);
5004 contact.setAvatar(avatar);
5005 syncRoster(account);
5006 getAvatarService().clear(contact);
5007 updateConversationUi();
5008 updateRosterUi();
5009 }
5010 if (callback != null) {
5011 callback.success(avatar);
5012 }
5013 Log.d(
5014 Config.LOGTAG,
5015 account.getJid().asBareJid()
5016 + ": successfully fetched pep avatar for "
5017 + avatar.owner);
5018 return;
5019 }
5020 } else {
5021
5022 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
5023 }
5024 } else {
5025 Element error = result.findChild("error");
5026 if (error == null) {
5027 Log.d(Config.LOGTAG, ERROR + "(server error)");
5028 } else {
5029 Log.d(Config.LOGTAG, ERROR + error.toString());
5030 }
5031 }
5032 if (callback != null) {
5033 callback.error(0, null);
5034 }
5035 });
5036 }
5037
5038 private void fetchAvatarVcard(
5039 final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
5040 final Iq packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
5041 this.sendIqPacket(
5042 account,
5043 packet,
5044 response -> {
5045 final boolean previouslyOmittedPepFetch;
5046 synchronized (mInProgressAvatarFetches) {
5047 final String KEY = generateFetchKey(account, avatar);
5048 mInProgressAvatarFetches.remove(KEY);
5049 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
5050 }
5051 if (response.getType() == Iq.Type.RESULT) {
5052 Element vCard = response.findChild("vCard", "vcard-temp");
5053 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
5054 String image = photo != null ? photo.findChildContent("BINVAL") : null;
5055 if (image != null) {
5056 avatar.image = image;
5057 if (getFileBackend().save(avatar)) {
5058 Log.d(
5059 Config.LOGTAG,
5060 account.getJid().asBareJid()
5061 + ": successfully fetched vCard avatar for "
5062 + avatar.owner
5063 + " omittedPep="
5064 + previouslyOmittedPepFetch);
5065 if (avatar.owner.isBareJid()) {
5066 if (account.getJid().asBareJid().equals(avatar.owner)
5067 && account.getAvatar() == null) {
5068 Log.d(
5069 Config.LOGTAG,
5070 account.getJid().asBareJid()
5071 + ": had no avatar. replacing with vcard");
5072 account.setAvatar(avatar.getFilename());
5073 databaseBackend.updateAccount(account);
5074 getAvatarService().clear(account);
5075 updateAccountUi();
5076 } else {
5077 final Contact contact =
5078 account.getRoster().getContact(avatar.owner);
5079 contact.setAvatar(avatar, previouslyOmittedPepFetch);
5080 syncRoster(account);
5081 getAvatarService().clear(contact);
5082 updateRosterUi();
5083 }
5084 updateConversationUi();
5085 } else {
5086 Conversation conversation =
5087 find(account, avatar.owner.asBareJid());
5088 if (conversation != null
5089 && conversation.getMode() == Conversation.MODE_MULTI) {
5090 MucOptions.User user =
5091 conversation
5092 .getMucOptions()
5093 .findUserByFullJid(avatar.owner);
5094 if (user != null) {
5095 if (user.setAvatar(avatar)) {
5096 getAvatarService().clear(user);
5097 updateConversationUi();
5098 updateMucRosterUi();
5099 }
5100 if (user.getRealJid() != null) {
5101 Contact contact =
5102 account.getRoster()
5103 .getContact(user.getRealJid());
5104 contact.setAvatar(avatar);
5105 syncRoster(account);
5106 getAvatarService().clear(contact);
5107 updateRosterUi();
5108 }
5109 }
5110 }
5111 }
5112 }
5113 }
5114 }
5115 });
5116 }
5117
5118 public void checkForAvatar(final Account account, final UiCallback<Avatar> callback) {
5119 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
5120 this.sendIqPacket(
5121 account,
5122 packet,
5123 response -> {
5124 if (response.getType() == Iq.Type.RESULT) {
5125 Element pubsub =
5126 response.findChild("pubsub", "http://jabber.org/protocol/pubsub");
5127 if (pubsub != null) {
5128 Element items = pubsub.findChild("items");
5129 if (items != null) {
5130 Avatar avatar = Avatar.parseMetadata(items);
5131 if (avatar != null) {
5132 avatar.owner = account.getJid().asBareJid();
5133 if (fileBackend.isAvatarCached(avatar)) {
5134 if (account.setAvatar(avatar.getFilename())) {
5135 databaseBackend.updateAccount(account);
5136 }
5137 getAvatarService().clear(account);
5138 callback.success(avatar);
5139 } else {
5140 fetchAvatarPep(account, avatar, callback);
5141 }
5142 return;
5143 }
5144 }
5145 }
5146 }
5147 callback.error(0, null);
5148 });
5149 }
5150
5151 public void notifyAccountAvatarHasChanged(final Account account) {
5152 final XmppConnection connection = account.getXmppConnection();
5153 if (connection != null && connection.getFeatures().bookmarksConversion()) {
5154 Log.d(
5155 Config.LOGTAG,
5156 account.getJid().asBareJid()
5157 + ": avatar changed. resending presence to online group chats");
5158 for (Conversation conversation : conversations) {
5159 if (conversation.getAccount() == account
5160 && conversation.getMode() == Conversational.MODE_MULTI) {
5161 final MucOptions mucOptions = conversation.getMucOptions();
5162 if (mucOptions.online()) {
5163 final var packet =
5164 mPresenceGenerator.selfPresence(
5165 account, Presence.Status.ONLINE, mucOptions.nonanonymous());
5166 packet.setTo(mucOptions.getSelf().getFullJid());
5167 connection.sendPresencePacket(packet);
5168 }
5169 }
5170 }
5171 }
5172 }
5173
5174 public void deleteContactOnServer(Contact contact) {
5175 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
5176 contact.resetOption(Contact.Options.DIRTY_PUSH);
5177 contact.setOption(Contact.Options.DIRTY_DELETE);
5178 Account account = contact.getAccount();
5179 if (account.getStatus() == Account.State.ONLINE) {
5180 final Iq iq = new Iq(Iq.Type.SET);
5181 Element item = iq.query(Namespace.ROSTER).addChild("item");
5182 item.setAttribute("jid", contact.getJid());
5183 item.setAttribute("subscription", "remove");
5184 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
5185 }
5186 }
5187
5188 public void updateConversation(final Conversation conversation) {
5189 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
5190 }
5191
5192 private void reconnectAccount(
5193 final Account account, final boolean force, final boolean interactive) {
5194 synchronized (account) {
5195 final XmppConnection existingConnection = account.getXmppConnection();
5196 final XmppConnection connection;
5197 if (existingConnection != null) {
5198 connection = existingConnection;
5199 } else if (account.isConnectionEnabled()) {
5200 connection = createConnection(account);
5201 account.setXmppConnection(connection);
5202 } else {
5203 return;
5204 }
5205 final boolean hasInternet = hasInternetConnection();
5206 if (account.isConnectionEnabled() && hasInternet) {
5207 if (!force) {
5208 disconnect(account, false);
5209 }
5210 Thread thread = new Thread(connection);
5211 connection.setInteractive(interactive);
5212 connection.prepareNewConnection();
5213 connection.interrupt();
5214 thread.start();
5215 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
5216 } else {
5217 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
5218 account.getRoster().clearPresences();
5219 connection.resetEverything();
5220 final AxolotlService axolotlService = account.getAxolotlService();
5221 if (axolotlService != null) {
5222 axolotlService.resetBrokenness();
5223 }
5224 if (!hasInternet) {
5225 account.setStatus(Account.State.NO_INTERNET);
5226 }
5227 }
5228 }
5229 }
5230
5231 public void reconnectAccountInBackground(final Account account) {
5232 new Thread(() -> reconnectAccount(account, false, true)).start();
5233 }
5234
5235 public void invite(final Conversation conversation, final Jid contact) {
5236 Log.d(
5237 Config.LOGTAG,
5238 conversation.getAccount().getJid().asBareJid()
5239 + ": inviting "
5240 + contact
5241 + " to "
5242 + conversation.getJid().asBareJid());
5243 final MucOptions.User user =
5244 conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
5245 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
5246 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
5247 }
5248 final var packet = mMessageGenerator.invite(conversation, contact);
5249 sendMessagePacket(conversation.getAccount(), packet);
5250 }
5251
5252 public void directInvite(Conversation conversation, Jid jid) {
5253 final var packet = mMessageGenerator.directInvite(conversation, jid);
5254 sendMessagePacket(conversation.getAccount(), packet);
5255 }
5256
5257 public void resetSendingToWaiting(Account account) {
5258 for (Conversation conversation : getConversations()) {
5259 if (conversation.getAccount() == account) {
5260 conversation.findUnsentTextMessages(
5261 message -> markMessage(message, Message.STATUS_WAITING));
5262 }
5263 }
5264 }
5265
5266 public Message markMessage(
5267 final Account account, final Jid recipient, final String uuid, final int status) {
5268 return markMessage(account, recipient, uuid, status, null);
5269 }
5270
5271 public Message markMessage(
5272 final Account account,
5273 final Jid recipient,
5274 final String uuid,
5275 final int status,
5276 String errorMessage) {
5277 if (uuid == null) {
5278 return null;
5279 }
5280 for (Conversation conversation : getConversations()) {
5281 if (conversation.getJid().asBareJid().equals(recipient)
5282 && conversation.getAccount() == account) {
5283 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
5284 if (message != null) {
5285 markMessage(message, status, errorMessage);
5286 }
5287 return message;
5288 }
5289 }
5290 return null;
5291 }
5292
5293 public boolean markMessage(
5294 final Conversation conversation,
5295 final String uuid,
5296 final int status,
5297 final String serverMessageId) {
5298 return markMessage(conversation, uuid, status, serverMessageId, null);
5299 }
5300
5301 public boolean markMessage(
5302 final Conversation conversation,
5303 final String uuid,
5304 final int status,
5305 final String serverMessageId,
5306 final LocalizedContent body) {
5307 if (uuid == null) {
5308 return false;
5309 } else {
5310 final Message message = conversation.findSentMessageWithUuid(uuid);
5311 if (message != null) {
5312 if (message.getServerMsgId() == null) {
5313 message.setServerMsgId(serverMessageId);
5314 }
5315 if (message.getEncryption() == Message.ENCRYPTION_NONE
5316 && message.isTypeText()
5317 && isBodyModified(message, body)) {
5318 message.setBody(body.content);
5319 if (body.count > 1) {
5320 message.setBodyLanguage(body.language);
5321 }
5322 markMessage(message, status, null, true);
5323 } else {
5324 markMessage(message, status);
5325 }
5326 return true;
5327 } else {
5328 return false;
5329 }
5330 }
5331 }
5332
5333 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
5334 if (body == null || body.content == null) {
5335 return false;
5336 }
5337 return !body.content.equals(message.getBody());
5338 }
5339
5340 public void markMessage(Message message, int status) {
5341 markMessage(message, status, null);
5342 }
5343
5344 public void markMessage(final Message message, final int status, final String errorMessage) {
5345 markMessage(message, status, errorMessage, false);
5346 }
5347
5348 public void markMessage(
5349 final Message message,
5350 final int status,
5351 final String errorMessage,
5352 final boolean includeBody) {
5353 final int oldStatus = message.getStatus();
5354 if (status == Message.STATUS_SEND_FAILED
5355 && (oldStatus == Message.STATUS_SEND_RECEIVED
5356 || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
5357 return;
5358 }
5359 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
5360 return;
5361 }
5362 message.setErrorMessage(errorMessage);
5363 message.setStatus(status);
5364 databaseBackend.updateMessage(message, includeBody);
5365 updateConversationUi();
5366 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
5367 mNotificationService.pushFailedDelivery(message);
5368 }
5369 }
5370
5371 private SharedPreferences getPreferences() {
5372 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
5373 }
5374
5375 public long getAutomaticMessageDeletionDate() {
5376 final long timeout =
5377 getLongPreference(
5378 AppSettings.AUTOMATIC_MESSAGE_DELETION,
5379 R.integer.automatic_message_deletion);
5380 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
5381 }
5382
5383 public long getLongPreference(String name, @IntegerRes int res) {
5384 long defaultValue = getResources().getInteger(res);
5385 try {
5386 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
5387 } catch (NumberFormatException e) {
5388 return defaultValue;
5389 }
5390 }
5391
5392 public boolean getBooleanPreference(String name, @BoolRes int res) {
5393 return getPreferences().getBoolean(name, getResources().getBoolean(res));
5394 }
5395
5396 public boolean confirmMessages() {
5397 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
5398 }
5399
5400 public boolean allowMessageCorrection() {
5401 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
5402 }
5403
5404 public boolean sendChatStates() {
5405 return getBooleanPreference("chat_states", R.bool.chat_states);
5406 }
5407
5408 public boolean useTorToConnect() {
5409 return QuickConversationsService.isConversations()
5410 && getBooleanPreference("use_tor", R.bool.use_tor);
5411 }
5412
5413 public boolean showExtendedConnectionOptions() {
5414 return QuickConversationsService.isConversations()
5415 && getBooleanPreference(
5416 AppSettings.SHOW_CONNECTION_OPTIONS, R.bool.show_connection_options);
5417 }
5418
5419 public boolean broadcastLastActivity() {
5420 return getBooleanPreference(AppSettings.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
5421 }
5422
5423 public int unreadCount() {
5424 int count = 0;
5425 for (Conversation conversation : getConversations()) {
5426 count += conversation.unreadCount();
5427 }
5428 return count;
5429 }
5430
5431 private <T> List<T> threadSafeList(Set<T> set) {
5432 synchronized (LISTENER_LOCK) {
5433 return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
5434 }
5435 }
5436
5437 public void showErrorToastInUi(int resId) {
5438 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
5439 listener.onShowErrorToast(resId);
5440 }
5441 }
5442
5443 public void updateConversationUi() {
5444 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
5445 listener.onConversationUpdate();
5446 }
5447 }
5448
5449 public void notifyJingleRtpConnectionUpdate(
5450 final Account account,
5451 final Jid with,
5452 final String sessionId,
5453 final RtpEndUserState state) {
5454 for (OnJingleRtpConnectionUpdate listener :
5455 threadSafeList(this.onJingleRtpConnectionUpdate)) {
5456 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
5457 }
5458 }
5459
5460 public void notifyJingleRtpConnectionUpdate(
5461 CallIntegration.AudioDevice selectedAudioDevice,
5462 Set<CallIntegration.AudioDevice> availableAudioDevices) {
5463 for (OnJingleRtpConnectionUpdate listener :
5464 threadSafeList(this.onJingleRtpConnectionUpdate)) {
5465 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
5466 }
5467 }
5468
5469 public void updateAccountUi() {
5470 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
5471 listener.onAccountUpdate();
5472 }
5473 }
5474
5475 public void updateRosterUi() {
5476 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
5477 listener.onRosterUpdate();
5478 }
5479 }
5480
5481 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
5482 if (mOnCaptchaRequested.size() > 0) {
5483 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
5484 Bitmap scaled =
5485 Bitmap.createScaledBitmap(
5486 captcha,
5487 (int) (captcha.getWidth() * metrics.scaledDensity),
5488 (int) (captcha.getHeight() * metrics.scaledDensity),
5489 false);
5490 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
5491 listener.onCaptchaRequested(account, id, data, scaled);
5492 }
5493 return true;
5494 }
5495 return false;
5496 }
5497
5498 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
5499 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
5500 listener.OnUpdateBlocklist(status);
5501 }
5502 }
5503
5504 public void updateMucRosterUi() {
5505 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
5506 listener.onMucRosterUpdate();
5507 }
5508 }
5509
5510 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
5511 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
5512 listener.onKeyStatusUpdated(report);
5513 }
5514 }
5515
5516 public Account findAccountByJid(final Jid jid) {
5517 for (final Account account : this.accounts) {
5518 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
5519 return account;
5520 }
5521 }
5522 return null;
5523 }
5524
5525 public Account findAccountByUuid(final String uuid) {
5526 for (Account account : this.accounts) {
5527 if (account.getUuid().equals(uuid)) {
5528 return account;
5529 }
5530 }
5531 return null;
5532 }
5533
5534 public Conversation findConversationByUuid(String uuid) {
5535 for (Conversation conversation : getConversations()) {
5536 if (conversation.getUuid().equals(uuid)) {
5537 return conversation;
5538 }
5539 }
5540 return null;
5541 }
5542
5543 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
5544 List<Conversation> findings = new ArrayList<>();
5545 for (Conversation c : getConversations()) {
5546 if (c.getAccount().isEnabled()
5547 && c.getJid().asBareJid().equals(xmppUri.getJid())
5548 && ((c.getMode() == Conversational.MODE_MULTI)
5549 == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
5550 findings.add(c);
5551 }
5552 }
5553 return findings.size() == 1 ? findings.get(0) : null;
5554 }
5555
5556 public boolean markRead(final Conversation conversation, boolean dismiss) {
5557 return markRead(conversation, null, dismiss).size() > 0;
5558 }
5559
5560 public void markRead(final Conversation conversation) {
5561 markRead(conversation, null, true);
5562 }
5563
5564 public List<Message> markRead(
5565 final Conversation conversation, String upToUuid, boolean dismiss) {
5566 if (dismiss) {
5567 mNotificationService.clear(conversation);
5568 }
5569 final List<Message> readMessages = conversation.markRead(upToUuid);
5570 if (readMessages.size() > 0) {
5571 Runnable runnable =
5572 () -> {
5573 for (Message message : readMessages) {
5574 databaseBackend.updateMessage(message, false);
5575 }
5576 };
5577 mDatabaseWriterExecutor.execute(runnable);
5578 updateConversationUi();
5579 updateUnreadCountBadge();
5580 return readMessages;
5581 } else {
5582 return readMessages;
5583 }
5584 }
5585
5586 public synchronized void updateUnreadCountBadge() {
5587 int count = unreadCount();
5588 if (unreadCount != count) {
5589 Log.d(Config.LOGTAG, "update unread count to " + count);
5590 if (count > 0) {
5591 ShortcutBadger.applyCount(getApplicationContext(), count);
5592 } else {
5593 ShortcutBadger.removeCount(getApplicationContext());
5594 }
5595 unreadCount = count;
5596 }
5597 }
5598
5599 public void sendReadMarker(final Conversation conversation, final String upToUuid) {
5600 final boolean isPrivateAndNonAnonymousMuc =
5601 conversation.getMode() == Conversation.MODE_MULTI
5602 && conversation.isPrivateAndNonAnonymous();
5603 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
5604 if (readMessages.isEmpty()) {
5605 return;
5606 }
5607 final var account = conversation.getAccount();
5608 final var connection = account.getXmppConnection();
5609 updateConversationUi();
5610 final var last =
5611 Iterables.getLast(
5612 Collections2.filter(
5613 readMessages,
5614 m ->
5615 !m.isPrivateMessage()
5616 && m.getStatus() == Message.STATUS_RECEIVED),
5617 null);
5618 if (last == null) {
5619 return;
5620 }
5621
5622 final boolean sendDisplayedMarker =
5623 confirmMessages()
5624 && (last.trusted() || isPrivateAndNonAnonymousMuc)
5625 && last.getRemoteMsgId() != null
5626 && (last.markable || isPrivateAndNonAnonymousMuc);
5627 final boolean serverAssist =
5628 connection != null && connection.getFeatures().mdsServerAssist();
5629
5630 final String stanzaId = last.getServerMsgId();
5631
5632 if (sendDisplayedMarker && serverAssist) {
5633 final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5634 final var packet = mMessageGenerator.confirm(last);
5635 packet.addChild(mdsDisplayed);
5636 if (!last.isPrivateMessage()) {
5637 packet.setTo(packet.getTo().asBareJid());
5638 }
5639 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server assisted " + packet);
5640 this.sendMessagePacket(account, packet);
5641 } else {
5642 publishMds(last);
5643 // read markers will be sent after MDS to flush the CSI stanza queue
5644 if (sendDisplayedMarker) {
5645 Log.d(
5646 Config.LOGTAG,
5647 conversation.getAccount().getJid().asBareJid()
5648 + ": sending displayed marker to "
5649 + last.getCounterpart().toString());
5650 final var packet = mMessageGenerator.confirm(last);
5651 this.sendMessagePacket(account, packet);
5652 }
5653 }
5654 }
5655
5656 private void publishMds(@Nullable final Message message) {
5657 final String stanzaId = message == null ? null : message.getServerMsgId();
5658 if (Strings.isNullOrEmpty(stanzaId)) {
5659 return;
5660 }
5661 final Conversation conversation;
5662 final var conversational = message.getConversation();
5663 if (conversational instanceof Conversation c) {
5664 conversation = c;
5665 } else {
5666 return;
5667 }
5668 final var account = conversation.getAccount();
5669 final var connection = account.getXmppConnection();
5670 if (connection == null || !connection.getFeatures().mds()) {
5671 return;
5672 }
5673 final Jid itemId;
5674 if (message.isPrivateMessage()) {
5675 itemId = message.getCounterpart();
5676 } else {
5677 itemId = conversation.getJid().asBareJid();
5678 }
5679 Log.d(Config.LOGTAG, "publishing mds for " + itemId + "/" + stanzaId);
5680 publishMds(account, itemId, stanzaId, conversation);
5681 }
5682
5683 private void publishMds(
5684 final Account account,
5685 final Jid itemId,
5686 final String stanzaId,
5687 final Conversation conversation) {
5688 final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5689 pushNodeAndEnforcePublishOptions(
5690 account,
5691 Namespace.MDS_DISPLAYED,
5692 item,
5693 itemId.toEscapedString(),
5694 PublishOptions.persistentWhitelistAccessMaxItems());
5695 }
5696
5697 public boolean sendReactions(final Message message, final Collection<String> reactions) {
5698 if (message.getConversation() instanceof Conversation conversation) {
5699 final String reactToId;
5700 final Collection<Reaction> combinedReactions;
5701 if (conversation.getMode() == Conversational.MODE_MULTI) {
5702 final var mucOptions = conversation.getMucOptions();
5703 if (!mucOptions.participating()) {
5704 Log.d(Config.LOGTAG, "not participating in MUC");
5705 return false;
5706 }
5707 final var self = mucOptions.getSelf();
5708 final String occupantId = self.getOccupantId();
5709 if (Strings.isNullOrEmpty(occupantId)) {
5710 Log.d(Config.LOGTAG, "occupant id not found for reaction in MUC");
5711 return false;
5712 }
5713 final var existingRaw =
5714 ImmutableSet.copyOf(
5715 Collections2.transform(message.getReactions(), r -> r.reaction));
5716 final var reactionsAsExistingVariants =
5717 ImmutableSet.copyOf(
5718 Collections2.transform(
5719 reactions, r -> Emoticons.existingVariant(r, existingRaw)));
5720 if (!reactions.equals(reactionsAsExistingVariants)) {
5721 Log.d(Config.LOGTAG, "modified reactions to existing variants");
5722 }
5723 reactToId = message.getServerMsgId();
5724 combinedReactions =
5725 Reaction.withOccupantId(
5726 message.getReactions(),
5727 reactionsAsExistingVariants,
5728 false,
5729 self.getFullJid(),
5730 conversation.getAccount().getJid(),
5731 occupantId);
5732 } else {
5733 if (message.isCarbon() || message.getStatus() == Message.STATUS_RECEIVED) {
5734 reactToId = message.getRemoteMsgId();
5735 } else {
5736 reactToId = message.getUuid();
5737 }
5738 combinedReactions =
5739 Reaction.withFrom(
5740 message.getReactions(),
5741 reactions,
5742 false,
5743 conversation.getAccount().getJid());
5744 }
5745 if (Strings.isNullOrEmpty(reactToId)) {
5746 return false;
5747 }
5748 final var reactionMessage =
5749 mMessageGenerator.reaction(conversation, reactToId, reactions);
5750 sendMessagePacket(conversation.getAccount(), reactionMessage);
5751 message.setReactions(combinedReactions);
5752 updateMessage(message, false);
5753 return true;
5754 } else {
5755 return false;
5756 }
5757 }
5758
5759 public MemorizingTrustManager getMemorizingTrustManager() {
5760 return this.mMemorizingTrustManager;
5761 }
5762
5763 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
5764 this.mMemorizingTrustManager = trustManager;
5765 }
5766
5767 public void updateMemorizingTrustManager() {
5768 final MemorizingTrustManager trustManager;
5769 if (appSettings.isTrustSystemCAStore()) {
5770 trustManager = new MemorizingTrustManager(getApplicationContext());
5771 } else {
5772 trustManager = new MemorizingTrustManager(getApplicationContext(), null);
5773 }
5774 setMemorizingTrustManager(trustManager);
5775 }
5776
5777 public LruCache<String, Bitmap> getBitmapCache() {
5778 return this.mBitmapCache;
5779 }
5780
5781 public Collection<String> getKnownHosts() {
5782 final Set<String> hosts = new HashSet<>();
5783 for (final Account account : getAccounts()) {
5784 hosts.add(account.getServer());
5785 for (final Contact contact : account.getRoster().getContacts()) {
5786 if (contact.showInRoster()) {
5787 final String server = contact.getServer();
5788 if (server != null) {
5789 hosts.add(server);
5790 }
5791 }
5792 }
5793 }
5794 if (Config.QUICKSY_DOMAIN != null) {
5795 hosts.remove(
5796 Config.QUICKSY_DOMAIN
5797 .toEscapedString()); // we only want to show this when we type a e164
5798 // number
5799 }
5800 if (Config.MAGIC_CREATE_DOMAIN != null) {
5801 hosts.add(Config.MAGIC_CREATE_DOMAIN);
5802 }
5803 return hosts;
5804 }
5805
5806 public Collection<String> getKnownConferenceHosts() {
5807 final Set<String> mucServers = new HashSet<>();
5808 for (final Account account : accounts) {
5809 if (account.getXmppConnection() != null) {
5810 mucServers.addAll(account.getXmppConnection().getMucServers());
5811 for (final Bookmark bookmark : account.getBookmarks()) {
5812 final Jid jid = bookmark.getJid();
5813 final String s = jid == null ? null : jid.getDomain().toEscapedString();
5814 if (s != null) {
5815 mucServers.add(s);
5816 }
5817 }
5818 }
5819 }
5820 return mucServers;
5821 }
5822
5823 public void sendMessagePacket(
5824 final Account account,
5825 final im.conversations.android.xmpp.model.stanza.Message packet) {
5826 final XmppConnection connection = account.getXmppConnection();
5827 if (connection != null) {
5828 connection.sendMessagePacket(packet);
5829 }
5830 }
5831
5832 public void sendPresencePacket(
5833 final Account account,
5834 final im.conversations.android.xmpp.model.stanza.Presence packet) {
5835 final XmppConnection connection = account.getXmppConnection();
5836 if (connection != null) {
5837 connection.sendPresencePacket(packet);
5838 }
5839 }
5840
5841 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5842 final XmppConnection connection = account.getXmppConnection();
5843 if (connection == null) {
5844 return;
5845 }
5846 connection.sendCreateAccountWithCaptchaPacket(id, data);
5847 }
5848
5849 public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback) {
5850 final XmppConnection connection = account.getXmppConnection();
5851 if (connection != null) {
5852 connection.sendIqPacket(packet, callback);
5853 } else if (callback != null) {
5854 callback.accept(Iq.TIMEOUT);
5855 }
5856 }
5857
5858 public void sendPresence(final Account account) {
5859 sendPresence(account, checkListeners() && broadcastLastActivity());
5860 }
5861
5862 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
5863 final Presence.Status status;
5864 if (manuallyChangePresence()) {
5865 status = account.getPresenceStatus();
5866 } else {
5867 status = getTargetPresence();
5868 }
5869 final var packet = mPresenceGenerator.selfPresence(account, status);
5870 if (mLastActivity > 0 && includeIdleTimestamp) {
5871 long since =
5872 Math.min(mLastActivity, System.currentTimeMillis()); // don't send future dates
5873 packet.addChild("idle", Namespace.IDLE)
5874 .setAttribute("since", AbstractGenerator.getTimestamp(since));
5875 }
5876 sendPresencePacket(account, packet);
5877 }
5878
5879 private void deactivateGracePeriod() {
5880 for (Account account : getAccounts()) {
5881 account.deactivateGracePeriod();
5882 }
5883 }
5884
5885 public void refreshAllPresences() {
5886 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
5887 for (Account account : getAccounts()) {
5888 if (account.isConnectionEnabled()) {
5889 sendPresence(account, includeIdleTimestamp);
5890 }
5891 }
5892 }
5893
5894 private void refreshAllFcmTokens() {
5895 for (Account account : getAccounts()) {
5896 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
5897 mPushManagementService.registerPushTokenOnServer(account);
5898 }
5899 }
5900 }
5901
5902 private void sendOfflinePresence(final Account account) {
5903 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
5904 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
5905 }
5906
5907 public MessageGenerator getMessageGenerator() {
5908 return this.mMessageGenerator;
5909 }
5910
5911 public PresenceGenerator getPresenceGenerator() {
5912 return this.mPresenceGenerator;
5913 }
5914
5915 public IqGenerator getIqGenerator() {
5916 return this.mIqGenerator;
5917 }
5918
5919 public JingleConnectionManager getJingleConnectionManager() {
5920 return this.mJingleConnectionManager;
5921 }
5922
5923 private boolean hasJingleRtpConnection(final Account account) {
5924 return this.mJingleConnectionManager.hasJingleRtpConnection(account);
5925 }
5926
5927 public MessageArchiveService getMessageArchiveService() {
5928 return this.mMessageArchiveService;
5929 }
5930
5931 public QuickConversationsService getQuickConversationsService() {
5932 return this.mQuickConversationsService;
5933 }
5934
5935 public List<Contact> findContacts(Jid jid, String accountJid) {
5936 ArrayList<Contact> contacts = new ArrayList<>();
5937 for (Account account : getAccounts()) {
5938 if ((account.isEnabled() || accountJid != null)
5939 && (accountJid == null
5940 || accountJid.equals(account.getJid().asBareJid().toString()))) {
5941 Contact contact = account.getRoster().getContactFromContactList(jid);
5942 if (contact != null) {
5943 contacts.add(contact);
5944 }
5945 }
5946 }
5947 return contacts;
5948 }
5949
5950 public Conversation findFirstMuc(Jid jid) {
5951 for (Conversation conversation : getConversations()) {
5952 if (conversation.getAccount().isEnabled()
5953 && conversation.getJid().asBareJid().equals(jid.asBareJid())
5954 && conversation.getMode() == Conversation.MODE_MULTI) {
5955 return conversation;
5956 }
5957 }
5958 return null;
5959 }
5960
5961 public NotificationService getNotificationService() {
5962 return this.mNotificationService;
5963 }
5964
5965 public HttpConnectionManager getHttpConnectionManager() {
5966 return this.mHttpConnectionManager;
5967 }
5968
5969 public void resendFailedMessages(final Message message) {
5970 message.setTime(System.currentTimeMillis());
5971 markMessage(message, Message.STATUS_WAITING);
5972 this.resendMessage(message, false);
5973 if (message.getConversation() instanceof Conversation c) {
5974 c.sort();
5975 }
5976 updateConversationUi();
5977 }
5978
5979 public void clearConversationHistory(final Conversation conversation) {
5980 final long clearDate;
5981 final String reference;
5982 if (conversation.countMessages() > 0) {
5983 Message latestMessage = conversation.getLatestMessage();
5984 clearDate = latestMessage.getTimeSent() + 1000;
5985 reference = latestMessage.getServerMsgId();
5986 } else {
5987 clearDate = System.currentTimeMillis();
5988 reference = null;
5989 }
5990 conversation.clearMessages();
5991 conversation.setHasMessagesLeftOnServer(false); // avoid messages getting loaded through mam
5992 conversation.setLastClearHistory(clearDate, reference);
5993 Runnable runnable =
5994 () -> {
5995 databaseBackend.deleteMessagesInConversation(conversation);
5996 databaseBackend.updateConversation(conversation);
5997 };
5998 mDatabaseWriterExecutor.execute(runnable);
5999 }
6000
6001 public boolean sendBlockRequest(
6002 final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
6003 if (blockable != null && blockable.getBlockedJid() != null) {
6004 final var account = blockable.getAccount();
6005 final Jid jid = blockable.getBlockedJid();
6006 this.sendIqPacket(
6007 account,
6008 getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId),
6009 (response) -> {
6010 if (response.getType() == Iq.Type.RESULT) {
6011 account.getBlocklist().add(jid);
6012 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
6013 }
6014 });
6015 if (blockable.getBlockedJid().isFullJid()) {
6016 return false;
6017 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
6018 updateConversationUi();
6019 return true;
6020 } else {
6021 return false;
6022 }
6023 } else {
6024 return false;
6025 }
6026 }
6027
6028 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
6029 boolean removed = false;
6030 synchronized (this.conversations) {
6031 boolean domainJid = blockedJid.getLocal() == null;
6032 for (Conversation conversation : this.conversations) {
6033 boolean jidMatches =
6034 (domainJid
6035 && blockedJid
6036 .getDomain()
6037 .equals(conversation.getJid().getDomain()))
6038 || blockedJid.equals(conversation.getJid().asBareJid());
6039 if (conversation.getAccount() == account
6040 && conversation.getMode() == Conversation.MODE_SINGLE
6041 && jidMatches) {
6042 this.conversations.remove(conversation);
6043 markRead(conversation);
6044 conversation.setStatus(Conversation.STATUS_ARCHIVED);
6045 Log.d(
6046 Config.LOGTAG,
6047 account.getJid().asBareJid()
6048 + ": archiving conversation "
6049 + conversation.getJid().asBareJid()
6050 + " because jid was blocked");
6051 updateConversation(conversation);
6052 removed = true;
6053 }
6054 }
6055 }
6056 return removed;
6057 }
6058
6059 public void sendUnblockRequest(final Blockable blockable) {
6060 if (blockable != null && blockable.getJid() != null) {
6061 final var account = blockable.getAccount();
6062 final Jid jid = blockable.getBlockedJid();
6063 this.sendIqPacket(
6064 account,
6065 getIqGenerator().generateSetUnblockRequest(jid),
6066 response -> {
6067 if (response.getType() == Iq.Type.RESULT) {
6068 account.getBlocklist().remove(jid);
6069 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
6070 }
6071 });
6072 }
6073 }
6074
6075 public void publishDisplayName(final Account account) {
6076 String displayName = account.getDisplayName();
6077 final Iq request;
6078 if (TextUtils.isEmpty(displayName)) {
6079 request = mIqGenerator.deleteNode(Namespace.NICK);
6080 } else {
6081 request = mIqGenerator.publishNick(displayName);
6082 }
6083 mAvatarService.clear(account);
6084 sendIqPacket(
6085 account,
6086 request,
6087 (packet) -> {
6088 if (packet.getType() == Iq.Type.ERROR) {
6089 Log.d(
6090 Config.LOGTAG,
6091 account.getJid().asBareJid()
6092 + ": unable to modify nick name "
6093 + packet);
6094 }
6095 });
6096 }
6097
6098 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
6099 ServiceDiscoveryResult result = discoCache.get(key);
6100 if (result != null) {
6101 return result;
6102 } else {
6103 result = databaseBackend.findDiscoveryResult(key.first, key.second);
6104 if (result != null) {
6105 discoCache.put(key, result);
6106 }
6107 return result;
6108 }
6109 }
6110
6111 public void fetchCaps(final Account account, final Jid jid, final Presence presence) {
6112 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
6113 final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
6114 if (disco != null) {
6115 presence.setServiceDiscoveryResult(disco);
6116 final Contact contact = account.getRoster().getContact(jid);
6117 if (contact.refreshRtpCapability()) {
6118 syncRoster(account);
6119 }
6120 } else {
6121 final Iq request = new Iq(Iq.Type.GET);
6122 request.setTo(jid);
6123 final String node = presence.getNode();
6124 final String ver = presence.getVer();
6125 final Element query = request.query(Namespace.DISCO_INFO);
6126 if (node != null && ver != null) {
6127 query.setAttribute("node", node + "#" + ver);
6128 }
6129 Log.d(
6130 Config.LOGTAG,
6131 account.getJid().asBareJid()
6132 + ": making disco request for "
6133 + key.second
6134 + " to "
6135 + jid);
6136 sendIqPacket(
6137 account,
6138 request,
6139 (response) -> {
6140 if (response.getType() == Iq.Type.RESULT) {
6141 final ServiceDiscoveryResult discoveryResult =
6142 new ServiceDiscoveryResult(response);
6143 if (presence.getVer().equals(discoveryResult.getVer())) {
6144 databaseBackend.insertDiscoveryResult(discoveryResult);
6145 injectServiceDiscoveryResult(
6146 account.getRoster(),
6147 presence.getHash(),
6148 presence.getVer(),
6149 discoveryResult);
6150 } else {
6151 Log.d(
6152 Config.LOGTAG,
6153 account.getJid().asBareJid()
6154 + ": mismatch in caps for contact "
6155 + jid
6156 + " "
6157 + presence.getVer()
6158 + " vs "
6159 + discoveryResult.getVer());
6160 }
6161 } else {
6162 Log.d(
6163 Config.LOGTAG,
6164 account.getJid().asBareJid()
6165 + ": unable to fetch caps from "
6166 + jid);
6167 }
6168 });
6169 }
6170 }
6171
6172 private void injectServiceDiscoveryResult(
6173 Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
6174 boolean rosterNeedsSync = false;
6175 for (final Contact contact : roster.getContacts()) {
6176 boolean serviceDiscoverySet = false;
6177 for (final Presence presence : contact.getPresences().getPresences()) {
6178 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
6179 presence.setServiceDiscoveryResult(disco);
6180 serviceDiscoverySet = true;
6181 }
6182 }
6183 if (serviceDiscoverySet) {
6184 rosterNeedsSync |= contact.refreshRtpCapability();
6185 }
6186 }
6187 if (rosterNeedsSync) {
6188 syncRoster(roster.getAccount());
6189 }
6190 }
6191
6192 public void fetchMamPreferences(final Account account, final OnMamPreferencesFetched callback) {
6193 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
6194 final Iq request = new Iq(Iq.Type.GET);
6195 request.addChild("prefs", version.namespace);
6196 sendIqPacket(
6197 account,
6198 request,
6199 (packet) -> {
6200 final Element prefs = packet.findChild("prefs", version.namespace);
6201 if (packet.getType() == Iq.Type.RESULT && prefs != null) {
6202 callback.onPreferencesFetched(prefs);
6203 } else {
6204 callback.onPreferencesFetchFailed();
6205 }
6206 });
6207 }
6208
6209 public PushManagementService getPushManagementService() {
6210 return mPushManagementService;
6211 }
6212
6213 public void changeStatus(Account account, PresenceTemplate template, String signature) {
6214 if (!template.getStatusMessage().isEmpty()) {
6215 databaseBackend.insertPresenceTemplate(template);
6216 }
6217 account.setPgpSignature(signature);
6218 account.setPresenceStatus(template.getStatus());
6219 account.setPresenceStatusMessage(template.getStatusMessage());
6220 databaseBackend.updateAccount(account);
6221 sendPresence(account);
6222 }
6223
6224 public List<PresenceTemplate> getPresenceTemplates(Account account) {
6225 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
6226 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
6227 if (!templates.contains(template)) {
6228 templates.add(0, template);
6229 }
6230 }
6231 return templates;
6232 }
6233
6234 public void saveConversationAsBookmark(final Conversation conversation, final String name) {
6235 final Account account = conversation.getAccount();
6236 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
6237 final String nick = conversation.getJid().getResource();
6238 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
6239 bookmark.setNick(nick);
6240 }
6241 if (!TextUtils.isEmpty(name)) {
6242 bookmark.setBookmarkName(name);
6243 }
6244 bookmark.setAutojoin(true);
6245 createBookmark(account, bookmark);
6246 bookmark.setConversation(conversation);
6247 }
6248
6249 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
6250 boolean performedVerification = false;
6251 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
6252 for (XmppUri.Fingerprint fp : fingerprints) {
6253 if (fp.type == XmppUri.FingerprintType.OMEMO) {
6254 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
6255 FingerprintStatus fingerprintStatus =
6256 axolotlService.getFingerprintTrust(fingerprint);
6257 if (fingerprintStatus != null) {
6258 if (!fingerprintStatus.isVerified()) {
6259 performedVerification = true;
6260 axolotlService.setFingerprintTrust(
6261 fingerprint, fingerprintStatus.toVerified());
6262 }
6263 } else {
6264 axolotlService.preVerifyFingerprint(contact, fingerprint);
6265 }
6266 }
6267 }
6268 return performedVerification;
6269 }
6270
6271 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
6272 final AxolotlService axolotlService = account.getAxolotlService();
6273 boolean verifiedSomething = false;
6274 for (XmppUri.Fingerprint fp : fingerprints) {
6275 if (fp.type == XmppUri.FingerprintType.OMEMO) {
6276 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
6277 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
6278 FingerprintStatus fingerprintStatus =
6279 axolotlService.getFingerprintTrust(fingerprint);
6280 if (fingerprintStatus != null) {
6281 if (!fingerprintStatus.isVerified()) {
6282 axolotlService.setFingerprintTrust(
6283 fingerprint, fingerprintStatus.toVerified());
6284 verifiedSomething = true;
6285 }
6286 } else {
6287 axolotlService.preVerifyFingerprint(account, fingerprint);
6288 verifiedSomething = true;
6289 }
6290 }
6291 }
6292 return verifiedSomething;
6293 }
6294
6295 public boolean blindTrustBeforeVerification() {
6296 return getBooleanPreference(AppSettings.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
6297 }
6298
6299 public ShortcutService getShortcutService() {
6300 return mShortcutService;
6301 }
6302
6303 public void pushMamPreferences(Account account, Element prefs) {
6304 final Iq set = new Iq(Iq.Type.SET);
6305 set.addChild(prefs);
6306 sendIqPacket(account, set, null);
6307 }
6308
6309 public void evictPreview(String uuid) {
6310 if (mBitmapCache.remove(uuid) != null) {
6311 Log.d(Config.LOGTAG, "deleted cached preview");
6312 }
6313 }
6314
6315 public interface OnMamPreferencesFetched {
6316 void onPreferencesFetched(Element prefs);
6317
6318 void onPreferencesFetchFailed();
6319 }
6320
6321 public interface OnAccountCreated {
6322 void onAccountCreated(Account account);
6323
6324 void informUser(int r);
6325 }
6326
6327 public interface OnMoreMessagesLoaded {
6328 void onMoreMessagesLoaded(int count, Conversation conversation);
6329
6330 void informUser(int r);
6331 }
6332
6333 public interface OnAccountPasswordChanged {
6334 void onPasswordChangeSucceeded();
6335
6336 void onPasswordChangeFailed();
6337 }
6338
6339 public interface OnRoomDestroy {
6340 void onRoomDestroySucceeded();
6341
6342 void onRoomDestroyFailed();
6343 }
6344
6345 public interface OnAffiliationChanged {
6346 void onAffiliationChangedSuccessful(Jid jid);
6347
6348 void onAffiliationChangeFailed(Jid jid, int resId);
6349 }
6350
6351 public interface OnConversationUpdate {
6352 void onConversationUpdate();
6353 }
6354
6355 public interface OnJingleRtpConnectionUpdate {
6356 void onJingleRtpConnectionUpdate(
6357 final Account account,
6358 final Jid with,
6359 final String sessionId,
6360 final RtpEndUserState state);
6361
6362 void onAudioDeviceChanged(
6363 CallIntegration.AudioDevice selectedAudioDevice,
6364 Set<CallIntegration.AudioDevice> availableAudioDevices);
6365 }
6366
6367 public interface OnAccountUpdate {
6368 void onAccountUpdate();
6369 }
6370
6371 public interface OnCaptchaRequested {
6372 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
6373 }
6374
6375 public interface OnRosterUpdate {
6376 void onRosterUpdate();
6377 }
6378
6379 public interface OnMucRosterUpdate {
6380 void onMucRosterUpdate();
6381 }
6382
6383 public interface OnConferenceConfigurationFetched {
6384 void onConferenceConfigurationFetched(Conversation conversation);
6385
6386 void onFetchFailed(Conversation conversation, String errorCondition);
6387 }
6388
6389 public interface OnConferenceJoined {
6390 void onConferenceJoined(Conversation conversation);
6391 }
6392
6393 public interface OnConfigurationPushed {
6394 void onPushSucceeded();
6395
6396 void onPushFailed();
6397 }
6398
6399 public interface OnShowErrorToast {
6400 void onShowErrorToast(int resId);
6401 }
6402
6403 public class XmppConnectionBinder extends Binder {
6404 public XmppConnectionService getService() {
6405 return XmppConnectionService.this;
6406 }
6407 }
6408
6409 private class InternalEventReceiver extends BroadcastReceiver {
6410
6411 @Override
6412 public void onReceive(final Context context, final Intent intent) {
6413 onStartCommand(intent, 0, 0);
6414 }
6415 }
6416
6417 private class RestrictedEventReceiver extends BroadcastReceiver {
6418
6419 private final Collection<String> allowedActions;
6420
6421 private RestrictedEventReceiver(final Collection<String> allowedActions) {
6422 this.allowedActions = allowedActions;
6423 }
6424
6425 @Override
6426 public void onReceive(final Context context, final Intent intent) {
6427 final String action = intent == null ? null : intent.getAction();
6428 if (allowedActions.contains(action)) {
6429 onStartCommand(intent, 0, 0);
6430 } else {
6431 Log.e(Config.LOGTAG, "restricting broadcast of event " + action);
6432 }
6433 }
6434 }
6435
6436 public static class OngoingCall {
6437 public final AbstractJingleConnection.Id id;
6438 public final Set<Media> media;
6439 public final boolean reconnecting;
6440
6441 public OngoingCall(
6442 AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
6443 this.id = id;
6444 this.media = media;
6445 this.reconnecting = reconnecting;
6446 }
6447
6448 @Override
6449 public boolean equals(Object o) {
6450 if (this == o) return true;
6451 if (o == null || getClass() != o.getClass()) return false;
6452 OngoingCall that = (OngoingCall) o;
6453 return reconnecting == that.reconnecting
6454 && Objects.equal(id, that.id)
6455 && Objects.equal(media, that.media);
6456 }
6457
6458 @Override
6459 public int hashCode() {
6460 return Objects.hashCode(id, media, reconnecting);
6461 }
6462 }
6463
6464 public static void toggleForegroundService(final XmppConnectionService service) {
6465 if (service == null) {
6466 return;
6467 }
6468 service.toggleForegroundService();
6469 }
6470
6471 public static void toggleForegroundService(final ConversationsActivity activity) {
6472 if (activity == null) {
6473 return;
6474 }
6475 toggleForegroundService(activity.xmppConnectionService);
6476 }
6477}