2 Copyright (C) 2015-2022 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
20 import org
.asamk
.signal
.manager
.api
.Configuration
;
21 import org
.asamk
.signal
.manager
.api
.Device
;
22 import org
.asamk
.signal
.manager
.api
.Group
;
23 import org
.asamk
.signal
.manager
.api
.Identity
;
24 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
25 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
26 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
27 import org
.asamk
.signal
.manager
.api
.Message
;
28 import org
.asamk
.signal
.manager
.api
.NotPrimaryDeviceException
;
29 import org
.asamk
.signal
.manager
.api
.Pair
;
30 import org
.asamk
.signal
.manager
.api
.ReceiveConfig
;
31 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
32 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
33 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
34 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
35 import org
.asamk
.signal
.manager
.api
.StickerPack
;
36 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
37 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
38 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
39 import org
.asamk
.signal
.manager
.api
.TypingAction
;
40 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
41 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
42 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
43 import org
.asamk
.signal
.manager
.api
.UserStatus
;
44 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
45 import org
.asamk
.signal
.manager
.groups
.GroupId
;
46 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
47 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
48 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
49 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
50 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
51 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
52 import org
.asamk
.signal
.manager
.helper
.Context
;
53 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
54 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
55 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
57 import org
.asamk
.signal
.manager
.storage
.recipients
.Recipient
;
58 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
59 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
60 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
61 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
62 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
63 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
64 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
65 import org
.slf4j
.Logger
;
66 import org
.slf4j
.LoggerFactory
;
67 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServicePreview
;
70 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
71 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
72 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
73 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
74 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
75 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
76 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
77 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
80 import java
.io
.IOException
;
82 import java
.time
.Duration
;
83 import java
.util
.ArrayList
;
84 import java
.util
.Collection
;
85 import java
.util
.HashMap
;
86 import java
.util
.HashSet
;
87 import java
.util
.List
;
89 import java
.util
.Objects
;
90 import java
.util
.Optional
;
92 import java
.util
.concurrent
.ExecutorService
;
93 import java
.util
.concurrent
.Executors
;
94 import java
.util
.concurrent
.atomic
.AtomicInteger
;
95 import java
.util
.concurrent
.locks
.ReentrantLock
;
96 import java
.util
.function
.Function
;
97 import java
.util
.stream
.Collectors
;
98 import java
.util
.stream
.Stream
;
100 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
102 class ManagerImpl
implements Manager
{
104 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
106 private SignalAccount account
;
107 private final SignalDependencies dependencies
;
108 private final Context context
;
110 private final ExecutorService executor
= Executors
.newCachedThreadPool();
112 private Thread receiveThread
;
113 private boolean isReceivingSynchronous
;
114 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
115 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
116 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
117 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
118 private final CompositeDisposable disposable
= new CompositeDisposable();
121 SignalAccount account
,
122 PathConfig pathConfig
,
123 AccountFileUpdater accountFileUpdater
,
124 ServiceEnvironmentConfig serviceEnvironmentConfig
,
127 this.account
= account
;
129 final var sessionLock
= new SignalSessionLock() {
130 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
133 public Lock
acquire() {
135 return LEGACY_LOCK
::unlock
;
138 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
140 account
.getCredentialsProvider(),
141 account
.getSignalServiceDataStore(),
144 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
145 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
146 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
148 this.context
= new Context(account
, new AccountFileUpdater() {
150 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
151 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
152 synchronized (addressChangedListeners
) {
153 addressChangedListeners
.forEach(Runnable
::run
);
158 public void removeAccount() {
159 accountFileUpdater
.removeAccount();
161 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
162 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
163 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
164 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
165 synchronized (this) {
169 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
170 logger
.trace("Archiving old sessions for {}", recipientId
);
171 account
.getSessionStore().archiveSessions(recipientId
);
172 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
173 final var profile
= account
.getProfileStore().getProfile(recipientId
);
174 if (profile
!= null) {
175 account
.getProfileStore()
176 .storeProfile(recipientId
,
177 Profile
.newBuilder(profile
)
178 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
179 .withLastUpdateTimestamp(0)
186 public String
getSelfNumber() {
187 return account
.getNumber();
190 void checkAccountState() throws IOException
{
191 context
.getAccountHelper().checkAccountState();
195 public Map
<String
, UserStatus
> getUserStatus(Set
<String
> numbers
) throws IOException
{
196 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
198 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
199 if (!canonicalizedNumber
.equals(n
)) {
200 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
202 return canonicalizedNumber
;
203 } catch (InvalidNumberException e
) {
208 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
209 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
211 .filter(s
-> !s
.isEmpty())
212 .collect(Collectors
.toSet());
213 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
215 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
216 final var number
= canonicalizedNumbers
.get(n
);
217 final var aci
= registeredUsers
.get(number
);
218 final var profile
= aci
== null
220 : context
.getProfileHelper()
221 .getRecipientProfile(account
.getRecipientResolver().resolveRecipient(aci
));
222 return new UserStatus(number
.isEmpty() ?
null : number
,
223 aci
== null ?
null : aci
.uuid(),
225 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
230 public void updateAccountAttributes(String deviceName
) throws IOException
{
231 if (deviceName
!= null) {
232 context
.getAccountHelper().setDeviceName(deviceName
);
234 context
.getAccountHelper().checkWhoAmiI();
235 context
.getAccountHelper().updateAccountAttributes();
239 public Configuration
getConfiguration() {
240 final var configurationStore
= account
.getConfigurationStore();
241 return Configuration
.from(configurationStore
);
245 public void updateConfiguration(
246 Configuration configuration
247 ) throws NotPrimaryDeviceException
{
248 if (!account
.isPrimaryDevice()) {
249 throw new NotPrimaryDeviceException();
252 final var configurationStore
= account
.getConfigurationStore();
253 if (configuration
.readReceipts().isPresent()) {
254 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
256 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
257 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
259 if (configuration
.typingIndicators().isPresent()) {
260 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
262 if (configuration
.linkPreviews().isPresent()) {
263 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
265 context
.getSyncHelper().sendConfigurationMessage();
269 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
270 context
.getProfileHelper()
271 .setProfile(updateProfile
.getGivenName(),
272 updateProfile
.getFamilyName(),
273 updateProfile
.getAbout(),
274 updateProfile
.getAboutEmoji(),
275 updateProfile
.isDeleteAvatar()
277 : updateProfile
.getAvatar() == null ?
null : Optional
.of(updateProfile
.getAvatar()),
278 updateProfile
.getMobileCoinAddress());
279 context
.getSyncHelper().sendSyncFetchProfileMessage();
283 public void unregister() throws IOException
{
284 context
.getAccountHelper().unregister();
288 public void deleteAccount() throws IOException
{
289 context
.getAccountHelper().deleteAccount();
293 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
294 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
296 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
300 public List
<Device
> getLinkedDevices() throws IOException
{
301 var devices
= dependencies
.getAccountManager().getDevices();
302 account
.setMultiDevice(devices
.size() > 1);
303 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
304 return devices
.stream().map(d
-> {
305 String deviceName
= d
.getName();
306 if (deviceName
!= null) {
308 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
309 } catch (IOException e
) {
310 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
313 return new Device(d
.getId(),
317 d
.getId() == account
.getDeviceId());
322 public void removeLinkedDevices(int deviceId
) throws IOException
{
323 context
.getAccountHelper().removeLinkedDevices(deviceId
);
327 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
328 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
329 context
.getAccountHelper().addDevice(deviceLinkInfo
);
333 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotPrimaryDeviceException
{
334 if (!account
.isPrimaryDevice()) {
335 throw new NotPrimaryDeviceException();
337 if (pin
.isPresent()) {
338 context
.getAccountHelper().setRegistrationPin(pin
.get());
340 context
.getAccountHelper().removeRegistrationPin();
344 void refreshPreKeys() throws IOException
{
345 context
.getPreKeyHelper().refreshPreKeys();
349 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
350 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
354 public List
<Group
> getGroups() {
355 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
358 private Group
toGroup(final GroupInfo groupInfo
) {
359 if (groupInfo
== null) {
363 return Group
.from(groupInfo
, account
.getRecipientAddressResolver(), account
.getSelfRecipientId());
367 public SendGroupMessageResults
quitGroup(
368 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
369 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
370 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
371 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
375 public void deleteGroup(GroupId groupId
) throws IOException
{
376 final var group
= context
.getGroupHelper().getGroup(groupId
);
377 if (group
.isMember(account
.getSelfRecipientId())) {
378 throw new IOException(
379 "The local group information cannot be removed, as the user is still a member of the group");
381 context
.getGroupHelper().deleteGroup(groupId
);
385 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
386 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
387 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
388 return context
.getGroupHelper()
390 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
395 public SendGroupMessageResults
updateGroup(
396 final GroupId groupId
, final UpdateGroup updateGroup
397 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
398 return context
.getGroupHelper()
399 .updateGroup(groupId
,
400 updateGroup
.getName(),
401 updateGroup
.getDescription(),
402 updateGroup
.getMembers() == null
404 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
405 updateGroup
.getRemoveMembers() == null
407 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
408 updateGroup
.getAdmins() == null
410 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
411 updateGroup
.getRemoveAdmins() == null
413 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
414 updateGroup
.getBanMembers() == null
416 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
417 updateGroup
.getUnbanMembers() == null
419 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
420 updateGroup
.isResetGroupLink(),
421 updateGroup
.getGroupLinkState(),
422 updateGroup
.getAddMemberPermission(),
423 updateGroup
.getEditDetailsPermission(),
424 updateGroup
.getAvatarFile(),
425 updateGroup
.getExpirationTimer(),
426 updateGroup
.getIsAnnouncementGroup());
430 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
431 GroupInviteLinkUrl inviteLinkUrl
432 ) throws IOException
, InactiveGroupLinkException
{
433 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
436 private SendMessageResults
sendMessage(
437 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
438 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
439 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
440 long timestamp
= System
.currentTimeMillis();
441 messageBuilder
.withTimestamp(timestamp
);
442 for (final var recipient
: recipients
) {
443 if (recipient
instanceof RecipientIdentifier
.Single single
) {
445 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
446 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
447 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
448 } catch (UnregisteredRecipientException e
) {
449 results
.put(recipient
,
450 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
452 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
453 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
454 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
455 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
456 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
457 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
460 return new SendMessageResults(timestamp
, results
);
463 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
464 return SendMessageResult
.from(result
, account
.getRecipientResolver(), account
.getRecipientAddressResolver());
467 private SendMessageResults
sendTypingMessage(
468 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
469 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
470 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
471 final var timestamp
= System
.currentTimeMillis();
472 for (var recipient
: recipients
) {
473 if (recipient
instanceof RecipientIdentifier
.Single single
) {
474 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
476 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
477 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
478 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
479 } catch (UnregisteredRecipientException e
) {
480 results
.put(recipient
,
481 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
483 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
484 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
485 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
486 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
487 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
490 return new SendMessageResults(timestamp
, results
);
494 public SendMessageResults
sendTypingMessage(
495 TypingAction action
, Set
<RecipientIdentifier
> recipients
496 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
497 return sendTypingMessage(action
.toSignalService(), recipients
);
501 public SendMessageResults
sendReadReceipt(
502 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
504 final var timestamp
= System
.currentTimeMillis();
505 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
509 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
513 public SendMessageResults
sendViewedReceipt(
514 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
516 final var timestamp
= System
.currentTimeMillis();
517 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
521 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
524 private SendMessageResults
sendReceiptMessage(
525 final RecipientIdentifier
.Single sender
,
526 final long timestamp
,
527 final SignalServiceReceiptMessage receiptMessage
530 final var result
= context
.getSendHelper()
531 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
532 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
533 } catch (UnregisteredRecipientException e
) {
534 return new SendMessageResults(timestamp
,
535 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
540 public SendMessageResults
sendMessage(
541 Message message
, Set
<RecipientIdentifier
> recipients
542 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
543 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
544 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
546 "No profile name set. When sending a message it's recommended to set a profile name wit the updateProfile command. This may become mandatory in the future.");
548 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
549 applyMessage(messageBuilder
, message
);
550 return sendMessage(messageBuilder
, recipients
);
553 private void applyMessage(
554 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
555 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
556 messageBuilder
.withBody(message
.messageText());
557 if (message
.attachments().size() > 0) {
558 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(message
.attachments()));
560 if (message
.mentions().size() > 0) {
561 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
563 if (message
.quote().isPresent()) {
564 final var quote
= message
.quote().get();
565 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
566 context
.getRecipientHelper()
567 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
570 resolveMentions(quote
.mentions()),
571 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
573 if (message
.sticker().isPresent()) {
574 final var sticker
= message
.sticker().get();
575 final var packId
= StickerPackId
.deserialize(sticker
.packId());
576 final var stickerId
= sticker
.stickerId();
578 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
579 if (stickerPack
== null) {
580 throw new InvalidStickerException("Sticker pack not found");
582 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
583 if (manifest
.stickers().size() <= stickerId
) {
584 throw new InvalidStickerException("Sticker id not part of this pack");
586 final var manifestSticker
= manifest
.stickers().get(stickerId
);
587 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
588 if (streamDetails
== null) {
589 throw new InvalidStickerException("Missing local sticker file");
591 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
592 stickerPack
.getPackKey(),
594 manifestSticker
.emoji(),
595 AttachmentUtils
.createAttachmentStream(streamDetails
, Optional
.empty())));
597 if (message
.previews().size() > 0) {
598 final var previews
= new ArrayList
<SignalServicePreview
>(message
.previews().size());
599 for (final var p
: message
.previews()) {
600 final var image
= p
.image().isPresent() ? context
.getAttachmentHelper()
601 .uploadAttachment(p
.image().get()) : null;
602 previews
.add(new SignalServicePreview(p
.url(),
606 Optional
.ofNullable(image
)));
608 messageBuilder
.withPreviews(previews
);
612 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
613 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
614 for (final var m
: mentionList
) {
615 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
616 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
617 .resolveSignalServiceAddress(recipientId
)
618 .getServiceId(), m
.start(), m
.length()));
624 public SendMessageResults
sendRemoteDeleteMessage(
625 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
626 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
627 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
628 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
629 for (final var recipient
: recipients
) {
630 if (recipient
instanceof RecipientIdentifier
.Single r
) {
632 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
633 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
634 } catch (UnregisteredRecipientException ignored
) {
636 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
637 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
640 return sendMessage(messageBuilder
, recipients
);
644 public SendMessageResults
sendMessageReaction(
647 RecipientIdentifier
.Single targetAuthor
,
648 long targetSentTimestamp
,
649 Set
<RecipientIdentifier
> recipients
650 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
651 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
652 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
654 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
655 targetSentTimestamp
);
656 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
657 return sendMessage(messageBuilder
, recipients
);
661 public SendMessageResults
sendPaymentNotificationMessage(
662 byte[] receipt
, String note
, RecipientIdentifier
.Single recipient
663 ) throws IOException
{
664 final var paymentNotification
= new SignalServiceDataMessage
.PaymentNotification(receipt
, note
);
665 final var payment
= new SignalServiceDataMessage
.Payment(paymentNotification
);
666 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withPayment(payment
);
668 return sendMessage(messageBuilder
, Set
.of(recipient
));
669 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
670 throw new AssertionError(e
);
675 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
676 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
679 return sendMessage(messageBuilder
,
680 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
681 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
682 throw new AssertionError(e
);
684 for (var recipient
: recipients
) {
685 final RecipientId recipientId
;
687 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
688 } catch (UnregisteredRecipientException e
) {
691 account
.getSessionStore().deleteAllSessions(recipientId
);
697 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
698 account
.removeRecipient(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
702 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
703 account
.getContactStore()
704 .deleteContact(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
708 public void setContactName(
709 RecipientIdentifier
.Single recipient
, String givenName
, final String familyName
710 ) throws NotPrimaryDeviceException
, UnregisteredRecipientException
{
711 if (!account
.isPrimaryDevice()) {
712 throw new NotPrimaryDeviceException();
714 context
.getContactHelper()
715 .setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), givenName
, familyName
);
719 public void setContactsBlocked(
720 Collection
<RecipientIdentifier
.Single
> recipients
, boolean blocked
721 ) throws NotPrimaryDeviceException
, IOException
, UnregisteredRecipientException
{
722 if (!account
.isPrimaryDevice()) {
723 throw new NotPrimaryDeviceException();
725 if (recipients
.size() == 0) {
728 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
729 final var selfRecipientId
= account
.getSelfRecipientId();
730 boolean shouldRotateProfileKey
= false;
731 for (final var recipientId
: recipientIds
) {
732 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
735 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
736 // if we don't have a common group with the blocked contact we need to rotate the profile key
737 shouldRotateProfileKey
= blocked
&& (
738 shouldRotateProfileKey
|| account
.getGroupStore()
741 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
744 if (shouldRotateProfileKey
) {
745 context
.getProfileHelper().rotateProfileKey();
747 context
.getSyncHelper().sendBlockedList();
751 public void setGroupsBlocked(
752 final Collection
<GroupId
> groupIds
, final boolean blocked
753 ) throws GroupNotFoundException
, NotPrimaryDeviceException
, IOException
{
754 if (!account
.isPrimaryDevice()) {
755 throw new NotPrimaryDeviceException();
757 if (groupIds
.size() == 0) {
760 boolean shouldRotateProfileKey
= false;
761 for (final var groupId
: groupIds
) {
762 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
765 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
766 shouldRotateProfileKey
= blocked
;
768 if (shouldRotateProfileKey
) {
769 context
.getProfileHelper().rotateProfileKey();
771 context
.getSyncHelper().sendBlockedList();
775 public void setExpirationTimer(
776 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
777 ) throws IOException
, UnregisteredRecipientException
{
778 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
779 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
780 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
782 sendMessage(messageBuilder
, Set
.of(recipient
));
783 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
784 throw new AssertionError(e
);
789 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
790 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
792 var messageSender
= dependencies
.getMessageSender();
794 var packKey
= KeyUtils
.createStickerUploadKey();
795 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
796 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
798 var sticker
= new Sticker(packId
, packKey
);
799 account
.getStickerStore().updateSticker(sticker
);
801 return new StickerPackUrl(packId
, packKey
);
805 public List
<StickerPack
> getStickerPacks() {
806 final var stickerPackStore
= context
.getStickerPackStore();
807 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
808 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
810 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
811 return new StickerPack(pack
.getPackId(),
812 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
816 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
817 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
818 } catch (Exception e
) {
819 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
823 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
828 public void requestAllSyncData() throws IOException
{
829 context
.getSyncHelper().requestAllSyncData();
830 retrieveRemoteStorage();
833 void retrieveRemoteStorage() throws IOException
{
834 context
.getStorageHelper().readDataFromStorage();
838 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
839 if (isReceivingSynchronous
) {
840 throw new IllegalStateException("Already receiving message synchronously.");
842 synchronized (messageHandlers
) {
843 if (isWeakListener
) {
844 weakHandlers
.add(handler
);
846 messageHandlers
.add(handler
);
847 startReceiveThreadIfRequired();
852 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
854 private void startReceiveThreadIfRequired() {
855 if (receiveThread
!= null) {
858 receiveThread
= new Thread(() -> {
859 logger
.debug("Starting receiving messages");
860 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
861 synchronized (messageHandlers
) {
862 final var handlers
= Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).toList();
863 handlers
.forEach(h
-> {
865 h
.handleMessage(envelope
, e
);
866 } catch (Throwable ex
) {
867 logger
.warn("Message handler failed, ignoring", ex
);
872 logger
.debug("Finished receiving messages");
873 synchronized (messageHandlers
) {
874 receiveThread
= null;
876 // Check if in the meantime another handler has been registered
877 if (!messageHandlers
.isEmpty()) {
878 logger
.debug("Another handler has been registered, starting receive thread again");
879 startReceiveThreadIfRequired();
883 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
885 receiveThread
.start();
889 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
891 synchronized (messageHandlers
) {
892 weakHandlers
.remove(handler
);
893 messageHandlers
.remove(handler
);
894 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
897 thread
= receiveThread
;
898 receiveThread
= null;
901 stopReceiveThread(thread
);
904 private void stopReceiveThread(final Thread thread
) {
905 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
906 logger
.debug("Receive stop requested, interrupting read from server.");
911 } catch (InterruptedException ignored
) {
916 public boolean isReceiving() {
917 if (isReceivingSynchronous
) {
920 synchronized (messageHandlers
) {
921 return messageHandlers
.size() > 0;
926 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
927 receiveMessages(timeout
, true, handler
);
931 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
932 receiveMessages(Duration
.ofMinutes(1), false, handler
);
935 private void receiveMessages(
936 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
937 ) throws IOException
{
939 throw new IllegalStateException("Already receiving message.");
941 isReceivingSynchronous
= true;
942 receiveThread
= Thread
.currentThread();
944 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
946 receiveThread
= null;
947 isReceivingSynchronous
= false;
952 public void setReceiveConfig(final ReceiveConfig receiveConfig
) {
953 context
.getReceiveHelper().setReceiveConfig(receiveConfig
);
957 public boolean hasCaughtUpWithOldMessages() {
958 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
962 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
963 final RecipientId recipientId
;
965 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
966 } catch (UnregisteredRecipientException e
) {
969 return context
.getContactHelper().isContactBlocked(recipientId
);
973 public void sendContacts() throws IOException
{
974 context
.getSyncHelper().sendContacts();
978 public List
<Recipient
> getRecipients(
979 boolean onlyContacts
,
980 Optional
<Boolean
> blocked
,
981 Collection
<RecipientIdentifier
.Single
> recipients
,
982 Optional
<String
> name
984 final var recipientIds
= recipients
.stream().map(a
-> {
986 return context
.getRecipientHelper().resolveRecipient(a
);
987 } catch (UnregisteredRecipientException e
) {
990 }).filter(Objects
::nonNull
).collect(Collectors
.toSet());
991 if (!recipients
.isEmpty() && recipientIds
.isEmpty()) {
994 // refresh profiles of explicitly given recipients
995 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
996 return account
.getRecipientStore().getRecipients(onlyContacts
, blocked
, recipientIds
, name
);
1000 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1001 final RecipientId recipientId
;
1003 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1004 } catch (UnregisteredRecipientException e
) {
1008 final var contact
= account
.getContactStore().getContact(recipientId
);
1009 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1010 return contact
.getName();
1013 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
1014 if (profile
!= null) {
1015 return profile
.getDisplayName();
1022 public Group
getGroup(GroupId groupId
) {
1023 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1027 public List
<Identity
> getIdentities() {
1028 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1031 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1032 if (identityInfo
== null) {
1036 final var address
= account
.getRecipientAddressResolver()
1037 .resolveRecipientAddress(identityInfo
.getRecipientId());
1038 final var scannableFingerprint
= context
.getIdentityHelper()
1039 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
1040 return new Identity(address
,
1041 identityInfo
.getIdentityKey(),
1042 context
.getIdentityHelper()
1043 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1044 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1045 identityInfo
.getTrustLevel(),
1046 identityInfo
.getDateAdded());
1050 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1051 IdentityInfo identity
;
1053 identity
= account
.getIdentityKeyStore()
1054 .getIdentityInfo(context
.getRecipientHelper().resolveRecipient(recipient
));
1055 } catch (UnregisteredRecipientException e
) {
1058 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1062 public boolean trustIdentityVerified(
1063 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1064 ) throws UnregisteredRecipientException
{
1065 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
1069 public boolean trustIdentityVerifiedSafetyNumber(
1070 RecipientIdentifier
.Single recipient
, String safetyNumber
1071 ) throws UnregisteredRecipientException
{
1072 return trustIdentity(recipient
,
1073 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1077 public boolean trustIdentityVerifiedSafetyNumber(
1078 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1079 ) throws UnregisteredRecipientException
{
1080 return trustIdentity(recipient
,
1081 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1085 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1086 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1089 private boolean trustIdentity(
1090 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1091 ) throws UnregisteredRecipientException
{
1092 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1093 final var updated
= trustMethod
.apply(recipientId
);
1094 if (updated
&& this.isReceiving()) {
1095 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1101 public void addAddressChangedListener(final Runnable listener
) {
1102 synchronized (addressChangedListeners
) {
1103 addressChangedListeners
.add(listener
);
1108 public void addClosedListener(final Runnable listener
) {
1109 synchronized (closedListeners
) {
1110 closedListeners
.add(listener
);
1115 public void close() {
1117 synchronized (messageHandlers
) {
1118 weakHandlers
.clear();
1119 messageHandlers
.clear();
1120 thread
= receiveThread
;
1121 receiveThread
= null;
1123 if (thread
!= null) {
1124 stopReceiveThread(thread
);
1126 executor
.shutdown();
1128 dependencies
.getSignalWebSocket().disconnect();
1129 disposable
.dispose();
1131 if (account
!= null) {
1135 synchronized (closedListeners
) {
1136 closedListeners
.forEach(Runnable
::run
);
1137 closedListeners
.clear();