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
.config
.ServiceEnvironmentConfig
;
42 import org
.asamk
.signal
.manager
.groups
.GroupId
;
43 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
44 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
45 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
46 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
47 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
48 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
49 import org
.asamk
.signal
.manager
.helper
.Context
;
50 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
51 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
52 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
53 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
57 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
58 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
59 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
60 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
61 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
62 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
63 import org
.slf4j
.Logger
;
64 import org
.slf4j
.LoggerFactory
;
65 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
66 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
69 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
70 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
71 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
72 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
73 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
76 import java
.io
.IOException
;
78 import java
.time
.Duration
;
79 import java
.util
.ArrayList
;
80 import java
.util
.HashMap
;
81 import java
.util
.HashSet
;
82 import java
.util
.List
;
84 import java
.util
.Optional
;
86 import java
.util
.UUID
;
87 import java
.util
.concurrent
.ExecutorService
;
88 import java
.util
.concurrent
.Executors
;
89 import java
.util
.concurrent
.atomic
.AtomicInteger
;
90 import java
.util
.concurrent
.locks
.ReentrantLock
;
91 import java
.util
.function
.Function
;
92 import java
.util
.stream
.Collectors
;
93 import java
.util
.stream
.Stream
;
95 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
97 class ManagerImpl
implements Manager
{
99 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
101 private SignalAccount account
;
102 private final SignalDependencies dependencies
;
103 private final Context context
;
105 private final ExecutorService executor
= Executors
.newCachedThreadPool();
107 private Thread receiveThread
;
108 private boolean isReceivingSynchronous
;
109 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
110 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
111 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
112 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
113 private final CompositeDisposable disposable
= new CompositeDisposable();
116 SignalAccount account
,
117 PathConfig pathConfig
,
118 AccountFileUpdater accountFileUpdater
,
119 ServiceEnvironmentConfig serviceEnvironmentConfig
,
122 this.account
= account
;
124 final var sessionLock
= new SignalSessionLock() {
125 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
128 public Lock
acquire() {
130 return LEGACY_LOCK
::unlock
;
133 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
135 account
.getCredentialsProvider(),
136 account
.getSignalServiceDataStore(),
139 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
140 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
141 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
143 this.context
= new Context(account
, (number
, aci
) -> {
144 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
145 synchronized (addressChangedListeners
) {
146 addressChangedListeners
.forEach(Runnable
::run
);
148 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
149 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
150 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
151 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
152 synchronized (this) {
156 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
157 logger
.trace("Archiving old sessions for {}", recipientId
);
158 account
.getSessionStore().archiveSessions(recipientId
);
159 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
160 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
161 if (profile
!= null) {
162 account
.getRecipientStore()
163 .storeProfile(recipientId
,
164 Profile
.newBuilder(profile
)
165 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
166 .withLastUpdateTimestamp(0)
173 public String
getSelfNumber() {
174 return account
.getNumber();
177 void checkAccountState() throws IOException
{
178 context
.getAccountHelper().checkAccountState();
182 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
183 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
185 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
186 if (!canonicalizedNumber
.equals(n
)) {
187 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
189 return canonicalizedNumber
;
190 } catch (InvalidNumberException e
) {
195 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
196 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
198 .filter(s
-> !s
.isEmpty())
199 .collect(Collectors
.toSet());
200 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
202 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
203 final var number
= canonicalizedNumbers
.get(n
);
204 final var aci
= registeredUsers
.get(number
);
205 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
210 public void updateAccountAttributes(String deviceName
) throws IOException
{
211 if (deviceName
!= null) {
212 context
.getAccountHelper().setDeviceName(deviceName
);
214 context
.getAccountHelper().updateAccountAttributes();
218 public Configuration
getConfiguration() {
219 final var configurationStore
= account
.getConfigurationStore();
220 return Configuration
.from(configurationStore
);
224 public void updateConfiguration(
225 Configuration configuration
226 ) throws NotMasterDeviceException
{
227 if (!account
.isMasterDevice()) {
228 throw new NotMasterDeviceException();
231 final var configurationStore
= account
.getConfigurationStore();
232 if (configuration
.readReceipts().isPresent()) {
233 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
235 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
236 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
238 if (configuration
.typingIndicators().isPresent()) {
239 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
241 if (configuration
.linkPreviews().isPresent()) {
242 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
244 context
.getSyncHelper().sendConfigurationMessage();
248 public void setProfile(
249 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
250 ) throws IOException
{
251 context
.getProfileHelper().setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
252 context
.getSyncHelper().sendSyncFetchProfileMessage();
256 public void unregister() throws IOException
{
257 context
.getAccountHelper().unregister();
261 public void deleteAccount() throws IOException
{
262 context
.getAccountHelper().deleteAccount();
266 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
267 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
269 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
273 public List
<Device
> getLinkedDevices() throws IOException
{
274 var devices
= dependencies
.getAccountManager().getDevices();
275 account
.setMultiDevice(devices
.size() > 1);
276 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
277 return devices
.stream().map(d
-> {
278 String deviceName
= d
.getName();
279 if (deviceName
!= null) {
281 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
282 } catch (IOException e
) {
283 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
286 return new Device(d
.getId(),
290 d
.getId() == account
.getDeviceId());
295 public void removeLinkedDevices(int deviceId
) throws IOException
{
296 context
.getAccountHelper().removeLinkedDevices(deviceId
);
300 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
301 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
302 context
.getAccountHelper().addDevice(deviceLinkInfo
);
306 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
307 if (!account
.isMasterDevice()) {
308 throw new NotMasterDeviceException();
310 if (pin
.isPresent()) {
311 context
.getAccountHelper().setRegistrationPin(pin
.get());
313 context
.getAccountHelper().removeRegistrationPin();
317 void refreshPreKeys() throws IOException
{
318 context
.getPreKeyHelper().refreshPreKeys();
322 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
323 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
327 public List
<Group
> getGroups() {
328 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
331 private Group
toGroup(final GroupInfo groupInfo
) {
332 if (groupInfo
== null) {
336 return Group
.from(groupInfo
,
337 account
.getRecipientStore()::resolveRecipientAddress
,
338 account
.getSelfRecipientId());
342 public SendGroupMessageResults
quitGroup(
343 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
344 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
345 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
346 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
350 public void deleteGroup(GroupId groupId
) throws IOException
{
351 final var group
= context
.getGroupHelper().getGroup(groupId
);
352 if (group
.isMember(account
.getSelfRecipientId())) {
353 throw new IOException(
354 "The local group information cannot be removed, as the user is still a member of the group");
356 context
.getGroupHelper().deleteGroup(groupId
);
360 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
361 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
362 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
363 return context
.getGroupHelper()
365 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
370 public SendGroupMessageResults
updateGroup(
371 final GroupId groupId
, final UpdateGroup updateGroup
372 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
373 return context
.getGroupHelper()
374 .updateGroup(groupId
,
375 updateGroup
.getName(),
376 updateGroup
.getDescription(),
377 updateGroup
.getMembers() == null
379 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
380 updateGroup
.getRemoveMembers() == null
382 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
383 updateGroup
.getAdmins() == null
385 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
386 updateGroup
.getRemoveAdmins() == null
388 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
389 updateGroup
.isResetGroupLink(),
390 updateGroup
.getGroupLinkState(),
391 updateGroup
.getAddMemberPermission(),
392 updateGroup
.getEditDetailsPermission(),
393 updateGroup
.getAvatarFile(),
394 updateGroup
.getExpirationTimer(),
395 updateGroup
.getIsAnnouncementGroup());
399 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
400 GroupInviteLinkUrl inviteLinkUrl
401 ) throws IOException
, InactiveGroupLinkException
{
402 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
405 private SendMessageResults
sendMessage(
406 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
407 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
408 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
409 long timestamp
= System
.currentTimeMillis();
410 messageBuilder
.withTimestamp(timestamp
);
411 for (final var recipient
: recipients
) {
412 if (recipient
instanceof RecipientIdentifier
.Single single
) {
414 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
415 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
416 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
417 } catch (UnregisteredRecipientException e
) {
418 results
.put(recipient
,
419 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
421 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
422 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
423 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
424 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
425 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
426 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
429 return new SendMessageResults(timestamp
, results
);
432 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
433 return SendMessageResult
.from(result
,
434 account
.getRecipientStore(),
435 account
.getRecipientStore()::resolveRecipientAddress
);
438 private SendMessageResults
sendTypingMessage(
439 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
440 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
441 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
442 final var timestamp
= System
.currentTimeMillis();
443 for (var recipient
: recipients
) {
444 if (recipient
instanceof RecipientIdentifier
.Single single
) {
445 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
447 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
448 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
449 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
450 } catch (UnregisteredRecipientException e
) {
451 results
.put(recipient
,
452 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
454 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
455 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
456 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
457 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
458 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
461 return new SendMessageResults(timestamp
, results
);
465 public SendMessageResults
sendTypingMessage(
466 TypingAction action
, Set
<RecipientIdentifier
> recipients
467 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
468 return sendTypingMessage(action
.toSignalService(), recipients
);
472 public SendMessageResults
sendReadReceipt(
473 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
474 ) throws IOException
{
475 final var timestamp
= System
.currentTimeMillis();
476 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
480 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
484 public SendMessageResults
sendViewedReceipt(
485 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
486 ) throws IOException
{
487 final var timestamp
= System
.currentTimeMillis();
488 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
492 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
495 private SendMessageResults
sendReceiptMessage(
496 final RecipientIdentifier
.Single sender
,
497 final long timestamp
,
498 final SignalServiceReceiptMessage receiptMessage
499 ) throws IOException
{
501 final var result
= context
.getSendHelper()
502 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
503 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
504 } catch (UnregisteredRecipientException e
) {
505 return new SendMessageResults(timestamp
,
506 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
511 public SendMessageResults
sendMessage(
512 Message message
, Set
<RecipientIdentifier
> recipients
513 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
514 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
515 applyMessage(messageBuilder
, message
);
516 return sendMessage(messageBuilder
, recipients
);
519 private void applyMessage(
520 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
521 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
522 messageBuilder
.withBody(message
.messageText());
523 final var attachments
= message
.attachments();
524 if (attachments
!= null) {
525 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
527 if (message
.mentions().size() > 0) {
528 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
530 if (message
.quote().isPresent()) {
531 final var quote
= message
.quote().get();
532 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
533 context
.getRecipientHelper()
534 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
537 resolveMentions(quote
.mentions())));
539 if (message
.sticker().isPresent()) {
540 final var sticker
= message
.sticker().get();
541 final var packId
= StickerPackId
.deserialize(sticker
.packId());
542 final var stickerId
= sticker
.stickerId();
544 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
545 if (stickerPack
== null) {
546 throw new InvalidStickerException("Sticker pack not found");
548 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
549 if (manifest
.stickers().size() <= stickerId
) {
550 throw new InvalidStickerException("Sticker id not part of this pack");
552 final var manifestSticker
= manifest
.stickers().get(stickerId
);
553 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
554 if (streamDetails
== null) {
555 throw new InvalidStickerException("Missing local sticker file");
557 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
558 stickerPack
.getPackKey(),
560 manifestSticker
.emoji(),
561 AttachmentUtils
.createAttachment(streamDetails
, Optional
.empty())));
565 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
566 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
567 for (final var m
: mentionList
) {
568 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
569 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
570 .resolveSignalServiceAddress(recipientId
)
571 .getServiceId(), m
.start(), m
.length()));
577 public SendMessageResults
sendRemoteDeleteMessage(
578 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
579 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
580 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
581 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
582 for (final var recipient
: recipients
) {
583 if (recipient
instanceof RecipientIdentifier
.Single r
) {
585 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
586 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
587 } catch (UnregisteredRecipientException ignored
) {
589 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
590 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
593 return sendMessage(messageBuilder
, recipients
);
597 public SendMessageResults
sendMessageReaction(
600 RecipientIdentifier
.Single targetAuthor
,
601 long targetSentTimestamp
,
602 Set
<RecipientIdentifier
> recipients
603 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
604 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
605 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
607 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
608 targetSentTimestamp
);
609 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
610 return sendMessage(messageBuilder
, recipients
);
614 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
615 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
618 return sendMessage(messageBuilder
,
619 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
620 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
621 throw new AssertionError(e
);
623 for (var recipient
: recipients
) {
624 final RecipientId recipientId
;
626 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
627 } catch (UnregisteredRecipientException e
) {
630 account
.getSessionStore().deleteAllSessions(recipientId
);
636 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
637 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
641 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
642 account
.getContactStore()
643 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
647 public void setContactName(
648 RecipientIdentifier
.Single recipient
, String name
649 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
650 if (!account
.isMasterDevice()) {
651 throw new NotMasterDeviceException();
653 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
657 public void setContactBlocked(
658 RecipientIdentifier
.Single recipient
, boolean blocked
659 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
660 if (!account
.isMasterDevice()) {
661 throw new NotMasterDeviceException();
663 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
664 // TODO cycle our profile key, if we're not together in a group with recipient
665 context
.getSyncHelper().sendBlockedList();
669 public void setGroupBlocked(
670 final GroupId groupId
, final boolean blocked
671 ) throws GroupNotFoundException
, NotMasterDeviceException
{
672 if (!account
.isMasterDevice()) {
673 throw new NotMasterDeviceException();
675 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
676 // TODO cycle our profile key
677 context
.getSyncHelper().sendBlockedList();
681 public void setExpirationTimer(
682 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
683 ) throws IOException
, UnregisteredRecipientException
{
684 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
685 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
686 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
688 sendMessage(messageBuilder
, Set
.of(recipient
));
689 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
690 throw new AssertionError(e
);
695 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
696 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
698 var messageSender
= dependencies
.getMessageSender();
700 var packKey
= KeyUtils
.createStickerUploadKey();
701 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
702 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
704 var sticker
= new Sticker(packId
, packKey
);
705 account
.getStickerStore().updateSticker(sticker
);
707 return new StickerPackUrl(packId
, packKey
);
711 public List
<StickerPack
> getStickerPacks() {
712 final var stickerPackStore
= context
.getStickerPackStore();
713 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
714 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
716 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
717 return new StickerPack(pack
.getPackId(),
718 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
722 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
723 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
724 } catch (Exception e
) {
725 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
729 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
734 public void requestAllSyncData() throws IOException
{
735 context
.getSyncHelper().requestAllSyncData();
736 retrieveRemoteStorage();
739 void retrieveRemoteStorage() throws IOException
{
740 if (account
.getStorageKey() != null) {
741 context
.getStorageHelper().readDataFromStorage();
746 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
747 if (isReceivingSynchronous
) {
748 throw new IllegalStateException("Already receiving message synchronously.");
750 synchronized (messageHandlers
) {
751 if (isWeakListener
) {
752 weakHandlers
.add(handler
);
754 messageHandlers
.add(handler
);
755 startReceiveThreadIfRequired();
760 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
762 private void startReceiveThreadIfRequired() {
763 if (receiveThread
!= null) {
766 receiveThread
= new Thread(() -> {
767 logger
.debug("Starting receiving messages");
768 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
769 synchronized (messageHandlers
) {
770 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
772 h
.handleMessage(envelope
, e
);
773 } catch (Throwable ex
) {
774 logger
.warn("Message handler failed, ignoring", ex
);
779 logger
.debug("Finished receiving messages");
780 synchronized (messageHandlers
) {
781 receiveThread
= null;
783 // Check if in the meantime another handler has been registered
784 if (!messageHandlers
.isEmpty()) {
785 logger
.debug("Another handler has been registered, starting receive thread again");
786 startReceiveThreadIfRequired();
790 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
792 receiveThread
.start();
796 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
798 synchronized (messageHandlers
) {
799 weakHandlers
.remove(handler
);
800 messageHandlers
.remove(handler
);
801 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
804 thread
= receiveThread
;
805 receiveThread
= null;
808 stopReceiveThread(thread
);
811 private void stopReceiveThread(final Thread thread
) {
812 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
813 logger
.debug("Receive stop requested, interrupting read from server.");
818 } catch (InterruptedException ignored
) {
823 public boolean isReceiving() {
824 if (isReceivingSynchronous
) {
827 synchronized (messageHandlers
) {
828 return messageHandlers
.size() > 0;
833 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
834 receiveMessages(timeout
, true, handler
);
838 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
839 receiveMessages(Duration
.ofMinutes(1), false, handler
);
842 private void receiveMessages(
843 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
844 ) throws IOException
{
846 throw new IllegalStateException("Already receiving message.");
848 isReceivingSynchronous
= true;
849 receiveThread
= Thread
.currentThread();
851 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
853 receiveThread
= null;
854 isReceivingSynchronous
= false;
859 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
860 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
864 public boolean hasCaughtUpWithOldMessages() {
865 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
869 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
870 final RecipientId recipientId
;
872 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
873 } catch (IOException
| UnregisteredRecipientException e
) {
876 return context
.getContactHelper().isContactBlocked(recipientId
);
880 public void sendContacts() throws IOException
{
881 context
.getSyncHelper().sendContacts();
885 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
886 return account
.getContactStore()
889 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
894 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
895 final RecipientId recipientId
;
897 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
898 } catch (IOException
| UnregisteredRecipientException e
) {
902 final var contact
= account
.getContactStore().getContact(recipientId
);
903 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
904 return contact
.getName();
907 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
908 if (profile
!= null) {
909 return profile
.getDisplayName();
916 public Group
getGroup(GroupId groupId
) {
917 return toGroup(context
.getGroupHelper().getGroup(groupId
));
921 public List
<Identity
> getIdentities() {
922 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
925 private Identity
toIdentity(final IdentityInfo identityInfo
) {
926 if (identityInfo
== null) {
930 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
931 final var scannableFingerprint
= context
.getIdentityHelper()
932 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
933 return new Identity(address
,
934 identityInfo
.getIdentityKey(),
935 context
.getIdentityHelper()
936 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
937 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
938 identityInfo
.getTrustLevel(),
939 identityInfo
.getDateAdded());
943 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
944 IdentityInfo identity
;
946 identity
= account
.getIdentityKeyStore()
947 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
948 } catch (IOException
| UnregisteredRecipientException e
) {
951 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
955 public boolean trustIdentityVerified(
956 RecipientIdentifier
.Single recipient
, byte[] fingerprint
957 ) throws UnregisteredRecipientException
{
958 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
962 public boolean trustIdentityVerifiedSafetyNumber(
963 RecipientIdentifier
.Single recipient
, String safetyNumber
964 ) throws UnregisteredRecipientException
{
965 return trustIdentity(recipient
,
966 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
970 public boolean trustIdentityVerifiedSafetyNumber(
971 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
972 ) throws UnregisteredRecipientException
{
973 return trustIdentity(recipient
,
974 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
978 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
979 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
982 private boolean trustIdentity(
983 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
984 ) throws UnregisteredRecipientException
{
985 RecipientId recipientId
;
987 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
988 } catch (IOException e
) {
991 final var updated
= trustMethod
.apply(recipientId
);
992 if (updated
&& this.isReceiving()) {
993 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
999 public void addAddressChangedListener(final Runnable listener
) {
1000 synchronized (addressChangedListeners
) {
1001 addressChangedListeners
.add(listener
);
1006 public void addClosedListener(final Runnable listener
) {
1007 synchronized (closedListeners
) {
1008 closedListeners
.add(listener
);
1013 public void close() {
1015 synchronized (messageHandlers
) {
1016 weakHandlers
.clear();
1017 messageHandlers
.clear();
1018 thread
= receiveThread
;
1019 receiveThread
= null;
1021 if (thread
!= null) {
1022 stopReceiveThread(thread
);
1024 executor
.shutdown();
1026 dependencies
.getSignalWebSocket().disconnect();
1027 disposable
.dispose();
1029 if (account
!= null) {
1033 synchronized (closedListeners
) {
1034 closedListeners
.forEach(Runnable
::run
);
1035 closedListeners
.clear();