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
.Configuration
;
20 import org
.asamk
.signal
.manager
.api
.Device
;
21 import org
.asamk
.signal
.manager
.api
.Group
;
22 import org
.asamk
.signal
.manager
.api
.Identity
;
23 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
24 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
25 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
26 import org
.asamk
.signal
.manager
.api
.Message
;
27 import org
.asamk
.signal
.manager
.api
.Pair
;
28 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
29 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
30 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
31 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
32 import org
.asamk
.signal
.manager
.api
.StickerPack
;
33 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
34 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
35 import org
.asamk
.signal
.manager
.api
.TypingAction
;
36 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
37 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
38 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
39 import org
.asamk
.signal
.manager
.groups
.GroupId
;
40 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
41 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
42 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
43 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
44 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
45 import org
.asamk
.signal
.manager
.helper
.Context
;
46 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
47 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
48 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
49 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
50 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
51 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
52 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
53 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
54 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
55 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
56 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
57 import org
.slf4j
.Logger
;
58 import org
.slf4j
.LoggerFactory
;
59 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
60 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
61 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
62 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
63 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
64 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
65 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
66 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
67 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
68 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
69 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
72 import java
.io
.IOException
;
74 import java
.time
.Duration
;
75 import java
.util
.ArrayList
;
76 import java
.util
.HashMap
;
77 import java
.util
.HashSet
;
78 import java
.util
.List
;
81 import java
.util
.UUID
;
82 import java
.util
.concurrent
.ExecutorService
;
83 import java
.util
.concurrent
.Executors
;
84 import java
.util
.concurrent
.locks
.ReentrantLock
;
85 import java
.util
.function
.Function
;
86 import java
.util
.stream
.Collectors
;
87 import java
.util
.stream
.Stream
;
89 public class ManagerImpl
implements Manager
{
91 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
93 private SignalAccount account
;
94 private final SignalDependencies dependencies
;
95 private final Context context
;
97 private final ExecutorService executor
= Executors
.newCachedThreadPool();
99 private Thread receiveThread
;
100 private boolean isReceivingSynchronous
;
101 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
102 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
103 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
106 SignalAccount account
,
107 PathConfig pathConfig
,
108 ServiceEnvironmentConfig serviceEnvironmentConfig
,
111 this.account
= account
;
113 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
114 account
.getAccount(),
115 account
.getPassword(),
116 account
.getDeviceId());
117 final var sessionLock
= new SignalSessionLock() {
118 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
121 public Lock
acquire() {
123 return LEGACY_LOCK
::unlock
;
126 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
129 account
.getSignalProtocolStore(),
132 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
133 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
134 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
136 this.context
= new Context(account
, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
137 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
138 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
139 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
140 synchronized (this) {
147 public String
getSelfNumber() {
148 return account
.getAccount();
152 public void checkAccountState() throws IOException
{
153 context
.getAccountHelper().checkAccountState();
157 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
158 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
160 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getAccount());
161 if (!canonicalizedNumber
.equals(n
)) {
162 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
164 return canonicalizedNumber
;
165 } catch (InvalidNumberException e
) {
170 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
171 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
173 .filter(s
-> !s
.isEmpty())
174 .collect(Collectors
.toSet());
175 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
177 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
178 final var number
= canonicalizedNumbers
.get(n
);
179 final var aci
= registeredUsers
.get(number
);
180 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
185 public void updateAccountAttributes(String deviceName
) throws IOException
{
186 if (deviceName
!= null) {
187 context
.getAccountHelper().setDeviceName(deviceName
);
189 context
.getAccountHelper().updateAccountAttributes();
193 public Configuration
getConfiguration() {
194 final var configurationStore
= account
.getConfigurationStore();
195 return Configuration
.from(configurationStore
);
199 public void updateConfiguration(
200 Configuration configuration
201 ) throws NotMasterDeviceException
{
202 if (!account
.isMasterDevice()) {
203 throw new NotMasterDeviceException();
206 final var configurationStore
= account
.getConfigurationStore();
207 if (configuration
.readReceipts().isPresent()) {
208 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
210 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
211 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
213 if (configuration
.typingIndicators().isPresent()) {
214 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
216 if (configuration
.linkPreviews().isPresent()) {
217 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
219 context
.getSyncHelper().sendConfigurationMessage();
223 public void setProfile(
224 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
225 ) throws IOException
{
226 context
.getProfileHelper()
227 .setProfile(givenName
,
231 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
232 context
.getSyncHelper().sendSyncFetchProfileMessage();
236 public void unregister() throws IOException
{
237 context
.getAccountHelper().unregister();
241 public void deleteAccount() throws IOException
{
242 context
.getAccountHelper().deleteAccount();
246 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
247 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
249 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
253 public List
<Device
> getLinkedDevices() throws IOException
{
254 var devices
= dependencies
.getAccountManager().getDevices();
255 account
.setMultiDevice(devices
.size() > 1);
256 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
257 return devices
.stream().map(d
-> {
258 String deviceName
= d
.getName();
259 if (deviceName
!= null) {
261 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
262 } catch (IOException e
) {
263 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
266 return new Device(d
.getId(),
270 d
.getId() == account
.getDeviceId());
275 public void removeLinkedDevices(long deviceId
) throws IOException
{
276 context
.getAccountHelper().removeLinkedDevices(deviceId
);
280 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
281 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
282 context
.getAccountHelper().addDevice(deviceLinkInfo
);
286 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
287 if (!account
.isMasterDevice()) {
288 throw new NotMasterDeviceException();
290 if (pin
.isPresent()) {
291 context
.getAccountHelper().setRegistrationPin(pin
.get());
293 context
.getAccountHelper().removeRegistrationPin();
297 void refreshPreKeys() throws IOException
{
298 context
.getPreKeyHelper().refreshPreKeys();
302 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
303 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
307 public List
<Group
> getGroups() {
308 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
311 private Group
toGroup(final GroupInfo groupInfo
) {
312 if (groupInfo
== null) {
316 return Group
.from(groupInfo
,
317 account
.getRecipientStore()::resolveRecipientAddress
,
318 account
.getSelfRecipientId());
322 public SendGroupMessageResults
quitGroup(
323 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
324 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
325 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
326 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
330 public void deleteGroup(GroupId groupId
) throws IOException
{
331 context
.getGroupHelper().deleteGroup(groupId
);
335 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
336 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
337 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
338 return context
.getGroupHelper()
340 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
345 public SendGroupMessageResults
updateGroup(
346 final GroupId groupId
, final UpdateGroup updateGroup
347 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
348 return context
.getGroupHelper()
349 .updateGroup(groupId
,
350 updateGroup
.getName(),
351 updateGroup
.getDescription(),
352 updateGroup
.getMembers() == null
354 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
355 updateGroup
.getRemoveMembers() == null
357 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
358 updateGroup
.getAdmins() == null
360 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
361 updateGroup
.getRemoveAdmins() == null
363 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
364 updateGroup
.isResetGroupLink(),
365 updateGroup
.getGroupLinkState(),
366 updateGroup
.getAddMemberPermission(),
367 updateGroup
.getEditDetailsPermission(),
368 updateGroup
.getAvatarFile(),
369 updateGroup
.getExpirationTimer(),
370 updateGroup
.getIsAnnouncementGroup());
374 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
375 GroupInviteLinkUrl inviteLinkUrl
376 ) throws IOException
, InactiveGroupLinkException
{
377 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
380 private SendMessageResults
sendMessage(
381 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
382 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
383 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
384 long timestamp
= System
.currentTimeMillis();
385 messageBuilder
.withTimestamp(timestamp
);
386 for (final var recipient
: recipients
) {
387 if (recipient
instanceof RecipientIdentifier
.Single single
) {
389 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
390 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
391 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
392 } catch (UnregisteredRecipientException e
) {
393 results
.put(recipient
,
394 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
396 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
397 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
398 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
399 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
400 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
401 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
404 return new SendMessageResults(timestamp
, results
);
407 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
408 return SendMessageResult
.from(result
,
409 account
.getRecipientStore(),
410 account
.getRecipientStore()::resolveRecipientAddress
);
413 private SendMessageResults
sendTypingMessage(
414 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
415 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
416 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
417 final var timestamp
= System
.currentTimeMillis();
418 for (var recipient
: recipients
) {
419 if (recipient
instanceof RecipientIdentifier
.Single single
) {
420 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
422 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
423 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
424 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
425 } catch (UnregisteredRecipientException e
) {
426 results
.put(recipient
,
427 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
429 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
430 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
431 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
432 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
433 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
436 return new SendMessageResults(timestamp
, results
);
440 public SendMessageResults
sendTypingMessage(
441 TypingAction action
, Set
<RecipientIdentifier
> recipients
442 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
443 return sendTypingMessage(action
.toSignalService(), recipients
);
447 public SendMessageResults
sendReadReceipt(
448 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
449 ) throws IOException
{
450 final var timestamp
= System
.currentTimeMillis();
451 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
455 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
459 public SendMessageResults
sendViewedReceipt(
460 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
461 ) throws IOException
{
462 final var timestamp
= System
.currentTimeMillis();
463 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
467 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
470 private SendMessageResults
sendReceiptMessage(
471 final RecipientIdentifier
.Single sender
,
472 final long timestamp
,
473 final SignalServiceReceiptMessage receiptMessage
474 ) throws IOException
{
476 final var result
= context
.getSendHelper()
477 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
478 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
479 } catch (UnregisteredRecipientException e
) {
480 return new SendMessageResults(timestamp
,
481 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
486 public SendMessageResults
sendMessage(
487 Message message
, Set
<RecipientIdentifier
> recipients
488 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
489 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
490 applyMessage(messageBuilder
, message
);
491 return sendMessage(messageBuilder
, recipients
);
494 private void applyMessage(
495 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
496 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
497 messageBuilder
.withBody(message
.messageText());
498 final var attachments
= message
.attachments();
499 if (attachments
!= null) {
500 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
502 if (message
.mentions().size() > 0) {
503 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
505 if (message
.quote().isPresent()) {
506 final var quote
= message
.quote().get();
507 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
508 context
.getRecipientHelper()
509 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
512 resolveMentions(quote
.mentions())));
514 if (message
.sticker().isPresent()) {
515 final var sticker
= message
.sticker().get();
516 final var packId
= StickerPackId
.deserialize(sticker
.packId());
517 final var stickerId
= sticker
.stickerId();
519 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
520 if (stickerPack
== null) {
521 throw new InvalidStickerException("Sticker pack not found");
523 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
524 if (manifest
.stickers().size() <= stickerId
) {
525 throw new InvalidStickerException("Sticker id not part of this pack");
527 final var manifestSticker
= manifest
.stickers().get(stickerId
);
528 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
529 if (streamDetails
== null) {
530 throw new InvalidStickerException("Missing local sticker file");
532 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
533 stickerPack
.getPackKey(),
535 manifestSticker
.emoji(),
536 AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent())));
540 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
541 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
542 for (final var m
: mentionList
) {
543 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
544 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
545 .resolveSignalServiceAddress(recipientId
)
546 .getAci(), m
.start(), m
.length()));
552 public SendMessageResults
sendRemoteDeleteMessage(
553 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
554 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
555 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
556 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
557 return sendMessage(messageBuilder
, recipients
);
561 public SendMessageResults
sendMessageReaction(
564 RecipientIdentifier
.Single targetAuthor
,
565 long targetSentTimestamp
,
566 Set
<RecipientIdentifier
> recipients
567 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
568 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
569 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
571 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
572 targetSentTimestamp
);
573 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
574 return sendMessage(messageBuilder
, recipients
);
578 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
579 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
582 return sendMessage(messageBuilder
,
583 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
584 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
585 throw new AssertionError(e
);
587 for (var recipient
: recipients
) {
588 final RecipientId recipientId
;
590 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
591 } catch (UnregisteredRecipientException e
) {
594 account
.getSessionStore().deleteAllSessions(recipientId
);
600 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
601 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
605 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
606 account
.getContactStore()
607 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
611 public void setContactName(
612 RecipientIdentifier
.Single recipient
, String name
613 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
614 if (!account
.isMasterDevice()) {
615 throw new NotMasterDeviceException();
617 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
621 public void setContactBlocked(
622 RecipientIdentifier
.Single recipient
, boolean blocked
623 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
624 if (!account
.isMasterDevice()) {
625 throw new NotMasterDeviceException();
627 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
628 // TODO cycle our profile key, if we're not together in a group with recipient
629 context
.getSyncHelper().sendBlockedList();
633 public void setGroupBlocked(
634 final GroupId groupId
, final boolean blocked
635 ) throws GroupNotFoundException
, NotMasterDeviceException
{
636 if (!account
.isMasterDevice()) {
637 throw new NotMasterDeviceException();
639 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
640 // TODO cycle our profile key
641 context
.getSyncHelper().sendBlockedList();
645 public void setExpirationTimer(
646 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
647 ) throws IOException
, UnregisteredRecipientException
{
648 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
649 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
650 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
652 sendMessage(messageBuilder
, Set
.of(recipient
));
653 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
654 throw new AssertionError(e
);
659 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
660 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
662 var messageSender
= dependencies
.getMessageSender();
664 var packKey
= KeyUtils
.createStickerUploadKey();
665 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
666 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
668 var sticker
= new Sticker(packId
, packKey
);
669 account
.getStickerStore().updateSticker(sticker
);
671 return new StickerPackUrl(packId
, packKey
);
675 public List
<StickerPack
> getStickerPacks() {
676 final var stickerPackStore
= context
.getStickerPackStore();
677 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
678 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
680 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
681 return new StickerPack(pack
.getPackId(),
682 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
686 java
.util
.Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
687 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
688 } catch (Exception e
) {
689 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
693 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
698 public void requestAllSyncData() throws IOException
{
699 context
.getSyncHelper().requestAllSyncData();
700 retrieveRemoteStorage();
703 void retrieveRemoteStorage() throws IOException
{
704 if (account
.getStorageKey() != null) {
705 context
.getStorageHelper().readDataFromStorage();
710 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
711 if (isReceivingSynchronous
) {
712 throw new IllegalStateException("Already receiving message synchronously.");
714 synchronized (messageHandlers
) {
715 if (isWeakListener
) {
716 weakHandlers
.add(handler
);
718 messageHandlers
.add(handler
);
719 startReceiveThreadIfRequired();
724 private void startReceiveThreadIfRequired() {
725 if (receiveThread
!= null) {
728 receiveThread
= new Thread(() -> {
729 logger
.debug("Starting receiving messages");
730 while (!Thread
.interrupted()) {
732 context
.getReceiveHelper().receiveMessages(Duration
.ofMinutes(1), false, (envelope
, e
) -> {
733 synchronized (messageHandlers
) {
734 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
736 h
.handleMessage(envelope
, e
);
737 } catch (Exception ex
) {
738 logger
.warn("Message handler failed, ignoring", ex
);
744 } catch (IOException e
) {
745 logger
.warn("Receiving messages failed, retrying", e
);
748 logger
.debug("Finished receiving messages");
749 synchronized (messageHandlers
) {
750 receiveThread
= null;
752 // Check if in the meantime another handler has been registered
753 if (!messageHandlers
.isEmpty()) {
754 logger
.debug("Another handler has been registered, starting receive thread again");
755 startReceiveThreadIfRequired();
760 receiveThread
.start();
764 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
766 synchronized (messageHandlers
) {
767 weakHandlers
.remove(handler
);
768 messageHandlers
.remove(handler
);
769 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
772 thread
= receiveThread
;
773 receiveThread
= null;
776 stopReceiveThread(thread
);
779 private void stopReceiveThread(final Thread thread
) {
783 } catch (InterruptedException ignored
) {
788 public boolean isReceiving() {
789 if (isReceivingSynchronous
) {
792 synchronized (messageHandlers
) {
793 return messageHandlers
.size() > 0;
798 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
799 receiveMessages(timeout
, true, handler
);
803 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
804 receiveMessages(Duration
.ofMinutes(1), false, handler
);
807 private void receiveMessages(
808 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
809 ) throws IOException
{
811 throw new IllegalStateException("Already receiving message.");
813 isReceivingSynchronous
= true;
814 receiveThread
= Thread
.currentThread();
816 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
818 receiveThread
= null;
819 isReceivingSynchronous
= false;
824 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
825 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
829 public boolean hasCaughtUpWithOldMessages() {
830 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
834 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
835 final RecipientId recipientId
;
837 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
838 } catch (IOException
| UnregisteredRecipientException e
) {
841 return context
.getContactHelper().isContactBlocked(recipientId
);
845 public void sendContacts() throws IOException
{
846 context
.getSyncHelper().sendContacts();
850 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
851 return account
.getContactStore()
854 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
859 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
860 final RecipientId recipientId
;
862 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
863 } catch (IOException
| UnregisteredRecipientException e
) {
867 final var contact
= account
.getContactStore().getContact(recipientId
);
868 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
869 return contact
.getName();
872 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
873 if (profile
!= null) {
874 return profile
.getDisplayName();
881 public Group
getGroup(GroupId groupId
) {
882 return toGroup(context
.getGroupHelper().getGroup(groupId
));
886 public List
<Identity
> getIdentities() {
887 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
890 private Identity
toIdentity(final IdentityInfo identityInfo
) {
891 if (identityInfo
== null) {
895 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
896 final var scannableFingerprint
= context
.getIdentityHelper()
897 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
898 return new Identity(address
,
899 identityInfo
.getIdentityKey(),
900 context
.getIdentityHelper()
901 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
902 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
903 identityInfo
.getTrustLevel(),
904 identityInfo
.getDateAdded());
908 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
909 IdentityInfo identity
;
911 identity
= account
.getIdentityKeyStore()
912 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
913 } catch (IOException
| UnregisteredRecipientException e
) {
916 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
920 public boolean trustIdentityVerified(
921 RecipientIdentifier
.Single recipient
, byte[] fingerprint
922 ) throws UnregisteredRecipientException
{
923 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
927 public boolean trustIdentityVerifiedSafetyNumber(
928 RecipientIdentifier
.Single recipient
, String safetyNumber
929 ) throws UnregisteredRecipientException
{
930 return trustIdentity(recipient
,
931 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
935 public boolean trustIdentityVerifiedSafetyNumber(
936 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
937 ) throws UnregisteredRecipientException
{
938 return trustIdentity(recipient
,
939 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
943 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
944 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
947 private boolean trustIdentity(
948 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
949 ) throws UnregisteredRecipientException
{
950 RecipientId recipientId
;
952 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
953 } catch (IOException e
) {
956 final var updated
= trustMethod
.apply(recipientId
);
957 if (updated
&& this.isReceiving()) {
958 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
964 public void addClosedListener(final Runnable listener
) {
965 synchronized (closedListeners
) {
966 closedListeners
.add(listener
);
971 public void close() {
973 synchronized (messageHandlers
) {
974 weakHandlers
.clear();
975 messageHandlers
.clear();
976 thread
= receiveThread
;
977 receiveThread
= null;
979 if (thread
!= null) {
980 stopReceiveThread(thread
);
984 dependencies
.getSignalWebSocket().disconnect();
986 synchronized (closedListeners
) {
987 closedListeners
.forEach(Runnable
::run
);
988 closedListeners
.clear();
991 if (account
!= null) {