2 Copyright (C) 2015-2021 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
.actions
.HandleAction
;
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
.Message
;
26 import org
.asamk
.signal
.manager
.api
.Pair
;
27 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
28 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
29 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
30 import org
.asamk
.signal
.manager
.api
.TypingAction
;
31 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
32 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
33 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
34 import org
.asamk
.signal
.manager
.groups
.GroupId
;
35 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
36 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
37 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
38 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
39 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
40 import org
.asamk
.signal
.manager
.helper
.AttachmentHelper
;
41 import org
.asamk
.signal
.manager
.helper
.ContactHelper
;
42 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
43 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
44 import org
.asamk
.signal
.manager
.helper
.IdentityHelper
;
45 import org
.asamk
.signal
.manager
.helper
.IncomingMessageHandler
;
46 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
47 import org
.asamk
.signal
.manager
.helper
.PreKeyHelper
;
48 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
49 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
50 import org
.asamk
.signal
.manager
.helper
.StorageHelper
;
51 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
52 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
53 import org
.asamk
.signal
.manager
.jobs
.Context
;
54 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
55 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
56 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
57 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
58 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
59 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
60 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
61 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
62 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
63 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
64 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
65 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
66 import org
.slf4j
.Logger
;
67 import org
.slf4j
.LoggerFactory
;
68 import org
.whispersystems
.libsignal
.InvalidKeyException
;
69 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
70 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
71 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
72 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
73 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
74 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
75 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
76 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
78 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
79 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
80 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
81 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
82 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
83 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
84 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
85 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
86 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
87 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
88 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
91 import java
.io
.IOException
;
93 import java
.net
.URISyntaxException
;
94 import java
.net
.URLEncoder
;
95 import java
.nio
.charset
.StandardCharsets
;
96 import java
.security
.SignatureException
;
97 import java
.util
.Collection
;
98 import java
.util
.HashMap
;
99 import java
.util
.HashSet
;
100 import java
.util
.List
;
101 import java
.util
.Map
;
102 import java
.util
.Set
;
103 import java
.util
.UUID
;
104 import java
.util
.concurrent
.ExecutorService
;
105 import java
.util
.concurrent
.Executors
;
106 import java
.util
.concurrent
.TimeUnit
;
107 import java
.util
.concurrent
.TimeoutException
;
108 import java
.util
.concurrent
.locks
.ReentrantLock
;
109 import java
.util
.stream
.Collectors
;
111 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
113 public class ManagerImpl
implements Manager
{
115 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
117 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
118 private final SignalDependencies dependencies
;
120 private SignalAccount account
;
122 private final ExecutorService executor
= Executors
.newCachedThreadPool();
124 private final ProfileHelper profileHelper
;
125 private final PinHelper pinHelper
;
126 private final StorageHelper storageHelper
;
127 private final SendHelper sendHelper
;
128 private final SyncHelper syncHelper
;
129 private final AttachmentHelper attachmentHelper
;
130 private final GroupHelper groupHelper
;
131 private final ContactHelper contactHelper
;
132 private final IncomingMessageHandler incomingMessageHandler
;
133 private final PreKeyHelper preKeyHelper
;
134 private final IdentityHelper identityHelper
;
136 private final Context context
;
137 private boolean hasCaughtUpWithOldMessages
= false;
138 private boolean ignoreAttachments
= false;
140 private Thread receiveThread
;
141 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
142 private boolean isReceivingSynchronous
;
145 SignalAccount account
,
146 PathConfig pathConfig
,
147 ServiceEnvironmentConfig serviceEnvironmentConfig
,
150 this.account
= account
;
151 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
153 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
154 account
.getUsername(),
155 account
.getPassword(),
156 account
.getDeviceId());
157 final var sessionLock
= new SignalSessionLock() {
158 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
161 public Lock
acquire() {
163 return LEGACY_LOCK
::unlock
;
166 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
169 account
.getSignalProtocolStore(),
172 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
173 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
174 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
176 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
177 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
178 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
,
180 account
::getProfileKey
,
181 this::getRecipientProfile
);
182 this.profileHelper
= new ProfileHelper(account
,
185 unidentifiedAccessHelper
::getAccessFor
,
186 this::resolveSignalServiceAddress
);
187 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
188 this::getRecipientProfile
,
189 account
::getSelfRecipientId
,
190 dependencies
.getGroupsV2Operations(),
191 dependencies
.getGroupsV2Api(),
192 this::resolveSignalServiceAddress
);
193 this.sendHelper
= new SendHelper(account
,
195 unidentifiedAccessHelper
,
196 this::resolveSignalServiceAddress
,
197 account
.getRecipientStore(),
198 this::handleIdentityFailure
,
200 this::refreshRegisteredUser
);
201 this.groupHelper
= new GroupHelper(account
,
207 this::resolveSignalServiceAddress
,
208 account
.getRecipientStore());
209 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
210 this.contactHelper
= new ContactHelper(account
);
211 this.syncHelper
= new SyncHelper(account
,
216 this::resolveSignalServiceAddress
);
217 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
219 this.context
= new Context(account
,
228 var jobExecutor
= new JobExecutor(context
);
230 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
232 account
.getRecipientStore(),
233 this::resolveSignalServiceAddress
,
238 this::getRecipientProfile
,
240 this.identityHelper
= new IdentityHelper(account
,
242 this::resolveSignalServiceAddress
,
248 public String
getSelfNumber() {
249 return account
.getUsername();
253 public void checkAccountState() throws IOException
{
254 if (account
.getLastReceiveTimestamp() == 0) {
255 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
257 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
258 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
261 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
265 preKeyHelper
.refreshPreKeysIfNecessary();
266 if (account
.getUuid() == null) {
267 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
269 updateAccountAttributes(null);
273 * This is used for checking a set of phone numbers for registration on Signal
275 * @param numbers The set of phone number in question
276 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
277 * @throws IOException if its unable to get the contacts to check if they're registered
280 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
281 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
283 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
284 } catch (InvalidNumberException e
) {
289 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
290 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
292 .filter(s
-> !s
.isEmpty())
293 .collect(Collectors
.toSet()));
295 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
296 final var number
= canonicalizedNumbers
.get(n
);
297 final var uuid
= registeredUsers
.get(number
);
298 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
303 public void updateAccountAttributes(String deviceName
) throws IOException
{
304 final String encryptedDeviceName
;
305 if (deviceName
== null) {
306 encryptedDeviceName
= account
.getEncryptedDeviceName();
308 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
309 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
310 account
.setEncryptedDeviceName(encryptedDeviceName
);
312 dependencies
.getAccountManager()
313 .setAccountAttributes(encryptedDeviceName
,
315 account
.getLocalRegistrationId(),
318 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
319 account
.getSelfUnidentifiedAccessKey(),
320 account
.isUnrestrictedUnidentifiedAccess(),
322 account
.isDiscoverableByPhoneNumber());
326 public void updateConfiguration(
327 final Boolean readReceipts
,
328 final Boolean unidentifiedDeliveryIndicators
,
329 final Boolean typingIndicators
,
330 final Boolean linkPreviews
331 ) throws IOException
, NotMasterDeviceException
{
332 if (!account
.isMasterDevice()) {
333 throw new NotMasterDeviceException();
336 final var configurationStore
= account
.getConfigurationStore();
337 if (readReceipts
!= null) {
338 configurationStore
.setReadReceipts(readReceipts
);
340 if (unidentifiedDeliveryIndicators
!= null) {
341 configurationStore
.setUnidentifiedDeliveryIndicators(unidentifiedDeliveryIndicators
);
343 if (typingIndicators
!= null) {
344 configurationStore
.setTypingIndicators(typingIndicators
);
346 if (linkPreviews
!= null) {
347 configurationStore
.setLinkPreviews(linkPreviews
);
349 syncHelper
.sendConfigurationMessage();
353 * @param givenName if null, the previous givenName will be kept
354 * @param familyName if null, the previous familyName will be kept
355 * @param about if null, the previous about text will be kept
356 * @param aboutEmoji if null, the previous about emoji will be kept
357 * @param avatar if avatar is null the image from the local avatar store is used (if present),
360 public void setProfile(
361 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
362 ) throws IOException
{
363 profileHelper
.setProfile(givenName
,
367 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
368 syncHelper
.sendSyncFetchProfileMessage();
372 public void unregister() throws IOException
{
373 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
374 // If this is the master device, other users can't send messages to this number anymore.
375 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
376 dependencies
.getAccountManager().setGcmId(Optional
.absent());
378 account
.setRegistered(false);
382 public void deleteAccount() throws IOException
{
384 pinHelper
.removeRegistrationLockPin();
385 } catch (UnauthenticatedResponseException e
) {
386 logger
.warn("Failed to remove registration lock pin");
388 account
.setRegistrationLockPin(null, null);
390 dependencies
.getAccountManager().deleteAccount();
392 account
.setRegistered(false);
396 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
397 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
401 public List
<Device
> getLinkedDevices() throws IOException
{
402 var devices
= dependencies
.getAccountManager().getDevices();
403 account
.setMultiDevice(devices
.size() > 1);
404 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
405 return devices
.stream().map(d
-> {
406 String deviceName
= d
.getName();
407 if (deviceName
!= null) {
409 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
410 } catch (IOException e
) {
411 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
414 return new Device(d
.getId(),
418 d
.getId() == account
.getDeviceId());
419 }).collect(Collectors
.toList());
423 public void removeLinkedDevices(long deviceId
) throws IOException
{
424 dependencies
.getAccountManager().removeDevice(deviceId
);
425 var devices
= dependencies
.getAccountManager().getDevices();
426 account
.setMultiDevice(devices
.size() > 1);
430 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
431 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
433 addDevice(info
.deviceIdentifier(), info
.deviceKey());
436 private void addDevice(
437 String deviceIdentifier
, ECPublicKey deviceKey
438 ) throws IOException
, InvalidDeviceLinkException
{
439 var identityKeyPair
= account
.getIdentityKeyPair();
440 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
443 dependencies
.getAccountManager()
444 .addDevice(deviceIdentifier
,
447 Optional
.of(account
.getProfileKey().serialize()),
449 } catch (InvalidKeyException e
) {
450 throw new InvalidDeviceLinkException("Invalid device link", e
);
452 account
.setMultiDevice(true);
456 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
457 if (!account
.isMasterDevice()) {
458 throw new RuntimeException("Only master device can set a PIN");
460 if (pin
.isPresent()) {
461 final var masterKey
= account
.getPinMasterKey() != null
462 ? account
.getPinMasterKey()
463 : KeyUtils
.createMasterKey();
465 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
467 account
.setRegistrationLockPin(pin
.get(), masterKey
);
470 pinHelper
.removeRegistrationLockPin();
472 account
.setRegistrationLockPin(null, null);
476 void refreshPreKeys() throws IOException
{
477 preKeyHelper
.refreshPreKeys();
481 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
{
482 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
485 private Profile
getRecipientProfile(RecipientId recipientId
) {
486 return profileHelper
.getRecipientProfile(recipientId
);
490 public List
<Group
> getGroups() {
491 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
494 private Group
toGroup(final GroupInfo groupInfo
) {
495 if (groupInfo
== null) {
499 return new Group(groupInfo
.getGroupId(),
500 groupInfo
.getTitle(),
501 groupInfo
.getDescription(),
502 groupInfo
.getGroupInviteLink(),
503 groupInfo
.getMembers()
505 .map(account
.getRecipientStore()::resolveRecipientAddress
)
506 .collect(Collectors
.toSet()),
507 groupInfo
.getPendingMembers()
509 .map(account
.getRecipientStore()::resolveRecipientAddress
)
510 .collect(Collectors
.toSet()),
511 groupInfo
.getRequestingMembers()
513 .map(account
.getRecipientStore()::resolveRecipientAddress
)
514 .collect(Collectors
.toSet()),
515 groupInfo
.getAdminMembers()
517 .map(account
.getRecipientStore()::resolveRecipientAddress
)
518 .collect(Collectors
.toSet()),
519 groupInfo
.isBlocked(),
520 groupInfo
.getMessageExpirationTimer(),
521 groupInfo
.getPermissionAddMember(),
522 groupInfo
.getPermissionEditDetails(),
523 groupInfo
.getPermissionSendMessage(),
524 groupInfo
.isMember(account
.getSelfRecipientId()),
525 groupInfo
.isAdmin(account
.getSelfRecipientId()));
529 public SendGroupMessageResults
quitGroup(
530 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
531 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
532 final var newAdmins
= resolveRecipients(groupAdmins
);
533 return groupHelper
.quitGroup(groupId
, newAdmins
);
537 public void deleteGroup(GroupId groupId
) throws IOException
{
538 groupHelper
.deleteGroup(groupId
);
542 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
543 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
544 ) throws IOException
, AttachmentInvalidException
{
545 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
549 public SendGroupMessageResults
updateGroup(
550 final GroupId groupId
, final UpdateGroup updateGroup
551 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
552 return groupHelper
.updateGroup(groupId
,
553 updateGroup
.getName(),
554 updateGroup
.getDescription(),
555 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
556 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
557 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
558 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
559 updateGroup
.isResetGroupLink(),
560 updateGroup
.getGroupLinkState(),
561 updateGroup
.getAddMemberPermission(),
562 updateGroup
.getEditDetailsPermission(),
563 updateGroup
.getAvatarFile(),
564 updateGroup
.getExpirationTimer(),
565 updateGroup
.getIsAnnouncementGroup());
569 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
570 GroupInviteLinkUrl inviteLinkUrl
571 ) throws IOException
, InactiveGroupLinkException
{
572 return groupHelper
.joinGroup(inviteLinkUrl
);
575 private SendMessageResults
sendMessage(
576 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
577 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
578 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
579 long timestamp
= System
.currentTimeMillis();
580 messageBuilder
.withTimestamp(timestamp
);
581 for (final var recipient
: recipients
) {
582 if (recipient
instanceof RecipientIdentifier
.Single single
) {
583 final var recipientId
= resolveRecipient(single
);
584 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
585 results
.put(recipient
, List
.of(result
));
586 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
587 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
588 results
.put(recipient
, List
.of(result
));
589 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
590 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, group
.groupId
);
591 results
.put(recipient
, result
);
594 return new SendMessageResults(timestamp
, results
);
597 private void sendTypingMessage(
598 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
599 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
600 final var timestamp
= System
.currentTimeMillis();
601 for (var recipient
: recipients
) {
602 if (recipient
instanceof RecipientIdentifier
.Single
) {
603 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
604 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
605 sendHelper
.sendTypingMessage(message
, recipientId
);
606 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
607 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
608 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
609 sendHelper
.sendGroupTypingMessage(message
, groupId
);
615 public void sendTypingMessage(
616 TypingAction action
, Set
<RecipientIdentifier
> recipients
617 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
618 sendTypingMessage(action
.toSignalService(), recipients
);
622 public void sendReadReceipt(
623 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
624 ) throws IOException
, UntrustedIdentityException
{
625 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
627 System
.currentTimeMillis());
629 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
633 public void sendViewedReceipt(
634 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
635 ) throws IOException
, UntrustedIdentityException
{
636 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
638 System
.currentTimeMillis());
640 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
644 public SendMessageResults
sendMessage(
645 Message message
, Set
<RecipientIdentifier
> recipients
646 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
647 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
648 applyMessage(messageBuilder
, message
);
649 return sendMessage(messageBuilder
, recipients
);
652 private void applyMessage(
653 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
654 ) throws AttachmentInvalidException
, IOException
{
655 messageBuilder
.withBody(message
.messageText());
656 final var attachments
= message
.attachments();
657 if (attachments
!= null) {
658 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
663 public SendMessageResults
sendRemoteDeleteMessage(
664 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
665 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
666 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
667 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
668 return sendMessage(messageBuilder
, recipients
);
672 public SendMessageResults
sendMessageReaction(
675 RecipientIdentifier
.Single targetAuthor
,
676 long targetSentTimestamp
,
677 Set
<RecipientIdentifier
> recipients
678 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
679 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
680 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
682 resolveSignalServiceAddress(targetAuthorRecipientId
),
683 targetSentTimestamp
);
684 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
685 return sendMessage(messageBuilder
, recipients
);
689 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
690 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
693 return sendMessage(messageBuilder
,
694 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
695 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
696 throw new AssertionError(e
);
698 for (var recipient
: recipients
) {
699 final var recipientId
= resolveRecipient(recipient
);
700 account
.getSessionStore().deleteAllSessions(recipientId
);
706 public void setContactName(
707 RecipientIdentifier
.Single recipient
, String name
708 ) throws NotMasterDeviceException
, IOException
{
709 if (!account
.isMasterDevice()) {
710 throw new NotMasterDeviceException();
712 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
716 public void setContactBlocked(
717 RecipientIdentifier
.Single recipient
, boolean blocked
718 ) throws NotMasterDeviceException
, IOException
{
719 if (!account
.isMasterDevice()) {
720 throw new NotMasterDeviceException();
722 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
723 // TODO cycle our profile key
724 syncHelper
.sendBlockedList();
728 public void setGroupBlocked(
729 final GroupId groupId
, final boolean blocked
730 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
731 if (!account
.isMasterDevice()) {
732 throw new NotMasterDeviceException();
734 groupHelper
.setGroupBlocked(groupId
, blocked
);
735 // TODO cycle our profile key
736 syncHelper
.sendBlockedList();
740 * Change the expiration timer for a contact
743 public void setExpirationTimer(
744 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
745 ) throws IOException
{
746 var recipientId
= resolveRecipient(recipient
);
747 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
748 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
750 sendMessage(messageBuilder
, Set
.of(recipient
));
751 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
752 throw new AssertionError(e
);
757 * Upload the sticker pack from path.
759 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
760 * @return if successful, returns the URL to install the sticker pack in the signal app
763 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
764 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
766 var messageSender
= dependencies
.getMessageSender();
768 var packKey
= KeyUtils
.createStickerUploadKey();
769 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
770 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
772 var sticker
= new Sticker(packId
, packKey
);
773 account
.getStickerStore().updateSticker(sticker
);
776 return new URI("https",
780 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
782 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
783 } catch (URISyntaxException e
) {
784 throw new AssertionError(e
);
789 public void requestAllSyncData() throws IOException
{
790 syncHelper
.requestAllSyncData();
791 retrieveRemoteStorage();
794 void retrieveRemoteStorage() throws IOException
{
795 if (account
.getStorageKey() != null) {
796 storageHelper
.readDataFromStorage();
800 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
801 final var address
= resolveSignalServiceAddress(recipientId
);
802 if (!address
.getNumber().isPresent()) {
805 final var number
= address
.getNumber().get();
806 final var uuid
= getRegisteredUser(number
);
807 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
810 private UUID
getRegisteredUser(final String number
) throws IOException
{
811 final Map
<String
, UUID
> uuidMap
;
813 uuidMap
= getRegisteredUsers(Set
.of(number
));
814 } catch (NumberFormatException e
) {
815 throw new IOException(number
, e
);
817 final var uuid
= uuidMap
.get(number
);
819 throw new IOException(number
, null);
824 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
825 final Map
<String
, UUID
> registeredUsers
;
827 registeredUsers
= dependencies
.getAccountManager()
828 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
830 serviceEnvironmentConfig
.getCdsMrenclave());
831 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
832 throw new IOException(e
);
835 // Store numbers as recipients so we have the number/uuid association
836 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
838 return registeredUsers
;
841 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
842 Set
<HandleAction
> queuedActions
= new HashSet
<>();
843 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
844 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
845 if (actions
!= null) {
846 queuedActions
.addAll(actions
);
849 handleQueuedActions(queuedActions
);
852 private List
<HandleAction
> retryFailedReceivedMessage(
853 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
855 var envelope
= cachedMessage
.loadEnvelope();
856 if (envelope
== null) {
857 cachedMessage
.delete();
861 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
862 final var actions
= result
.first();
863 final var exception
= result
.second();
865 if (exception
instanceof UntrustedIdentityException
) {
866 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
867 // Envelope is more than a month old, cleaning up.
868 cachedMessage
.delete();
871 if (!envelope
.hasSourceUuid()) {
872 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
873 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
875 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
876 } catch (IOException ioException
) {
877 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
883 // If successful and for all other errors that are not recoverable, delete the cached message
884 cachedMessage
.delete();
889 public void addReceiveHandler(final ReceiveMessageHandler handler
) {
890 if (isReceivingSynchronous
) {
891 throw new IllegalStateException("Already receiving message synchronously.");
893 synchronized (messageHandlers
) {
894 messageHandlers
.add(handler
);
896 startReceiveThreadIfRequired();
900 private void startReceiveThreadIfRequired() {
901 if (receiveThread
!= null) {
904 receiveThread
= new Thread(() -> {
905 while (!Thread
.interrupted()) {
907 receiveMessagesInternal(1L, TimeUnit
.HOURS
, false, (envelope
, decryptedContent
, e
) -> {
908 synchronized (messageHandlers
) {
909 for (ReceiveMessageHandler h
: messageHandlers
) {
911 h
.handleMessage(envelope
, decryptedContent
, e
);
912 } catch (Exception ex
) {
913 logger
.warn("Message handler failed, ignoring", ex
);
919 } catch (IOException e
) {
920 logger
.warn("Receiving messages failed, retrying", e
);
923 hasCaughtUpWithOldMessages
= false;
924 synchronized (messageHandlers
) {
925 receiveThread
= null;
927 // Check if in the meantime another handler has been registered
928 if (!messageHandlers
.isEmpty()) {
929 startReceiveThreadIfRequired();
934 receiveThread
.start();
938 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
940 synchronized (messageHandlers
) {
941 thread
= receiveThread
;
942 receiveThread
= null;
943 messageHandlers
.remove(handler
);
944 if (!messageHandlers
.isEmpty() || isReceivingSynchronous
) {
949 stopReceiveThread(thread
);
952 private void stopReceiveThread(final Thread thread
) {
956 } catch (InterruptedException ignored
) {
961 public boolean isReceiving() {
962 if (isReceivingSynchronous
) {
965 synchronized (messageHandlers
) {
966 return messageHandlers
.size() > 0;
971 public void receiveMessages(long timeout
, TimeUnit unit
, ReceiveMessageHandler handler
) throws IOException
{
972 receiveMessages(timeout
, unit
, true, handler
);
976 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
977 receiveMessages(1L, TimeUnit
.HOURS
, false, handler
);
980 private void receiveMessages(
981 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
982 ) throws IOException
{
984 throw new IllegalStateException("Already receiving message.");
986 isReceivingSynchronous
= true;
987 receiveThread
= Thread
.currentThread();
989 receiveMessagesInternal(timeout
, unit
, returnOnTimeout
, handler
);
991 receiveThread
= null;
992 hasCaughtUpWithOldMessages
= false;
993 isReceivingSynchronous
= false;
997 private void receiveMessagesInternal(
998 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
999 ) throws IOException
{
1000 retryFailedReceivedMessages(handler
);
1002 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1004 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1005 signalWebSocket
.connect();
1007 hasCaughtUpWithOldMessages
= false;
1008 var backOffCounter
= 0;
1009 final var MAX_BACKOFF_COUNTER
= 9;
1011 while (!Thread
.interrupted()) {
1012 SignalServiceEnvelope envelope
;
1013 final CachedMessage
[] cachedMessage
= {null};
1014 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1015 logger
.debug("Checking for new message from server");
1017 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1018 final var recipientId
= envelope1
.hasSourceUuid()
1019 ?
resolveRecipient(envelope1
.getSourceAddress())
1021 // store message on disk, before acknowledging receipt to the server
1022 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1026 if (result
.isPresent()) {
1027 envelope
= result
.get();
1028 logger
.debug("New message received from server");
1030 logger
.debug("Received indicator that server queue is empty");
1031 handleQueuedActions(queuedActions
);
1032 queuedActions
.clear();
1034 hasCaughtUpWithOldMessages
= true;
1035 synchronized (this) {
1039 // Continue to wait another timeout for new messages
1042 } catch (AssertionError e
) {
1043 if (e
.getCause() instanceof InterruptedException
) {
1044 Thread
.currentThread().interrupt();
1049 } catch (IOException e
) {
1050 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1051 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1052 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1053 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1054 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1056 Thread
.sleep(sleepMilliseconds
);
1057 } catch (InterruptedException interruptedException
) {
1060 hasCaughtUpWithOldMessages
= false;
1061 signalWebSocket
.connect();
1065 } catch (TimeoutException e
) {
1067 if (returnOnTimeout
) return;
1071 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
1072 queuedActions
.addAll(result
.first());
1073 final var exception
= result
.second();
1075 if (hasCaughtUpWithOldMessages
) {
1076 handleQueuedActions(queuedActions
);
1077 queuedActions
.clear();
1079 if (cachedMessage
[0] != null) {
1080 if (exception
instanceof UntrustedIdentityException
) {
1081 logger
.debug("Keeping message with untrusted identity in message cache");
1082 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1083 final var recipientId
= resolveRecipient(address
);
1084 if (!envelope
.hasSourceUuid()) {
1086 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1087 } catch (IOException ioException
) {
1088 logger
.warn("Failed to move cached message to recipient folder: {}",
1089 ioException
.getMessage());
1093 cachedMessage
[0].delete();
1097 handleQueuedActions(queuedActions
);
1098 queuedActions
.clear();
1102 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1103 this.ignoreAttachments
= ignoreAttachments
;
1107 public boolean hasCaughtUpWithOldMessages() {
1108 return hasCaughtUpWithOldMessages
;
1111 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1112 logger
.debug("Handling message actions");
1113 var interrupted
= false;
1114 for (var action
: queuedActions
) {
1116 action
.execute(context
);
1117 } catch (Throwable e
) {
1118 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1119 && e
.getCause() instanceof InterruptedException
) {
1123 logger
.warn("Message action failed.", e
);
1127 Thread
.currentThread().interrupt();
1132 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1133 final RecipientId recipientId
;
1135 recipientId
= resolveRecipient(recipient
);
1136 } catch (IOException e
) {
1139 return contactHelper
.isContactBlocked(recipientId
);
1143 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
1144 return attachmentHelper
.getAttachmentFile(attachmentId
);
1148 public void sendContacts() throws IOException
{
1149 syncHelper
.sendContacts();
1153 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1154 return account
.getContactStore()
1157 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1158 .collect(Collectors
.toList());
1162 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1163 final RecipientId recipientId
;
1165 recipientId
= resolveRecipient(recipient
);
1166 } catch (IOException e
) {
1170 final var contact
= account
.getContactStore().getContact(recipientId
);
1171 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1172 return contact
.getName();
1175 final var profile
= getRecipientProfile(recipientId
);
1176 if (profile
!= null) {
1177 return profile
.getDisplayName();
1184 public Group
getGroup(GroupId groupId
) {
1185 return toGroup(groupHelper
.getGroup(groupId
));
1188 private GroupInfo
getGroupInfo(GroupId groupId
) {
1189 return groupHelper
.getGroup(groupId
);
1193 public List
<Identity
> getIdentities() {
1194 return account
.getIdentityKeyStore()
1197 .map(this::toIdentity
)
1198 .collect(Collectors
.toList());
1201 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1202 if (identityInfo
== null) {
1206 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1207 final var scannableFingerprint
= identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1208 identityInfo
.getIdentityKey());
1209 return new Identity(address
,
1210 identityInfo
.getIdentityKey(),
1211 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1212 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1213 identityInfo
.getTrustLevel(),
1214 identityInfo
.getDateAdded());
1218 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1219 IdentityInfo identity
;
1221 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1222 } catch (IOException e
) {
1225 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1229 * Trust this the identity with this fingerprint
1231 * @param recipient username of the identity
1232 * @param fingerprint Fingerprint
1235 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1236 RecipientId recipientId
;
1238 recipientId
= resolveRecipient(recipient
);
1239 } catch (IOException e
) {
1242 return identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1246 * Trust this the identity with this safety number
1248 * @param recipient username of the identity
1249 * @param safetyNumber Safety number
1252 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1253 RecipientId recipientId
;
1255 recipientId
= resolveRecipient(recipient
);
1256 } catch (IOException e
) {
1259 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1263 * Trust this the identity with this scannable safety number
1265 * @param recipient username of the identity
1266 * @param safetyNumber Scannable safety number
1269 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1270 RecipientId recipientId
;
1272 recipientId
= resolveRecipient(recipient
);
1273 } catch (IOException e
) {
1276 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1280 * Trust all keys of this identity without verification
1282 * @param recipient username of the identity
1285 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1286 RecipientId recipientId
;
1288 recipientId
= resolveRecipient(recipient
);
1289 } catch (IOException e
) {
1292 return identityHelper
.trustIdentityAllKeys(recipientId
);
1295 private void handleIdentityFailure(
1296 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1298 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1302 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1303 return resolveSignalServiceAddress(resolveRecipient(address
));
1306 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1307 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1308 if (address
.getUuid().isPresent()) {
1309 return address
.toSignalServiceAddress();
1312 // Address in recipient store doesn't have a uuid, this shouldn't happen
1313 // Try to retrieve the uuid from the server
1314 final var number
= address
.getNumber().get();
1317 uuid
= getRegisteredUser(number
);
1318 } catch (IOException e
) {
1319 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1320 // Return SignalServiceAddress with unknown UUID
1321 return address
.toSignalServiceAddress();
1323 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1326 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
1327 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1328 for (var number
: recipients
) {
1329 final var recipientId
= resolveRecipient(number
);
1330 recipientIds
.add(recipientId
);
1332 return recipientIds
;
1335 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
1336 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1337 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1339 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1340 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1342 return getRegisteredUser(number
);
1343 } catch (IOException e
) {
1350 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1351 return account
.getRecipientStore().resolveRecipient(address
);
1354 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1355 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1359 public void close() throws IOException
{
1363 private void close(boolean closeAccount
) throws IOException
{
1365 synchronized (messageHandlers
) {
1366 messageHandlers
.clear();
1367 thread
= receiveThread
;
1368 receiveThread
= null;
1370 if (thread
!= null) {
1371 stopReceiveThread(thread
);
1373 executor
.shutdown();
1375 dependencies
.getSignalWebSocket().disconnect();
1377 if (closeAccount
&& account
!= null) {