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
.libsignal
.util
.guava
.Optional
;
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
.util
.DeviceNameUtil
;
71 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
72 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
73 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
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
.HashMap
;
83 import java
.util
.HashSet
;
84 import java
.util
.List
;
87 import java
.util
.UUID
;
88 import java
.util
.concurrent
.ExecutorService
;
89 import java
.util
.concurrent
.Executors
;
90 import java
.util
.concurrent
.atomic
.AtomicInteger
;
91 import java
.util
.concurrent
.locks
.ReentrantLock
;
92 import java
.util
.function
.Function
;
93 import java
.util
.stream
.Collectors
;
94 import java
.util
.stream
.Stream
;
96 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
98 class ManagerImpl
implements Manager
{
100 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
102 private SignalAccount account
;
103 private final AccountFileUpdater accountFileUpdater
;
104 private final SignalDependencies dependencies
;
105 private final Context context
;
107 private final ExecutorService executor
= Executors
.newCachedThreadPool();
109 private Thread receiveThread
;
110 private boolean isReceivingSynchronous
;
111 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
112 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
113 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
114 private final CompositeDisposable disposable
= new CompositeDisposable();
117 SignalAccount account
,
118 PathConfig pathConfig
,
119 AccountFileUpdater accountFileUpdater
,
120 ServiceEnvironmentConfig serviceEnvironmentConfig
,
123 this.account
= account
;
124 this.accountFileUpdater
= accountFileUpdater
;
126 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
128 account
.getPassword(),
129 account
.getDeviceId());
130 final var sessionLock
= new SignalSessionLock() {
131 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
134 public Lock
acquire() {
136 return LEGACY_LOCK
::unlock
;
139 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
142 account
.getSignalProtocolStore(),
145 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
146 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
147 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
149 this.context
= new Context(account
,
155 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
156 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
157 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
158 synchronized (this) {
162 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
163 logger
.trace("Archiving old sessions for {}", recipientId
);
164 account
.getSessionStore().archiveSessions(recipientId
);
165 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
166 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
167 if (profile
!= null) {
168 account
.getRecipientStore()
169 .storeProfile(recipientId
,
170 Profile
.newBuilder(profile
)
171 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
172 .withLastUpdateTimestamp(0)
179 public String
getSelfNumber() {
180 return account
.getNumber();
183 void checkAccountState() throws IOException
{
184 context
.getAccountHelper().checkAccountState();
188 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
189 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
191 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
192 if (!canonicalizedNumber
.equals(n
)) {
193 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
195 return canonicalizedNumber
;
196 } catch (InvalidNumberException e
) {
201 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
202 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
204 .filter(s
-> !s
.isEmpty())
205 .collect(Collectors
.toSet());
206 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
208 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
209 final var number
= canonicalizedNumbers
.get(n
);
210 final var aci
= registeredUsers
.get(number
);
211 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
216 public void updateAccountAttributes(String deviceName
) throws IOException
{
217 if (deviceName
!= null) {
218 context
.getAccountHelper().setDeviceName(deviceName
);
220 context
.getAccountHelper().updateAccountAttributes();
224 public Configuration
getConfiguration() {
225 final var configurationStore
= account
.getConfigurationStore();
226 return Configuration
.from(configurationStore
);
230 public void updateConfiguration(
231 Configuration configuration
232 ) throws NotMasterDeviceException
{
233 if (!account
.isMasterDevice()) {
234 throw new NotMasterDeviceException();
237 final var configurationStore
= account
.getConfigurationStore();
238 if (configuration
.readReceipts().isPresent()) {
239 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
241 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
242 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
244 if (configuration
.typingIndicators().isPresent()) {
245 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
247 if (configuration
.linkPreviews().isPresent()) {
248 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
250 context
.getSyncHelper().sendConfigurationMessage();
254 public void setProfile(
255 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
256 ) throws IOException
{
257 context
.getProfileHelper()
258 .setProfile(givenName
,
262 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
263 context
.getSyncHelper().sendSyncFetchProfileMessage();
267 public void unregister() throws IOException
{
268 context
.getAccountHelper().unregister();
272 public void deleteAccount() throws IOException
{
273 context
.getAccountHelper().deleteAccount();
277 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
278 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
280 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
284 public List
<Device
> getLinkedDevices() throws IOException
{
285 var devices
= dependencies
.getAccountManager().getDevices();
286 account
.setMultiDevice(devices
.size() > 1);
287 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
288 return devices
.stream().map(d
-> {
289 String deviceName
= d
.getName();
290 if (deviceName
!= null) {
292 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
293 } catch (IOException e
) {
294 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
297 return new Device(d
.getId(),
301 d
.getId() == account
.getDeviceId());
306 public void removeLinkedDevices(int deviceId
) throws IOException
{
307 context
.getAccountHelper().removeLinkedDevices(deviceId
);
311 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
312 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
313 context
.getAccountHelper().addDevice(deviceLinkInfo
);
317 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
318 if (!account
.isMasterDevice()) {
319 throw new NotMasterDeviceException();
321 if (pin
.isPresent()) {
322 context
.getAccountHelper().setRegistrationPin(pin
.get());
324 context
.getAccountHelper().removeRegistrationPin();
328 void refreshPreKeys() throws IOException
{
329 context
.getPreKeyHelper().refreshPreKeys();
333 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
334 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
338 public List
<Group
> getGroups() {
339 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
342 private Group
toGroup(final GroupInfo groupInfo
) {
343 if (groupInfo
== null) {
347 return Group
.from(groupInfo
,
348 account
.getRecipientStore()::resolveRecipientAddress
,
349 account
.getSelfRecipientId());
353 public SendGroupMessageResults
quitGroup(
354 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
355 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
356 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
357 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
361 public void deleteGroup(GroupId groupId
) throws IOException
{
362 context
.getGroupHelper().deleteGroup(groupId
);
366 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
367 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
368 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
369 return context
.getGroupHelper()
371 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
376 public SendGroupMessageResults
updateGroup(
377 final GroupId groupId
, final UpdateGroup updateGroup
378 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
379 return context
.getGroupHelper()
380 .updateGroup(groupId
,
381 updateGroup
.getName(),
382 updateGroup
.getDescription(),
383 updateGroup
.getMembers() == null
385 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
386 updateGroup
.getRemoveMembers() == null
388 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
389 updateGroup
.getAdmins() == null
391 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
392 updateGroup
.getRemoveAdmins() == null
394 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
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
.absent());
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())));
545 if (message
.sticker().isPresent()) {
546 final var sticker
= message
.sticker().get();
547 final var packId
= StickerPackId
.deserialize(sticker
.packId());
548 final var stickerId
= sticker
.stickerId();
550 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
551 if (stickerPack
== null) {
552 throw new InvalidStickerException("Sticker pack not found");
554 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
555 if (manifest
.stickers().size() <= stickerId
) {
556 throw new InvalidStickerException("Sticker id not part of this pack");
558 final var manifestSticker
= manifest
.stickers().get(stickerId
);
559 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
560 if (streamDetails
== null) {
561 throw new InvalidStickerException("Missing local sticker file");
563 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
564 stickerPack
.getPackKey(),
566 manifestSticker
.emoji(),
567 AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent())));
571 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
572 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
573 for (final var m
: mentionList
) {
574 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
575 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
576 .resolveSignalServiceAddress(recipientId
)
577 .getAci(), m
.start(), m
.length()));
583 public SendMessageResults
sendRemoteDeleteMessage(
584 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
585 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
586 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
587 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
588 for (final var recipient
: recipients
) {
589 if (recipient
instanceof RecipientIdentifier
.Single r
) {
591 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
592 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
593 } catch (UnregisteredRecipientException ignored
) {
595 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
596 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
599 return sendMessage(messageBuilder
, recipients
);
603 public SendMessageResults
sendMessageReaction(
606 RecipientIdentifier
.Single targetAuthor
,
607 long targetSentTimestamp
,
608 Set
<RecipientIdentifier
> recipients
609 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
610 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
611 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
613 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
614 targetSentTimestamp
);
615 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
616 return sendMessage(messageBuilder
, recipients
);
620 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
621 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
624 return sendMessage(messageBuilder
,
625 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
626 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
627 throw new AssertionError(e
);
629 for (var recipient
: recipients
) {
630 final RecipientId recipientId
;
632 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
633 } catch (UnregisteredRecipientException e
) {
636 account
.getSessionStore().deleteAllSessions(recipientId
);
642 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
643 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
647 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
648 account
.getContactStore()
649 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
653 public void setContactName(
654 RecipientIdentifier
.Single recipient
, String name
655 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
656 if (!account
.isMasterDevice()) {
657 throw new NotMasterDeviceException();
659 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
663 public void setContactBlocked(
664 RecipientIdentifier
.Single recipient
, boolean blocked
665 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
666 if (!account
.isMasterDevice()) {
667 throw new NotMasterDeviceException();
669 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
670 // TODO cycle our profile key, if we're not together in a group with recipient
671 context
.getSyncHelper().sendBlockedList();
675 public void setGroupBlocked(
676 final GroupId groupId
, final boolean blocked
677 ) throws GroupNotFoundException
, NotMasterDeviceException
{
678 if (!account
.isMasterDevice()) {
679 throw new NotMasterDeviceException();
681 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
682 // TODO cycle our profile key
683 context
.getSyncHelper().sendBlockedList();
687 public void setExpirationTimer(
688 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
689 ) throws IOException
, UnregisteredRecipientException
{
690 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
691 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
692 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
694 sendMessage(messageBuilder
, Set
.of(recipient
));
695 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
696 throw new AssertionError(e
);
701 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
702 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
704 var messageSender
= dependencies
.getMessageSender();
706 var packKey
= KeyUtils
.createStickerUploadKey();
707 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
708 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
710 var sticker
= new Sticker(packId
, packKey
);
711 account
.getStickerStore().updateSticker(sticker
);
713 return new StickerPackUrl(packId
, packKey
);
717 public List
<StickerPack
> getStickerPacks() {
718 final var stickerPackStore
= context
.getStickerPackStore();
719 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
720 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
722 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
723 return new StickerPack(pack
.getPackId(),
724 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
728 java
.util
.Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
729 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
730 } catch (Exception e
) {
731 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
735 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
740 public void requestAllSyncData() throws IOException
{
741 context
.getSyncHelper().requestAllSyncData();
742 retrieveRemoteStorage();
745 void retrieveRemoteStorage() throws IOException
{
746 if (account
.getStorageKey() != null) {
747 context
.getStorageHelper().readDataFromStorage();
752 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
753 if (isReceivingSynchronous
) {
754 throw new IllegalStateException("Already receiving message synchronously.");
756 synchronized (messageHandlers
) {
757 if (isWeakListener
) {
758 weakHandlers
.add(handler
);
760 messageHandlers
.add(handler
);
761 startReceiveThreadIfRequired();
766 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
768 private void startReceiveThreadIfRequired() {
769 if (receiveThread
!= null) {
772 receiveThread
= new Thread(() -> {
773 logger
.debug("Starting receiving messages");
774 while (!Thread
.interrupted()) {
776 context
.getReceiveHelper().receiveMessages(Duration
.ofMinutes(1), false, (envelope
, e
) -> {
777 synchronized (messageHandlers
) {
778 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
780 h
.handleMessage(envelope
, e
);
781 } catch (Exception ex
) {
782 logger
.warn("Message handler failed, ignoring", ex
);
788 } catch (IOException e
) {
789 logger
.warn("Receiving messages failed, retrying", e
);
792 logger
.debug("Finished receiving messages");
793 synchronized (messageHandlers
) {
794 receiveThread
= null;
796 // Check if in the meantime another handler has been registered
797 if (!messageHandlers
.isEmpty()) {
798 logger
.debug("Another handler has been registered, starting receive thread again");
799 startReceiveThreadIfRequired();
803 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
805 receiveThread
.start();
809 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
811 synchronized (messageHandlers
) {
812 weakHandlers
.remove(handler
);
813 messageHandlers
.remove(handler
);
814 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
817 thread
= receiveThread
;
818 receiveThread
= null;
821 stopReceiveThread(thread
);
824 private void stopReceiveThread(final Thread thread
) {
828 } catch (InterruptedException ignored
) {
833 public boolean isReceiving() {
834 if (isReceivingSynchronous
) {
837 synchronized (messageHandlers
) {
838 return messageHandlers
.size() > 0;
843 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
844 receiveMessages(timeout
, true, handler
);
848 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
849 receiveMessages(Duration
.ofMinutes(1), false, handler
);
852 private void receiveMessages(
853 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
854 ) throws IOException
{
856 throw new IllegalStateException("Already receiving message.");
858 isReceivingSynchronous
= true;
859 receiveThread
= Thread
.currentThread();
861 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
863 receiveThread
= null;
864 isReceivingSynchronous
= false;
869 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
870 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
874 public boolean hasCaughtUpWithOldMessages() {
875 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
879 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
880 final RecipientId recipientId
;
882 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
883 } catch (IOException
| UnregisteredRecipientException e
) {
886 return context
.getContactHelper().isContactBlocked(recipientId
);
890 public void sendContacts() throws IOException
{
891 context
.getSyncHelper().sendContacts();
895 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
896 return account
.getContactStore()
899 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
904 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
905 final RecipientId recipientId
;
907 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
908 } catch (IOException
| UnregisteredRecipientException e
) {
912 final var contact
= account
.getContactStore().getContact(recipientId
);
913 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
914 return contact
.getName();
917 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
918 if (profile
!= null) {
919 return profile
.getDisplayName();
926 public Group
getGroup(GroupId groupId
) {
927 return toGroup(context
.getGroupHelper().getGroup(groupId
));
931 public List
<Identity
> getIdentities() {
932 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
935 private Identity
toIdentity(final IdentityInfo identityInfo
) {
936 if (identityInfo
== null) {
940 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
941 final var scannableFingerprint
= context
.getIdentityHelper()
942 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
943 return new Identity(address
,
944 identityInfo
.getIdentityKey(),
945 context
.getIdentityHelper()
946 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
947 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
948 identityInfo
.getTrustLevel(),
949 identityInfo
.getDateAdded());
953 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
954 IdentityInfo identity
;
956 identity
= account
.getIdentityKeyStore()
957 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
958 } catch (IOException
| UnregisteredRecipientException e
) {
961 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
965 public boolean trustIdentityVerified(
966 RecipientIdentifier
.Single recipient
, byte[] fingerprint
967 ) throws UnregisteredRecipientException
{
968 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
972 public boolean trustIdentityVerifiedSafetyNumber(
973 RecipientIdentifier
.Single recipient
, String safetyNumber
974 ) throws UnregisteredRecipientException
{
975 return trustIdentity(recipient
,
976 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
980 public boolean trustIdentityVerifiedSafetyNumber(
981 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
982 ) throws UnregisteredRecipientException
{
983 return trustIdentity(recipient
,
984 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
988 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
989 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
992 private boolean trustIdentity(
993 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
994 ) throws UnregisteredRecipientException
{
995 RecipientId recipientId
;
997 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
998 } catch (IOException e
) {
1001 final var updated
= trustMethod
.apply(recipientId
);
1002 if (updated
&& this.isReceiving()) {
1003 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1009 public void addClosedListener(final Runnable listener
) {
1010 synchronized (closedListeners
) {
1011 closedListeners
.add(listener
);
1016 public void close() {
1018 synchronized (messageHandlers
) {
1019 weakHandlers
.clear();
1020 messageHandlers
.clear();
1021 thread
= receiveThread
;
1022 receiveThread
= null;
1024 if (thread
!= null) {
1025 stopReceiveThread(thread
);
1027 executor
.shutdown();
1029 dependencies
.getSignalWebSocket().disconnect();
1030 disposable
.dispose();
1032 synchronized (closedListeners
) {
1033 closedListeners
.forEach(Runnable
::run
);
1034 closedListeners
.clear();
1037 if (account
!= null) {