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
.NotMasterDeviceException
;
29 import org
.asamk
.signal
.manager
.api
.Pair
;
30 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
31 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
32 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
33 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
34 import org
.asamk
.signal
.manager
.api
.StickerPack
;
35 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
36 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
37 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
38 import org
.asamk
.signal
.manager
.api
.TypingAction
;
39 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
40 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
41 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
42 import org
.asamk
.signal
.manager
.api
.UserStatus
;
43 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
44 import org
.asamk
.signal
.manager
.groups
.GroupId
;
45 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
46 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
47 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
48 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
49 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
50 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
51 import org
.asamk
.signal
.manager
.helper
.Context
;
52 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
53 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
54 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.Recipient
;
57 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
58 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
59 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
60 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
61 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
62 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
63 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
64 import org
.slf4j
.Logger
;
65 import org
.slf4j
.LoggerFactory
;
66 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
70 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
71 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
72 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
73 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
74 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
75 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
78 import java
.io
.IOException
;
80 import java
.time
.Duration
;
81 import java
.util
.ArrayList
;
82 import java
.util
.Collection
;
83 import java
.util
.HashMap
;
84 import java
.util
.HashSet
;
85 import java
.util
.List
;
87 import java
.util
.Objects
;
88 import java
.util
.Optional
;
90 import java
.util
.concurrent
.ExecutorService
;
91 import java
.util
.concurrent
.Executors
;
92 import java
.util
.concurrent
.atomic
.AtomicInteger
;
93 import java
.util
.concurrent
.locks
.ReentrantLock
;
94 import java
.util
.function
.Function
;
95 import java
.util
.stream
.Collectors
;
96 import java
.util
.stream
.Stream
;
98 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
100 class ManagerImpl
implements Manager
{
102 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
104 private SignalAccount account
;
105 private final SignalDependencies dependencies
;
106 private final Context context
;
108 private final ExecutorService executor
= Executors
.newCachedThreadPool();
110 private Thread receiveThread
;
111 private boolean isReceivingSynchronous
;
112 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
113 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
114 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
115 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
116 private final CompositeDisposable disposable
= new CompositeDisposable();
119 SignalAccount account
,
120 PathConfig pathConfig
,
121 AccountFileUpdater accountFileUpdater
,
122 ServiceEnvironmentConfig serviceEnvironmentConfig
,
125 this.account
= account
;
127 final var sessionLock
= new SignalSessionLock() {
128 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
131 public Lock
acquire() {
133 return LEGACY_LOCK
::unlock
;
136 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
138 account
.getCredentialsProvider(),
139 account
.getSignalServiceDataStore(),
142 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
143 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
144 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
146 this.context
= new Context(account
, new AccountFileUpdater() {
148 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
149 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
150 synchronized (addressChangedListeners
) {
151 addressChangedListeners
.forEach(Runnable
::run
);
156 public void removeAccount() {
157 accountFileUpdater
.removeAccount();
159 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
160 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
161 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
162 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
163 synchronized (this) {
167 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
168 logger
.trace("Archiving old sessions for {}", recipientId
);
169 account
.getSessionStore().archiveSessions(recipientId
);
170 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
171 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
172 if (profile
!= null) {
173 account
.getRecipientStore()
174 .storeProfile(recipientId
,
175 Profile
.newBuilder(profile
)
176 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
177 .withLastUpdateTimestamp(0)
184 public String
getSelfNumber() {
185 return account
.getNumber();
188 void checkAccountState() throws IOException
{
189 context
.getAccountHelper().checkAccountState();
193 public Map
<String
, UserStatus
> getUserStatus(Set
<String
> numbers
) throws IOException
{
194 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
196 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
197 if (!canonicalizedNumber
.equals(n
)) {
198 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
200 return canonicalizedNumber
;
201 } catch (InvalidNumberException e
) {
206 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
207 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
209 .filter(s
-> !s
.isEmpty())
210 .collect(Collectors
.toSet());
211 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
213 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
214 final var number
= canonicalizedNumbers
.get(n
);
215 final var aci
= registeredUsers
.get(number
);
216 final var profile
= aci
== null
218 : context
.getProfileHelper().getRecipientProfile(account
.getRecipientStore().resolveRecipient(aci
));
219 return new UserStatus(number
.isEmpty() ?
null : number
,
220 aci
== null ?
null : aci
.uuid(),
222 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
227 public void updateAccountAttributes(String deviceName
) throws IOException
{
228 if (deviceName
!= null) {
229 context
.getAccountHelper().setDeviceName(deviceName
);
231 context
.getAccountHelper().updateAccountAttributes();
235 public Configuration
getConfiguration() {
236 final var configurationStore
= account
.getConfigurationStore();
237 return Configuration
.from(configurationStore
);
241 public void updateConfiguration(
242 Configuration configuration
243 ) throws NotMasterDeviceException
{
244 if (!account
.isMasterDevice()) {
245 throw new NotMasterDeviceException();
248 final var configurationStore
= account
.getConfigurationStore();
249 if (configuration
.readReceipts().isPresent()) {
250 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
252 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
253 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
255 if (configuration
.typingIndicators().isPresent()) {
256 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
258 if (configuration
.linkPreviews().isPresent()) {
259 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
261 context
.getSyncHelper().sendConfigurationMessage();
265 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
266 context
.getProfileHelper()
267 .setProfile(updateProfile
.getGivenName(),
268 updateProfile
.getFamilyName(),
269 updateProfile
.getAbout(),
270 updateProfile
.getAboutEmoji(),
271 updateProfile
.isDeleteAvatar()
273 : updateProfile
.getAvatar() == null ?
null : Optional
.of(updateProfile
.getAvatar()),
274 updateProfile
.getMobileCoinAddress());
275 context
.getSyncHelper().sendSyncFetchProfileMessage();
279 public void unregister() throws IOException
{
280 context
.getAccountHelper().unregister();
284 public void deleteAccount() throws IOException
{
285 context
.getAccountHelper().deleteAccount();
289 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
290 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
292 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
296 public List
<Device
> getLinkedDevices() throws IOException
{
297 var devices
= dependencies
.getAccountManager().getDevices();
298 account
.setMultiDevice(devices
.size() > 1);
299 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
300 return devices
.stream().map(d
-> {
301 String deviceName
= d
.getName();
302 if (deviceName
!= null) {
304 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
305 } catch (IOException e
) {
306 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
309 return new Device(d
.getId(),
313 d
.getId() == account
.getDeviceId());
318 public void removeLinkedDevices(int deviceId
) throws IOException
{
319 context
.getAccountHelper().removeLinkedDevices(deviceId
);
323 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
324 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
325 context
.getAccountHelper().addDevice(deviceLinkInfo
);
329 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
330 if (!account
.isMasterDevice()) {
331 throw new NotMasterDeviceException();
333 if (pin
.isPresent()) {
334 context
.getAccountHelper().setRegistrationPin(pin
.get());
336 context
.getAccountHelper().removeRegistrationPin();
340 void refreshPreKeys() throws IOException
{
341 context
.getPreKeyHelper().refreshPreKeys();
345 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
346 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
350 public List
<Group
> getGroups() {
351 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
354 private Group
toGroup(final GroupInfo groupInfo
) {
355 if (groupInfo
== null) {
359 return Group
.from(groupInfo
,
360 account
.getRecipientStore()::resolveRecipientAddress
,
361 account
.getSelfRecipientId());
365 public SendGroupMessageResults
quitGroup(
366 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
367 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
368 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
369 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
373 public void deleteGroup(GroupId groupId
) throws IOException
{
374 final var group
= context
.getGroupHelper().getGroup(groupId
);
375 if (group
.isMember(account
.getSelfRecipientId())) {
376 throw new IOException(
377 "The local group information cannot be removed, as the user is still a member of the group");
379 context
.getGroupHelper().deleteGroup(groupId
);
383 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
384 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
385 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
386 return context
.getGroupHelper()
388 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
393 public SendGroupMessageResults
updateGroup(
394 final GroupId groupId
, final UpdateGroup updateGroup
395 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
396 return context
.getGroupHelper()
397 .updateGroup(groupId
,
398 updateGroup
.getName(),
399 updateGroup
.getDescription(),
400 updateGroup
.getMembers() == null
402 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
403 updateGroup
.getRemoveMembers() == null
405 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
406 updateGroup
.getAdmins() == null
408 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
409 updateGroup
.getRemoveAdmins() == null
411 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
412 updateGroup
.getBanMembers() == null
414 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
415 updateGroup
.getUnbanMembers() == null
417 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
418 updateGroup
.isResetGroupLink(),
419 updateGroup
.getGroupLinkState(),
420 updateGroup
.getAddMemberPermission(),
421 updateGroup
.getEditDetailsPermission(),
422 updateGroup
.getAvatarFile(),
423 updateGroup
.getExpirationTimer(),
424 updateGroup
.getIsAnnouncementGroup());
428 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
429 GroupInviteLinkUrl inviteLinkUrl
430 ) throws IOException
, InactiveGroupLinkException
{
431 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
434 private SendMessageResults
sendMessage(
435 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
436 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
437 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
438 long timestamp
= System
.currentTimeMillis();
439 messageBuilder
.withTimestamp(timestamp
);
440 for (final var recipient
: recipients
) {
441 if (recipient
instanceof RecipientIdentifier
.Single single
) {
443 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
444 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
445 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
446 } catch (UnregisteredRecipientException e
) {
447 results
.put(recipient
,
448 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
450 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
451 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
452 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
453 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
454 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
455 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
458 return new SendMessageResults(timestamp
, results
);
461 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
462 return SendMessageResult
.from(result
,
463 account
.getRecipientStore(),
464 account
.getRecipientStore()::resolveRecipientAddress
);
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 final var attachments
= message
.attachments();
558 if (attachments
!= null) {
559 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
561 if (message
.mentions().size() > 0) {
562 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
564 if (message
.quote().isPresent()) {
565 final var quote
= message
.quote().get();
566 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
567 context
.getRecipientHelper()
568 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
571 resolveMentions(quote
.mentions()),
572 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
574 if (message
.sticker().isPresent()) {
575 final var sticker
= message
.sticker().get();
576 final var packId
= StickerPackId
.deserialize(sticker
.packId());
577 final var stickerId
= sticker
.stickerId();
579 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
580 if (stickerPack
== null) {
581 throw new InvalidStickerException("Sticker pack not found");
583 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
584 if (manifest
.stickers().size() <= stickerId
) {
585 throw new InvalidStickerException("Sticker id not part of this pack");
587 final var manifestSticker
= manifest
.stickers().get(stickerId
);
588 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
589 if (streamDetails
== null) {
590 throw new InvalidStickerException("Missing local sticker file");
592 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
593 stickerPack
.getPackKey(),
595 manifestSticker
.emoji(),
596 AttachmentUtils
.createAttachment(streamDetails
, Optional
.empty())));
600 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
601 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
602 for (final var m
: mentionList
) {
603 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
604 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
605 .resolveSignalServiceAddress(recipientId
)
606 .getServiceId(), m
.start(), m
.length()));
612 public SendMessageResults
sendRemoteDeleteMessage(
613 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
614 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
615 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
616 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
617 for (final var recipient
: recipients
) {
618 if (recipient
instanceof RecipientIdentifier
.Single r
) {
620 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
621 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
622 } catch (UnregisteredRecipientException ignored
) {
624 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
625 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
628 return sendMessage(messageBuilder
, recipients
);
632 public SendMessageResults
sendMessageReaction(
635 RecipientIdentifier
.Single targetAuthor
,
636 long targetSentTimestamp
,
637 Set
<RecipientIdentifier
> recipients
638 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
639 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
640 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
642 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
643 targetSentTimestamp
);
644 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
645 return sendMessage(messageBuilder
, recipients
);
649 public SendMessageResults
sendPaymentNotificationMessage(
650 byte[] receipt
, String note
, RecipientIdentifier
.Single recipient
651 ) throws IOException
{
652 final var paymentNotification
= new SignalServiceDataMessage
.PaymentNotification(receipt
, note
);
653 final var payment
= new SignalServiceDataMessage
.Payment(paymentNotification
);
654 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withPayment(payment
);
656 return sendMessage(messageBuilder
, Set
.of(recipient
));
657 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
658 throw new AssertionError(e
);
663 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
664 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
667 return sendMessage(messageBuilder
,
668 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
669 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
670 throw new AssertionError(e
);
672 for (var recipient
: recipients
) {
673 final RecipientId recipientId
;
675 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
676 } catch (UnregisteredRecipientException e
) {
679 account
.getSessionStore().deleteAllSessions(recipientId
);
685 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
686 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
690 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
691 account
.getContactStore()
692 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
696 public void setContactName(
697 RecipientIdentifier
.Single recipient
, String name
698 ) throws NotMasterDeviceException
, UnregisteredRecipientException
{
699 if (!account
.isMasterDevice()) {
700 throw new NotMasterDeviceException();
702 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
706 public void setContactsBlocked(
707 Collection
<RecipientIdentifier
.Single
> recipients
, boolean blocked
708 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
709 if (!account
.isMasterDevice()) {
710 throw new NotMasterDeviceException();
712 if (recipients
.size() == 0) {
715 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
716 final var selfRecipientId
= account
.getSelfRecipientId();
717 boolean shouldRotateProfileKey
= false;
718 for (final var recipientId
: recipientIds
) {
719 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
722 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
723 // if we don't have a common group with the blocked contact we need to rotate the profile key
724 shouldRotateProfileKey
= blocked
&& (
725 shouldRotateProfileKey
|| account
.getGroupStore()
728 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
731 if (shouldRotateProfileKey
) {
732 context
.getProfileHelper().rotateProfileKey();
734 context
.getSyncHelper().sendBlockedList();
738 public void setGroupsBlocked(
739 final Collection
<GroupId
> groupIds
, final boolean blocked
740 ) throws GroupNotFoundException
, NotMasterDeviceException
, IOException
{
741 if (!account
.isMasterDevice()) {
742 throw new NotMasterDeviceException();
744 if (groupIds
.size() == 0) {
747 boolean shouldRotateProfileKey
= false;
748 for (final var groupId
: groupIds
) {
749 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
752 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
753 shouldRotateProfileKey
= blocked
;
755 if (shouldRotateProfileKey
) {
756 context
.getProfileHelper().rotateProfileKey();
758 context
.getSyncHelper().sendBlockedList();
762 public void setExpirationTimer(
763 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
764 ) throws IOException
, UnregisteredRecipientException
{
765 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
766 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
767 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
769 sendMessage(messageBuilder
, Set
.of(recipient
));
770 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
771 throw new AssertionError(e
);
776 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
777 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
779 var messageSender
= dependencies
.getMessageSender();
781 var packKey
= KeyUtils
.createStickerUploadKey();
782 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
783 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
785 var sticker
= new Sticker(packId
, packKey
);
786 account
.getStickerStore().updateSticker(sticker
);
788 return new StickerPackUrl(packId
, packKey
);
792 public List
<StickerPack
> getStickerPacks() {
793 final var stickerPackStore
= context
.getStickerPackStore();
794 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
795 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
797 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
798 return new StickerPack(pack
.getPackId(),
799 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
803 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
804 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
805 } catch (Exception e
) {
806 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
810 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
815 public void requestAllSyncData() throws IOException
{
816 context
.getSyncHelper().requestAllSyncData();
817 retrieveRemoteStorage();
820 void retrieveRemoteStorage() throws IOException
{
821 if (account
.getStorageKey() != null) {
822 context
.getStorageHelper().readDataFromStorage();
827 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
828 if (isReceivingSynchronous
) {
829 throw new IllegalStateException("Already receiving message synchronously.");
831 synchronized (messageHandlers
) {
832 if (isWeakListener
) {
833 weakHandlers
.add(handler
);
835 messageHandlers
.add(handler
);
836 startReceiveThreadIfRequired();
841 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
843 private void startReceiveThreadIfRequired() {
844 if (receiveThread
!= null) {
847 receiveThread
= new Thread(() -> {
848 logger
.debug("Starting receiving messages");
849 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
850 synchronized (messageHandlers
) {
851 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
853 h
.handleMessage(envelope
, e
);
854 } catch (Throwable ex
) {
855 logger
.warn("Message handler failed, ignoring", ex
);
860 logger
.debug("Finished receiving messages");
861 synchronized (messageHandlers
) {
862 receiveThread
= null;
864 // Check if in the meantime another handler has been registered
865 if (!messageHandlers
.isEmpty()) {
866 logger
.debug("Another handler has been registered, starting receive thread again");
867 startReceiveThreadIfRequired();
871 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
873 receiveThread
.start();
877 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
879 synchronized (messageHandlers
) {
880 weakHandlers
.remove(handler
);
881 messageHandlers
.remove(handler
);
882 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
885 thread
= receiveThread
;
886 receiveThread
= null;
889 stopReceiveThread(thread
);
892 private void stopReceiveThread(final Thread thread
) {
893 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
894 logger
.debug("Receive stop requested, interrupting read from server.");
899 } catch (InterruptedException ignored
) {
904 public boolean isReceiving() {
905 if (isReceivingSynchronous
) {
908 synchronized (messageHandlers
) {
909 return messageHandlers
.size() > 0;
914 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
915 receiveMessages(timeout
, true, handler
);
919 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
920 receiveMessages(Duration
.ofMinutes(1), false, handler
);
923 private void receiveMessages(
924 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
925 ) throws IOException
{
927 throw new IllegalStateException("Already receiving message.");
929 isReceivingSynchronous
= true;
930 receiveThread
= Thread
.currentThread();
932 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
934 receiveThread
= null;
935 isReceivingSynchronous
= false;
940 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
941 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
945 public boolean hasCaughtUpWithOldMessages() {
946 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
950 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
951 final RecipientId recipientId
;
953 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
954 } catch (UnregisteredRecipientException e
) {
957 return context
.getContactHelper().isContactBlocked(recipientId
);
961 public void sendContacts() throws IOException
{
962 context
.getSyncHelper().sendContacts();
966 public List
<Recipient
> getRecipients(
967 boolean onlyContacts
,
968 Optional
<Boolean
> blocked
,
969 Collection
<RecipientIdentifier
.Single
> recipients
,
970 Optional
<String
> name
972 final var recipientIds
= recipients
.stream().map(a
-> {
974 return context
.getRecipientHelper().resolveRecipient(a
);
975 } catch (UnregisteredRecipientException e
) {
978 }).filter(Objects
::nonNull
).collect(Collectors
.toSet());
979 // refresh profiles of explicitly given recipients
980 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
981 return account
.getRecipientStore().getRecipients(onlyContacts
, blocked
, recipientIds
, name
);
985 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
986 final RecipientId recipientId
;
988 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
989 } catch (UnregisteredRecipientException e
) {
993 final var contact
= account
.getContactStore().getContact(recipientId
);
994 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
995 return contact
.getName();
998 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
999 if (profile
!= null) {
1000 return profile
.getDisplayName();
1007 public Group
getGroup(GroupId groupId
) {
1008 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1012 public List
<Identity
> getIdentities() {
1013 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1016 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1017 if (identityInfo
== null) {
1021 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1022 final var scannableFingerprint
= context
.getIdentityHelper()
1023 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
1024 return new Identity(address
,
1025 identityInfo
.getIdentityKey(),
1026 context
.getIdentityHelper()
1027 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1028 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1029 identityInfo
.getTrustLevel(),
1030 identityInfo
.getDateAdded());
1034 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1035 IdentityInfo identity
;
1037 identity
= account
.getIdentityKeyStore()
1038 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
1039 } catch (UnregisteredRecipientException e
) {
1042 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1046 public boolean trustIdentityVerified(
1047 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1048 ) throws UnregisteredRecipientException
{
1049 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
1053 public boolean trustIdentityVerifiedSafetyNumber(
1054 RecipientIdentifier
.Single recipient
, String safetyNumber
1055 ) throws UnregisteredRecipientException
{
1056 return trustIdentity(recipient
,
1057 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1061 public boolean trustIdentityVerifiedSafetyNumber(
1062 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1063 ) throws UnregisteredRecipientException
{
1064 return trustIdentity(recipient
,
1065 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1069 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1070 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1073 private boolean trustIdentity(
1074 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1075 ) throws UnregisteredRecipientException
{
1076 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1077 final var updated
= trustMethod
.apply(recipientId
);
1078 if (updated
&& this.isReceiving()) {
1079 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1085 public void addAddressChangedListener(final Runnable listener
) {
1086 synchronized (addressChangedListeners
) {
1087 addressChangedListeners
.add(listener
);
1092 public void addClosedListener(final Runnable listener
) {
1093 synchronized (closedListeners
) {
1094 closedListeners
.add(listener
);
1099 public void close() {
1101 synchronized (messageHandlers
) {
1102 weakHandlers
.clear();
1103 messageHandlers
.clear();
1104 thread
= receiveThread
;
1105 receiveThread
= null;
1107 if (thread
!= null) {
1108 stopReceiveThread(thread
);
1110 executor
.shutdown();
1112 dependencies
.getSignalWebSocket().disconnect();
1113 disposable
.dispose();
1115 if (account
!= null) {
1119 synchronized (closedListeners
) {
1120 closedListeners
.forEach(Runnable
::run
);
1121 closedListeners
.clear();