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
.getBanMembers() == null
391 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
392 updateGroup
.getUnbanMembers() == null
394 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
395 updateGroup
.isResetGroupLink(),
396 updateGroup
.getGroupLinkState(),
397 updateGroup
.getAddMemberPermission(),
398 updateGroup
.getEditDetailsPermission(),
399 updateGroup
.getAvatarFile(),
400 updateGroup
.getExpirationTimer(),
401 updateGroup
.getIsAnnouncementGroup());
405 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
406 GroupInviteLinkUrl inviteLinkUrl
407 ) throws IOException
, InactiveGroupLinkException
{
408 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
411 private SendMessageResults
sendMessage(
412 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
413 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
414 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
415 long timestamp
= System
.currentTimeMillis();
416 messageBuilder
.withTimestamp(timestamp
);
417 for (final var recipient
: recipients
) {
418 if (recipient
instanceof RecipientIdentifier
.Single single
) {
420 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
421 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
422 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
423 } catch (UnregisteredRecipientException e
) {
424 results
.put(recipient
,
425 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
427 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
428 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
429 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
430 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
431 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
432 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
435 return new SendMessageResults(timestamp
, results
);
438 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
439 return SendMessageResult
.from(result
,
440 account
.getRecipientStore(),
441 account
.getRecipientStore()::resolveRecipientAddress
);
444 private SendMessageResults
sendTypingMessage(
445 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
446 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
447 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
448 final var timestamp
= System
.currentTimeMillis();
449 for (var recipient
: recipients
) {
450 if (recipient
instanceof RecipientIdentifier
.Single single
) {
451 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
453 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
454 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
455 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
456 } catch (UnregisteredRecipientException e
) {
457 results
.put(recipient
,
458 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
460 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
461 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
462 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
463 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
464 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
467 return new SendMessageResults(timestamp
, results
);
471 public SendMessageResults
sendTypingMessage(
472 TypingAction action
, Set
<RecipientIdentifier
> recipients
473 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
474 return sendTypingMessage(action
.toSignalService(), recipients
);
478 public SendMessageResults
sendReadReceipt(
479 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
480 ) throws IOException
{
481 final var timestamp
= System
.currentTimeMillis();
482 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
486 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
490 public SendMessageResults
sendViewedReceipt(
491 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
492 ) throws IOException
{
493 final var timestamp
= System
.currentTimeMillis();
494 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
498 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
501 private SendMessageResults
sendReceiptMessage(
502 final RecipientIdentifier
.Single sender
,
503 final long timestamp
,
504 final SignalServiceReceiptMessage receiptMessage
505 ) throws IOException
{
507 final var result
= context
.getSendHelper()
508 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
509 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
510 } catch (UnregisteredRecipientException e
) {
511 return new SendMessageResults(timestamp
,
512 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
517 public SendMessageResults
sendMessage(
518 Message message
, Set
<RecipientIdentifier
> recipients
519 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
520 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
521 applyMessage(messageBuilder
, message
);
522 return sendMessage(messageBuilder
, recipients
);
525 private void applyMessage(
526 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
527 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
528 messageBuilder
.withBody(message
.messageText());
529 final var attachments
= message
.attachments();
530 if (attachments
!= null) {
531 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
533 if (message
.mentions().size() > 0) {
534 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
536 if (message
.quote().isPresent()) {
537 final var quote
= message
.quote().get();
538 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
539 context
.getRecipientHelper()
540 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
543 resolveMentions(quote
.mentions()),
544 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
546 if (message
.sticker().isPresent()) {
547 final var sticker
= message
.sticker().get();
548 final var packId
= StickerPackId
.deserialize(sticker
.packId());
549 final var stickerId
= sticker
.stickerId();
551 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
552 if (stickerPack
== null) {
553 throw new InvalidStickerException("Sticker pack not found");
555 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
556 if (manifest
.stickers().size() <= stickerId
) {
557 throw new InvalidStickerException("Sticker id not part of this pack");
559 final var manifestSticker
= manifest
.stickers().get(stickerId
);
560 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
561 if (streamDetails
== null) {
562 throw new InvalidStickerException("Missing local sticker file");
564 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
565 stickerPack
.getPackKey(),
567 manifestSticker
.emoji(),
568 AttachmentUtils
.createAttachment(streamDetails
, Optional
.empty())));
572 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
573 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
574 for (final var m
: mentionList
) {
575 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
576 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
577 .resolveSignalServiceAddress(recipientId
)
578 .getServiceId(), m
.start(), m
.length()));
584 public SendMessageResults
sendRemoteDeleteMessage(
585 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
586 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
587 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
588 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
589 for (final var recipient
: recipients
) {
590 if (recipient
instanceof RecipientIdentifier
.Single r
) {
592 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
593 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
594 } catch (UnregisteredRecipientException ignored
) {
596 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
597 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
600 return sendMessage(messageBuilder
, recipients
);
604 public SendMessageResults
sendMessageReaction(
607 RecipientIdentifier
.Single targetAuthor
,
608 long targetSentTimestamp
,
609 Set
<RecipientIdentifier
> recipients
610 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
611 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
612 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
614 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
615 targetSentTimestamp
);
616 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
617 return sendMessage(messageBuilder
, recipients
);
621 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
622 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
625 return sendMessage(messageBuilder
,
626 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
627 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
628 throw new AssertionError(e
);
630 for (var recipient
: recipients
) {
631 final RecipientId recipientId
;
633 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
634 } catch (UnregisteredRecipientException e
) {
637 account
.getSessionStore().deleteAllSessions(recipientId
);
643 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
644 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
648 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
649 account
.getContactStore()
650 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
654 public void setContactName(
655 RecipientIdentifier
.Single recipient
, String name
656 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
657 if (!account
.isMasterDevice()) {
658 throw new NotMasterDeviceException();
660 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
664 public void setContactBlocked(
665 RecipientIdentifier
.Single recipient
, boolean blocked
666 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
667 if (!account
.isMasterDevice()) {
668 throw new NotMasterDeviceException();
670 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
671 // TODO cycle our profile key, if we're not together in a group with recipient
672 context
.getSyncHelper().sendBlockedList();
676 public void setGroupBlocked(
677 final GroupId groupId
, final boolean blocked
678 ) throws GroupNotFoundException
, NotMasterDeviceException
{
679 if (!account
.isMasterDevice()) {
680 throw new NotMasterDeviceException();
682 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
683 // TODO cycle our profile key
684 context
.getSyncHelper().sendBlockedList();
688 public void setExpirationTimer(
689 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
690 ) throws IOException
, UnregisteredRecipientException
{
691 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
692 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
693 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
695 sendMessage(messageBuilder
, Set
.of(recipient
));
696 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
697 throw new AssertionError(e
);
702 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
703 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
705 var messageSender
= dependencies
.getMessageSender();
707 var packKey
= KeyUtils
.createStickerUploadKey();
708 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
709 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
711 var sticker
= new Sticker(packId
, packKey
);
712 account
.getStickerStore().updateSticker(sticker
);
714 return new StickerPackUrl(packId
, packKey
);
718 public List
<StickerPack
> getStickerPacks() {
719 final var stickerPackStore
= context
.getStickerPackStore();
720 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
721 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
723 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
724 return new StickerPack(pack
.getPackId(),
725 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
729 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
730 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
731 } catch (Exception e
) {
732 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
736 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
741 public void requestAllSyncData() throws IOException
{
742 context
.getSyncHelper().requestAllSyncData();
743 retrieveRemoteStorage();
746 void retrieveRemoteStorage() throws IOException
{
747 if (account
.getStorageKey() != null) {
748 context
.getStorageHelper().readDataFromStorage();
753 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
754 if (isReceivingSynchronous
) {
755 throw new IllegalStateException("Already receiving message synchronously.");
757 synchronized (messageHandlers
) {
758 if (isWeakListener
) {
759 weakHandlers
.add(handler
);
761 messageHandlers
.add(handler
);
762 startReceiveThreadIfRequired();
767 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
769 private void startReceiveThreadIfRequired() {
770 if (receiveThread
!= null) {
773 receiveThread
= new Thread(() -> {
774 logger
.debug("Starting receiving messages");
775 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
776 synchronized (messageHandlers
) {
777 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
779 h
.handleMessage(envelope
, e
);
780 } catch (Throwable ex
) {
781 logger
.warn("Message handler failed, ignoring", ex
);
786 logger
.debug("Finished receiving messages");
787 synchronized (messageHandlers
) {
788 receiveThread
= null;
790 // Check if in the meantime another handler has been registered
791 if (!messageHandlers
.isEmpty()) {
792 logger
.debug("Another handler has been registered, starting receive thread again");
793 startReceiveThreadIfRequired();
797 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
799 receiveThread
.start();
803 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
805 synchronized (messageHandlers
) {
806 weakHandlers
.remove(handler
);
807 messageHandlers
.remove(handler
);
808 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
811 thread
= receiveThread
;
812 receiveThread
= null;
815 stopReceiveThread(thread
);
818 private void stopReceiveThread(final Thread thread
) {
819 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
820 logger
.debug("Receive stop requested, interrupting read from server.");
825 } catch (InterruptedException ignored
) {
830 public boolean isReceiving() {
831 if (isReceivingSynchronous
) {
834 synchronized (messageHandlers
) {
835 return messageHandlers
.size() > 0;
840 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
841 receiveMessages(timeout
, true, handler
);
845 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
846 receiveMessages(Duration
.ofMinutes(1), false, handler
);
849 private void receiveMessages(
850 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
851 ) throws IOException
{
853 throw new IllegalStateException("Already receiving message.");
855 isReceivingSynchronous
= true;
856 receiveThread
= Thread
.currentThread();
858 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
860 receiveThread
= null;
861 isReceivingSynchronous
= false;
866 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
867 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
871 public boolean hasCaughtUpWithOldMessages() {
872 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
876 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
877 final RecipientId recipientId
;
879 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
880 } catch (IOException
| UnregisteredRecipientException e
) {
883 return context
.getContactHelper().isContactBlocked(recipientId
);
887 public void sendContacts() throws IOException
{
888 context
.getSyncHelper().sendContacts();
892 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
893 return account
.getContactStore()
896 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
901 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
902 final RecipientId recipientId
;
904 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
905 } catch (IOException
| UnregisteredRecipientException e
) {
909 final var contact
= account
.getContactStore().getContact(recipientId
);
910 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
911 return contact
.getName();
914 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
915 if (profile
!= null) {
916 return profile
.getDisplayName();
923 public Group
getGroup(GroupId groupId
) {
924 return toGroup(context
.getGroupHelper().getGroup(groupId
));
928 public List
<Identity
> getIdentities() {
929 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
932 private Identity
toIdentity(final IdentityInfo identityInfo
) {
933 if (identityInfo
== null) {
937 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
938 final var scannableFingerprint
= context
.getIdentityHelper()
939 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
940 return new Identity(address
,
941 identityInfo
.getIdentityKey(),
942 context
.getIdentityHelper()
943 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
944 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
945 identityInfo
.getTrustLevel(),
946 identityInfo
.getDateAdded());
950 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
951 IdentityInfo identity
;
953 identity
= account
.getIdentityKeyStore()
954 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
955 } catch (IOException
| UnregisteredRecipientException e
) {
958 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
962 public boolean trustIdentityVerified(
963 RecipientIdentifier
.Single recipient
, byte[] fingerprint
964 ) throws UnregisteredRecipientException
{
965 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
969 public boolean trustIdentityVerifiedSafetyNumber(
970 RecipientIdentifier
.Single recipient
, String safetyNumber
971 ) throws UnregisteredRecipientException
{
972 return trustIdentity(recipient
,
973 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
977 public boolean trustIdentityVerifiedSafetyNumber(
978 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
979 ) throws UnregisteredRecipientException
{
980 return trustIdentity(recipient
,
981 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
985 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
986 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
989 private boolean trustIdentity(
990 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
991 ) throws UnregisteredRecipientException
{
992 RecipientId recipientId
;
994 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
995 } catch (IOException e
) {
998 final var updated
= trustMethod
.apply(recipientId
);
999 if (updated
&& this.isReceiving()) {
1000 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1006 public void addAddressChangedListener(final Runnable listener
) {
1007 synchronized (addressChangedListeners
) {
1008 addressChangedListeners
.add(listener
);
1013 public void addClosedListener(final Runnable listener
) {
1014 synchronized (closedListeners
) {
1015 closedListeners
.add(listener
);
1020 public void close() {
1022 synchronized (messageHandlers
) {
1023 weakHandlers
.clear();
1024 messageHandlers
.clear();
1025 thread
= receiveThread
;
1026 receiveThread
= null;
1028 if (thread
!= null) {
1029 stopReceiveThread(thread
);
1031 executor
.shutdown();
1033 dependencies
.getSignalWebSocket().disconnect();
1034 disposable
.dispose();
1036 if (account
!= null) {
1040 synchronized (closedListeners
) {
1041 closedListeners
.forEach(Runnable
::run
);
1042 closedListeners
.clear();