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
.SendMessageResult
;
30 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
31 import org
.asamk
.signal
.manager
.api
.TypingAction
;
32 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
33 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
34 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
35 import org
.asamk
.signal
.manager
.groups
.GroupId
;
36 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
37 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
38 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
39 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
40 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
41 import org
.asamk
.signal
.manager
.helper
.AttachmentHelper
;
42 import org
.asamk
.signal
.manager
.helper
.ContactHelper
;
43 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
44 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
45 import org
.asamk
.signal
.manager
.helper
.IdentityHelper
;
46 import org
.asamk
.signal
.manager
.helper
.IncomingMessageHandler
;
47 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
48 import org
.asamk
.signal
.manager
.helper
.PreKeyHelper
;
49 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
50 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
51 import org
.asamk
.signal
.manager
.helper
.StorageHelper
;
52 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
53 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
54 import org
.asamk
.signal
.manager
.jobs
.Context
;
55 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
56 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
57 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
58 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
59 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
60 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
61 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
62 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
63 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
64 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
65 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
66 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
67 import org
.slf4j
.Logger
;
68 import org
.slf4j
.LoggerFactory
;
69 import org
.whispersystems
.libsignal
.InvalidKeyException
;
70 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
71 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
72 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
73 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
74 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
75 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
76 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
77 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
78 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
79 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
80 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
81 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
82 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
83 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
84 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
85 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
86 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
87 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
90 import java
.io
.IOException
;
92 import java
.net
.URISyntaxException
;
93 import java
.net
.URLEncoder
;
94 import java
.nio
.charset
.StandardCharsets
;
95 import java
.security
.SignatureException
;
96 import java
.util
.Collection
;
97 import java
.util
.HashMap
;
98 import java
.util
.HashSet
;
99 import java
.util
.List
;
100 import java
.util
.Map
;
101 import java
.util
.Set
;
102 import java
.util
.UUID
;
103 import java
.util
.concurrent
.ExecutorService
;
104 import java
.util
.concurrent
.Executors
;
105 import java
.util
.concurrent
.TimeUnit
;
106 import java
.util
.concurrent
.TimeoutException
;
107 import java
.util
.concurrent
.locks
.ReentrantLock
;
108 import java
.util
.stream
.Collectors
;
110 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
112 public class ManagerImpl
implements Manager
{
114 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
116 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
117 private final SignalDependencies dependencies
;
119 private SignalAccount account
;
121 private final ExecutorService executor
= Executors
.newCachedThreadPool();
123 private final ProfileHelper profileHelper
;
124 private final PinHelper pinHelper
;
125 private final StorageHelper storageHelper
;
126 private final SendHelper sendHelper
;
127 private final SyncHelper syncHelper
;
128 private final AttachmentHelper attachmentHelper
;
129 private final GroupHelper groupHelper
;
130 private final ContactHelper contactHelper
;
131 private final IncomingMessageHandler incomingMessageHandler
;
132 private final PreKeyHelper preKeyHelper
;
133 private final IdentityHelper identityHelper
;
135 private final Context context
;
136 private boolean hasCaughtUpWithOldMessages
= false;
137 private boolean ignoreAttachments
= false;
139 private Thread receiveThread
;
140 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
141 private boolean isReceivingSynchronous
;
144 SignalAccount account
,
145 PathConfig pathConfig
,
146 ServiceEnvironmentConfig serviceEnvironmentConfig
,
149 this.account
= account
;
150 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
152 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
153 account
.getUsername(),
154 account
.getPassword(),
155 account
.getDeviceId());
156 final var sessionLock
= new SignalSessionLock() {
157 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
160 public Lock
acquire() {
162 return LEGACY_LOCK
::unlock
;
165 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
168 account
.getSignalProtocolStore(),
171 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
172 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
173 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
175 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
176 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
177 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
,
179 account
::getProfileKey
,
180 this::getRecipientProfile
);
181 this.profileHelper
= new ProfileHelper(account
,
184 unidentifiedAccessHelper
::getAccessFor
,
185 this::resolveSignalServiceAddress
);
186 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
187 this::getRecipientProfile
,
188 account
::getSelfRecipientId
,
189 dependencies
.getGroupsV2Operations(),
190 dependencies
.getGroupsV2Api(),
191 this::resolveSignalServiceAddress
);
192 this.sendHelper
= new SendHelper(account
,
194 unidentifiedAccessHelper
,
195 this::resolveSignalServiceAddress
,
196 account
.getRecipientStore(),
197 this::handleIdentityFailure
,
199 this::refreshRegisteredUser
);
200 this.groupHelper
= new GroupHelper(account
,
206 this::resolveSignalServiceAddress
,
207 account
.getRecipientStore());
208 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
209 this.contactHelper
= new ContactHelper(account
);
210 this.syncHelper
= new SyncHelper(account
,
215 this::resolveSignalServiceAddress
);
216 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
218 this.context
= new Context(account
,
227 var jobExecutor
= new JobExecutor(context
);
229 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
231 account
.getRecipientStore(),
232 this::resolveSignalServiceAddress
,
237 this::getRecipientProfile
,
239 this.identityHelper
= new IdentityHelper(account
,
241 this::resolveSignalServiceAddress
,
247 public String
getSelfNumber() {
248 return account
.getUsername();
252 public void checkAccountState() throws IOException
{
253 if (account
.getLastReceiveTimestamp() == 0) {
254 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
256 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
257 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
260 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
264 preKeyHelper
.refreshPreKeysIfNecessary();
265 if (account
.getUuid() == null) {
266 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
268 updateAccountAttributes(null);
272 * This is used for checking a set of phone numbers for registration on Signal
274 * @param numbers The set of phone number in question
275 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
276 * @throws IOException if its unable to get the contacts to check if they're registered
279 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
280 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
282 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
283 } catch (InvalidNumberException e
) {
288 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
289 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
291 .filter(s
-> !s
.isEmpty())
292 .collect(Collectors
.toSet()));
294 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
295 final var number
= canonicalizedNumbers
.get(n
);
296 final var uuid
= registeredUsers
.get(number
);
297 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
302 public void updateAccountAttributes(String deviceName
) throws IOException
{
303 final String encryptedDeviceName
;
304 if (deviceName
== null) {
305 encryptedDeviceName
= account
.getEncryptedDeviceName();
307 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
308 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
309 account
.setEncryptedDeviceName(encryptedDeviceName
);
311 dependencies
.getAccountManager()
312 .setAccountAttributes(encryptedDeviceName
,
314 account
.getLocalRegistrationId(),
317 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
318 account
.getSelfUnidentifiedAccessKey(),
319 account
.isUnrestrictedUnidentifiedAccess(),
321 account
.isDiscoverableByPhoneNumber());
325 public void updateConfiguration(
326 final Boolean readReceipts
,
327 final Boolean unidentifiedDeliveryIndicators
,
328 final Boolean typingIndicators
,
329 final Boolean linkPreviews
330 ) throws IOException
, NotMasterDeviceException
{
331 if (!account
.isMasterDevice()) {
332 throw new NotMasterDeviceException();
335 final var configurationStore
= account
.getConfigurationStore();
336 if (readReceipts
!= null) {
337 configurationStore
.setReadReceipts(readReceipts
);
339 if (unidentifiedDeliveryIndicators
!= null) {
340 configurationStore
.setUnidentifiedDeliveryIndicators(unidentifiedDeliveryIndicators
);
342 if (typingIndicators
!= null) {
343 configurationStore
.setTypingIndicators(typingIndicators
);
345 if (linkPreviews
!= null) {
346 configurationStore
.setLinkPreviews(linkPreviews
);
348 syncHelper
.sendConfigurationMessage();
352 * @param givenName if null, the previous givenName will be kept
353 * @param familyName if null, the previous familyName will be kept
354 * @param about if null, the previous about text will be kept
355 * @param aboutEmoji if null, the previous about emoji will be kept
356 * @param avatar if avatar is null the image from the local avatar store is used (if present),
359 public void setProfile(
360 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
361 ) throws IOException
{
362 profileHelper
.setProfile(givenName
,
366 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
367 syncHelper
.sendSyncFetchProfileMessage();
371 public void unregister() throws IOException
{
372 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
373 // If this is the master device, other users can't send messages to this number anymore.
374 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
375 dependencies
.getAccountManager().setGcmId(Optional
.absent());
377 account
.setRegistered(false);
381 public void deleteAccount() throws IOException
{
383 pinHelper
.removeRegistrationLockPin();
384 } catch (IOException e
) {
385 logger
.warn("Failed to remove registration lock pin");
387 account
.setRegistrationLockPin(null, null);
389 dependencies
.getAccountManager().deleteAccount();
391 account
.setRegistered(false);
395 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
396 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
400 public List
<Device
> getLinkedDevices() throws IOException
{
401 var devices
= dependencies
.getAccountManager().getDevices();
402 account
.setMultiDevice(devices
.size() > 1);
403 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
404 return devices
.stream().map(d
-> {
405 String deviceName
= d
.getName();
406 if (deviceName
!= null) {
408 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
409 } catch (IOException e
) {
410 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
413 return new Device(d
.getId(),
417 d
.getId() == account
.getDeviceId());
418 }).collect(Collectors
.toList());
422 public void removeLinkedDevices(long deviceId
) throws IOException
{
423 dependencies
.getAccountManager().removeDevice(deviceId
);
424 var devices
= dependencies
.getAccountManager().getDevices();
425 account
.setMultiDevice(devices
.size() > 1);
429 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
430 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
432 addDevice(info
.deviceIdentifier(), info
.deviceKey());
435 private void addDevice(
436 String deviceIdentifier
, ECPublicKey deviceKey
437 ) throws IOException
, InvalidDeviceLinkException
{
438 var identityKeyPair
= account
.getIdentityKeyPair();
439 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
442 dependencies
.getAccountManager()
443 .addDevice(deviceIdentifier
,
446 Optional
.of(account
.getProfileKey().serialize()),
448 } catch (InvalidKeyException e
) {
449 throw new InvalidDeviceLinkException("Invalid device link", e
);
451 account
.setMultiDevice(true);
455 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
{
456 if (!account
.isMasterDevice()) {
457 throw new RuntimeException("Only master device can set a PIN");
459 if (pin
.isPresent()) {
460 final var masterKey
= account
.getPinMasterKey() != null
461 ? account
.getPinMasterKey()
462 : KeyUtils
.createMasterKey();
464 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
466 account
.setRegistrationLockPin(pin
.get(), masterKey
);
469 pinHelper
.removeRegistrationLockPin();
471 account
.setRegistrationLockPin(null, null);
475 void refreshPreKeys() throws IOException
{
476 preKeyHelper
.refreshPreKeys();
480 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
{
481 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
484 private Profile
getRecipientProfile(RecipientId recipientId
) {
485 return profileHelper
.getRecipientProfile(recipientId
);
489 public List
<Group
> getGroups() {
490 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
493 private Group
toGroup(final GroupInfo groupInfo
) {
494 if (groupInfo
== null) {
498 return new Group(groupInfo
.getGroupId(),
499 groupInfo
.getTitle(),
500 groupInfo
.getDescription(),
501 groupInfo
.getGroupInviteLink(),
502 groupInfo
.getMembers()
504 .map(account
.getRecipientStore()::resolveRecipientAddress
)
505 .collect(Collectors
.toSet()),
506 groupInfo
.getPendingMembers()
508 .map(account
.getRecipientStore()::resolveRecipientAddress
)
509 .collect(Collectors
.toSet()),
510 groupInfo
.getRequestingMembers()
512 .map(account
.getRecipientStore()::resolveRecipientAddress
)
513 .collect(Collectors
.toSet()),
514 groupInfo
.getAdminMembers()
516 .map(account
.getRecipientStore()::resolveRecipientAddress
)
517 .collect(Collectors
.toSet()),
518 groupInfo
.isBlocked(),
519 groupInfo
.getMessageExpirationTimer(),
520 groupInfo
.getPermissionAddMember(),
521 groupInfo
.getPermissionEditDetails(),
522 groupInfo
.getPermissionSendMessage(),
523 groupInfo
.isMember(account
.getSelfRecipientId()),
524 groupInfo
.isAdmin(account
.getSelfRecipientId()));
528 public SendGroupMessageResults
quitGroup(
529 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
530 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
531 final var newAdmins
= resolveRecipients(groupAdmins
);
532 return groupHelper
.quitGroup(groupId
, newAdmins
);
536 public void deleteGroup(GroupId groupId
) throws IOException
{
537 groupHelper
.deleteGroup(groupId
);
541 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
542 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
543 ) throws IOException
, AttachmentInvalidException
{
544 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
548 public SendGroupMessageResults
updateGroup(
549 final GroupId groupId
, final UpdateGroup updateGroup
550 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
551 return groupHelper
.updateGroup(groupId
,
552 updateGroup
.getName(),
553 updateGroup
.getDescription(),
554 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
555 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
556 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
557 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
558 updateGroup
.isResetGroupLink(),
559 updateGroup
.getGroupLinkState(),
560 updateGroup
.getAddMemberPermission(),
561 updateGroup
.getEditDetailsPermission(),
562 updateGroup
.getAvatarFile(),
563 updateGroup
.getExpirationTimer(),
564 updateGroup
.getIsAnnouncementGroup());
568 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
569 GroupInviteLinkUrl inviteLinkUrl
570 ) throws IOException
, InactiveGroupLinkException
{
571 return groupHelper
.joinGroup(inviteLinkUrl
);
574 private SendMessageResults
sendMessage(
575 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
576 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
577 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
578 long timestamp
= System
.currentTimeMillis();
579 messageBuilder
.withTimestamp(timestamp
);
580 for (final var recipient
: recipients
) {
581 if (recipient
instanceof RecipientIdentifier
.Single single
) {
582 final var recipientId
= resolveRecipient(single
);
583 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
584 results
.put(recipient
,
585 List
.of(SendMessageResult
.from(result
,
586 account
.getRecipientStore(),
587 account
.getRecipientStore()::resolveRecipientAddress
)));
588 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
589 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
590 results
.put(recipient
,
591 List
.of(SendMessageResult
.from(result
,
592 account
.getRecipientStore(),
593 account
.getRecipientStore()::resolveRecipientAddress
)));
594 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
595 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, group
.groupId());
596 results
.put(recipient
,
598 .map(sendMessageResult
-> SendMessageResult
.from(sendMessageResult
,
599 account
.getRecipientStore(),
600 account
.getRecipientStore()::resolveRecipientAddress
))
601 .collect(Collectors
.toList()));
604 return new SendMessageResults(timestamp
, results
);
607 private void sendTypingMessage(
608 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
609 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
610 final var timestamp
= System
.currentTimeMillis();
611 for (var recipient
: recipients
) {
612 if (recipient
instanceof RecipientIdentifier
.Single
) {
613 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
614 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
615 sendHelper
.sendTypingMessage(message
, recipientId
);
616 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
617 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
618 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
619 sendHelper
.sendGroupTypingMessage(message
, groupId
);
625 public void sendTypingMessage(
626 TypingAction action
, Set
<RecipientIdentifier
> recipients
627 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
628 sendTypingMessage(action
.toSignalService(), recipients
);
632 public void sendReadReceipt(
633 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
634 ) throws IOException
, UntrustedIdentityException
{
635 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
637 System
.currentTimeMillis());
639 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
643 public void sendViewedReceipt(
644 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
645 ) throws IOException
, UntrustedIdentityException
{
646 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
648 System
.currentTimeMillis());
650 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
654 public SendMessageResults
sendMessage(
655 Message message
, Set
<RecipientIdentifier
> recipients
656 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
657 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
658 applyMessage(messageBuilder
, message
);
659 return sendMessage(messageBuilder
, recipients
);
662 private void applyMessage(
663 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
664 ) throws AttachmentInvalidException
, IOException
{
665 messageBuilder
.withBody(message
.messageText());
666 final var attachments
= message
.attachments();
667 if (attachments
!= null) {
668 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
673 public SendMessageResults
sendRemoteDeleteMessage(
674 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
675 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
676 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
677 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
678 return sendMessage(messageBuilder
, recipients
);
682 public SendMessageResults
sendMessageReaction(
685 RecipientIdentifier
.Single targetAuthor
,
686 long targetSentTimestamp
,
687 Set
<RecipientIdentifier
> recipients
688 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
689 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
690 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
692 resolveSignalServiceAddress(targetAuthorRecipientId
),
693 targetSentTimestamp
);
694 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
695 return sendMessage(messageBuilder
, recipients
);
699 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
700 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
703 return sendMessage(messageBuilder
,
704 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
705 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
706 throw new AssertionError(e
);
708 for (var recipient
: recipients
) {
709 final var recipientId
= resolveRecipient(recipient
);
710 account
.getSessionStore().deleteAllSessions(recipientId
);
716 public void setContactName(
717 RecipientIdentifier
.Single recipient
, String name
718 ) throws NotMasterDeviceException
, IOException
{
719 if (!account
.isMasterDevice()) {
720 throw new NotMasterDeviceException();
722 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
726 public void setContactBlocked(
727 RecipientIdentifier
.Single recipient
, boolean blocked
728 ) throws NotMasterDeviceException
, IOException
{
729 if (!account
.isMasterDevice()) {
730 throw new NotMasterDeviceException();
732 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
733 // TODO cycle our profile key
734 syncHelper
.sendBlockedList();
738 public void setGroupBlocked(
739 final GroupId groupId
, final boolean blocked
740 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
741 if (!account
.isMasterDevice()) {
742 throw new NotMasterDeviceException();
744 groupHelper
.setGroupBlocked(groupId
, blocked
);
745 // TODO cycle our profile key
746 syncHelper
.sendBlockedList();
750 * Change the expiration timer for a contact
753 public void setExpirationTimer(
754 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
755 ) throws IOException
{
756 var recipientId
= resolveRecipient(recipient
);
757 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
758 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
760 sendMessage(messageBuilder
, Set
.of(recipient
));
761 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
762 throw new AssertionError(e
);
767 * Upload the sticker pack from path.
769 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
770 * @return if successful, returns the URL to install the sticker pack in the signal app
773 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
774 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
776 var messageSender
= dependencies
.getMessageSender();
778 var packKey
= KeyUtils
.createStickerUploadKey();
779 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
780 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
782 var sticker
= new Sticker(packId
, packKey
);
783 account
.getStickerStore().updateSticker(sticker
);
786 return new URI("https",
790 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
792 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
793 } catch (URISyntaxException e
) {
794 throw new AssertionError(e
);
799 public void requestAllSyncData() throws IOException
{
800 syncHelper
.requestAllSyncData();
801 retrieveRemoteStorage();
804 void retrieveRemoteStorage() throws IOException
{
805 if (account
.getStorageKey() != null) {
806 storageHelper
.readDataFromStorage();
810 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
811 final var address
= resolveSignalServiceAddress(recipientId
);
812 if (!address
.getNumber().isPresent()) {
815 final var number
= address
.getNumber().get();
816 final var uuid
= getRegisteredUser(number
);
817 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
820 private UUID
getRegisteredUser(final String number
) throws IOException
{
821 final Map
<String
, UUID
> uuidMap
;
823 uuidMap
= getRegisteredUsers(Set
.of(number
));
824 } catch (NumberFormatException e
) {
825 throw new IOException(number
, e
);
827 final var uuid
= uuidMap
.get(number
);
829 throw new IOException(number
, null);
834 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
835 final Map
<String
, UUID
> registeredUsers
;
837 registeredUsers
= dependencies
.getAccountManager()
838 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
840 serviceEnvironmentConfig
.getCdsMrenclave());
841 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
842 throw new IOException(e
);
845 // Store numbers as recipients so we have the number/uuid association
846 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
848 return registeredUsers
;
851 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
852 Set
<HandleAction
> queuedActions
= new HashSet
<>();
853 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
854 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
855 if (actions
!= null) {
856 queuedActions
.addAll(actions
);
859 handleQueuedActions(queuedActions
);
862 private List
<HandleAction
> retryFailedReceivedMessage(
863 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
865 var envelope
= cachedMessage
.loadEnvelope();
866 if (envelope
== null) {
867 cachedMessage
.delete();
871 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
872 final var actions
= result
.first();
873 final var exception
= result
.second();
875 if (exception
instanceof UntrustedIdentityException
) {
876 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
877 // Envelope is more than a month old, cleaning up.
878 cachedMessage
.delete();
881 if (!envelope
.hasSourceUuid()) {
882 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
883 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
885 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
886 } catch (IOException ioException
) {
887 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
893 // If successful and for all other errors that are not recoverable, delete the cached message
894 cachedMessage
.delete();
899 public void addReceiveHandler(final ReceiveMessageHandler handler
) {
900 if (isReceivingSynchronous
) {
901 throw new IllegalStateException("Already receiving message synchronously.");
903 synchronized (messageHandlers
) {
904 messageHandlers
.add(handler
);
906 startReceiveThreadIfRequired();
910 private void startReceiveThreadIfRequired() {
911 if (receiveThread
!= null) {
914 receiveThread
= new Thread(() -> {
915 while (!Thread
.interrupted()) {
917 receiveMessagesInternal(1L, TimeUnit
.HOURS
, false, (envelope
, e
) -> {
918 synchronized (messageHandlers
) {
919 for (ReceiveMessageHandler h
: messageHandlers
) {
921 h
.handleMessage(envelope
, e
);
922 } catch (Exception ex
) {
923 logger
.warn("Message handler failed, ignoring", ex
);
929 } catch (IOException e
) {
930 logger
.warn("Receiving messages failed, retrying", e
);
933 hasCaughtUpWithOldMessages
= false;
934 synchronized (messageHandlers
) {
935 receiveThread
= null;
937 // Check if in the meantime another handler has been registered
938 if (!messageHandlers
.isEmpty()) {
939 startReceiveThreadIfRequired();
944 receiveThread
.start();
948 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
950 synchronized (messageHandlers
) {
951 thread
= receiveThread
;
952 receiveThread
= null;
953 messageHandlers
.remove(handler
);
954 if (!messageHandlers
.isEmpty() || isReceivingSynchronous
) {
959 stopReceiveThread(thread
);
962 private void stopReceiveThread(final Thread thread
) {
966 } catch (InterruptedException ignored
) {
971 public boolean isReceiving() {
972 if (isReceivingSynchronous
) {
975 synchronized (messageHandlers
) {
976 return messageHandlers
.size() > 0;
981 public void receiveMessages(long timeout
, TimeUnit unit
, ReceiveMessageHandler handler
) throws IOException
{
982 receiveMessages(timeout
, unit
, true, handler
);
986 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
987 receiveMessages(1L, TimeUnit
.HOURS
, false, handler
);
990 private void receiveMessages(
991 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
992 ) throws IOException
{
994 throw new IllegalStateException("Already receiving message.");
996 isReceivingSynchronous
= true;
997 receiveThread
= Thread
.currentThread();
999 receiveMessagesInternal(timeout
, unit
, returnOnTimeout
, handler
);
1001 receiveThread
= null;
1002 hasCaughtUpWithOldMessages
= false;
1003 isReceivingSynchronous
= false;
1007 private void receiveMessagesInternal(
1008 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1009 ) throws IOException
{
1010 retryFailedReceivedMessages(handler
);
1012 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1014 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1015 signalWebSocket
.connect();
1017 hasCaughtUpWithOldMessages
= false;
1018 var backOffCounter
= 0;
1019 final var MAX_BACKOFF_COUNTER
= 9;
1021 while (!Thread
.interrupted()) {
1022 SignalServiceEnvelope envelope
;
1023 final CachedMessage
[] cachedMessage
= {null};
1024 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1025 logger
.debug("Checking for new message from server");
1027 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1028 final var recipientId
= envelope1
.hasSourceUuid()
1029 ?
resolveRecipient(envelope1
.getSourceAddress())
1031 // store message on disk, before acknowledging receipt to the server
1032 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1036 if (result
.isPresent()) {
1037 envelope
= result
.get();
1038 logger
.debug("New message received from server");
1040 logger
.debug("Received indicator that server queue is empty");
1041 handleQueuedActions(queuedActions
);
1042 queuedActions
.clear();
1044 hasCaughtUpWithOldMessages
= true;
1045 synchronized (this) {
1049 // Continue to wait another timeout for new messages
1052 } catch (AssertionError e
) {
1053 if (e
.getCause() instanceof InterruptedException
) {
1054 Thread
.currentThread().interrupt();
1059 } catch (IOException e
) {
1060 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1061 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1062 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1063 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1064 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1066 Thread
.sleep(sleepMilliseconds
);
1067 } catch (InterruptedException interruptedException
) {
1070 hasCaughtUpWithOldMessages
= false;
1071 signalWebSocket
.connect();
1075 } catch (TimeoutException e
) {
1077 if (returnOnTimeout
) return;
1081 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
1082 queuedActions
.addAll(result
.first());
1083 final var exception
= result
.second();
1085 if (hasCaughtUpWithOldMessages
) {
1086 handleQueuedActions(queuedActions
);
1087 queuedActions
.clear();
1089 if (cachedMessage
[0] != null) {
1090 if (exception
instanceof UntrustedIdentityException
) {
1091 logger
.debug("Keeping message with untrusted identity in message cache");
1092 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1093 final var recipientId
= resolveRecipient(address
);
1094 if (!envelope
.hasSourceUuid()) {
1096 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1097 } catch (IOException ioException
) {
1098 logger
.warn("Failed to move cached message to recipient folder: {}",
1099 ioException
.getMessage());
1103 cachedMessage
[0].delete();
1107 handleQueuedActions(queuedActions
);
1108 queuedActions
.clear();
1112 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1113 this.ignoreAttachments
= ignoreAttachments
;
1117 public boolean hasCaughtUpWithOldMessages() {
1118 return hasCaughtUpWithOldMessages
;
1121 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1122 logger
.debug("Handling message actions");
1123 var interrupted
= false;
1124 for (var action
: queuedActions
) {
1126 action
.execute(context
);
1127 } catch (Throwable e
) {
1128 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1129 && e
.getCause() instanceof InterruptedException
) {
1133 logger
.warn("Message action failed.", e
);
1137 Thread
.currentThread().interrupt();
1142 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1143 final RecipientId recipientId
;
1145 recipientId
= resolveRecipient(recipient
);
1146 } catch (IOException e
) {
1149 return contactHelper
.isContactBlocked(recipientId
);
1153 public File
getAttachmentFile(String attachmentId
) {
1154 return attachmentHelper
.getAttachmentFile(attachmentId
);
1158 public void sendContacts() throws IOException
{
1159 syncHelper
.sendContacts();
1163 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1164 return account
.getContactStore()
1167 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1168 .collect(Collectors
.toList());
1172 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1173 final RecipientId recipientId
;
1175 recipientId
= resolveRecipient(recipient
);
1176 } catch (IOException e
) {
1180 final var contact
= account
.getContactStore().getContact(recipientId
);
1181 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1182 return contact
.getName();
1185 final var profile
= getRecipientProfile(recipientId
);
1186 if (profile
!= null) {
1187 return profile
.getDisplayName();
1194 public Group
getGroup(GroupId groupId
) {
1195 return toGroup(groupHelper
.getGroup(groupId
));
1198 private GroupInfo
getGroupInfo(GroupId groupId
) {
1199 return groupHelper
.getGroup(groupId
);
1203 public List
<Identity
> getIdentities() {
1204 return account
.getIdentityKeyStore()
1207 .map(this::toIdentity
)
1208 .collect(Collectors
.toList());
1211 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1212 if (identityInfo
== null) {
1216 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1217 final var scannableFingerprint
= identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1218 identityInfo
.getIdentityKey());
1219 return new Identity(address
,
1220 identityInfo
.getIdentityKey(),
1221 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1222 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1223 identityInfo
.getTrustLevel(),
1224 identityInfo
.getDateAdded());
1228 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1229 IdentityInfo identity
;
1231 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1232 } catch (IOException e
) {
1235 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1239 * Trust this the identity with this fingerprint
1241 * @param recipient username of the identity
1242 * @param fingerprint Fingerprint
1245 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1246 RecipientId recipientId
;
1248 recipientId
= resolveRecipient(recipient
);
1249 } catch (IOException e
) {
1252 return identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1256 * Trust this the identity with this safety number
1258 * @param recipient username of the identity
1259 * @param safetyNumber Safety number
1262 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1263 RecipientId recipientId
;
1265 recipientId
= resolveRecipient(recipient
);
1266 } catch (IOException e
) {
1269 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1273 * Trust this the identity with this scannable safety number
1275 * @param recipient username of the identity
1276 * @param safetyNumber Scannable safety number
1279 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1280 RecipientId recipientId
;
1282 recipientId
= resolveRecipient(recipient
);
1283 } catch (IOException e
) {
1286 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1290 * Trust all keys of this identity without verification
1292 * @param recipient username of the identity
1295 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1296 RecipientId recipientId
;
1298 recipientId
= resolveRecipient(recipient
);
1299 } catch (IOException e
) {
1302 return identityHelper
.trustIdentityAllKeys(recipientId
);
1305 private void handleIdentityFailure(
1306 final RecipientId recipientId
,
1307 final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
.IdentityFailure identityFailure
1309 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1312 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1313 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1314 if (address
.getUuid().isPresent()) {
1315 return address
.toSignalServiceAddress();
1318 // Address in recipient store doesn't have a uuid, this shouldn't happen
1319 // Try to retrieve the uuid from the server
1320 final var number
= address
.getNumber().get();
1323 uuid
= getRegisteredUser(number
);
1324 } catch (IOException e
) {
1325 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1326 // Return SignalServiceAddress with unknown UUID
1327 return address
.toSignalServiceAddress();
1329 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1332 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
1333 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1334 for (var number
: recipients
) {
1335 final var recipientId
= resolveRecipient(number
);
1336 recipientIds
.add(recipientId
);
1338 return recipientIds
;
1341 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
1342 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1343 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid());
1345 final var number
= ((RecipientIdentifier
.Number
) recipient
).number();
1346 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1348 return getRegisteredUser(number
);
1349 } catch (IOException e
) {
1356 private RecipientId
resolveRecipient(RecipientAddress address
) {
1357 return account
.getRecipientStore().resolveRecipient(address
);
1360 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1361 return account
.getRecipientStore().resolveRecipient(address
);
1364 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1365 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1369 public void close() throws IOException
{
1373 private void close(boolean closeAccount
) throws IOException
{
1375 synchronized (messageHandlers
) {
1376 messageHandlers
.clear();
1377 thread
= receiveThread
;
1378 receiveThread
= null;
1380 if (thread
!= null) {
1381 stopReceiveThread(thread
);
1383 executor
.shutdown();
1385 dependencies
.getSignalWebSocket().disconnect();
1387 if (closeAccount
&& account
!= null) {