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
.Message
;
24 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
25 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
26 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
27 import org
.asamk
.signal
.manager
.api
.TypingAction
;
28 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
29 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
30 import org
.asamk
.signal
.manager
.groups
.GroupId
;
31 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
32 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
33 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
34 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
35 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
36 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
37 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
38 import org
.asamk
.signal
.manager
.helper
.AttachmentHelper
;
39 import org
.asamk
.signal
.manager
.helper
.ContactHelper
;
40 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
41 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
42 import org
.asamk
.signal
.manager
.helper
.IncomingMessageHandler
;
43 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
44 import org
.asamk
.signal
.manager
.helper
.PreKeyHelper
;
45 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
46 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
47 import org
.asamk
.signal
.manager
.helper
.StorageHelper
;
48 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
49 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
50 import org
.asamk
.signal
.manager
.jobs
.Context
;
51 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
52 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
53 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
54 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
57 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
58 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
59 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
60 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
61 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
62 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
63 import org
.asamk
.signal
.manager
.util
.Utils
;
64 import org
.slf4j
.Logger
;
65 import org
.slf4j
.LoggerFactory
;
66 import org
.whispersystems
.libsignal
.IdentityKey
;
67 import org
.whispersystems
.libsignal
.InvalidKeyException
;
68 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
69 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
70 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
71 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
72 import org
.whispersystems
.libsignal
.util
.Pair
;
73 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
74 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
75 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
76 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
78 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
79 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
80 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
81 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
82 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
83 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
84 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
85 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
86 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
87 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
88 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
89 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
90 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
91 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
92 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
93 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
96 import java
.io
.IOException
;
98 import java
.net
.URISyntaxException
;
99 import java
.net
.URLEncoder
;
100 import java
.nio
.charset
.StandardCharsets
;
101 import java
.security
.SignatureException
;
102 import java
.util
.Arrays
;
103 import java
.util
.Collection
;
104 import java
.util
.Date
;
105 import java
.util
.HashMap
;
106 import java
.util
.HashSet
;
107 import java
.util
.List
;
108 import java
.util
.Map
;
109 import java
.util
.Set
;
110 import java
.util
.UUID
;
111 import java
.util
.concurrent
.ExecutorService
;
112 import java
.util
.concurrent
.Executors
;
113 import java
.util
.concurrent
.TimeUnit
;
114 import java
.util
.concurrent
.TimeoutException
;
115 import java
.util
.concurrent
.locks
.ReentrantLock
;
116 import java
.util
.function
.Function
;
117 import java
.util
.stream
.Collectors
;
119 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
121 public class ManagerImpl
implements Manager
{
123 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
125 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
126 private final SignalDependencies dependencies
;
128 private SignalAccount account
;
130 private final ExecutorService executor
= Executors
.newCachedThreadPool();
132 private final ProfileHelper profileHelper
;
133 private final PinHelper pinHelper
;
134 private final StorageHelper storageHelper
;
135 private final SendHelper sendHelper
;
136 private final SyncHelper syncHelper
;
137 private final AttachmentHelper attachmentHelper
;
138 private final GroupHelper groupHelper
;
139 private final ContactHelper contactHelper
;
140 private final IncomingMessageHandler incomingMessageHandler
;
141 private final PreKeyHelper preKeyHelper
;
143 private final Context context
;
144 private boolean hasCaughtUpWithOldMessages
= false;
147 SignalAccount account
,
148 PathConfig pathConfig
,
149 ServiceEnvironmentConfig serviceEnvironmentConfig
,
152 this.account
= account
;
153 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
155 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
156 account
.getUsername(),
157 account
.getPassword(),
158 account
.getDeviceId());
159 final var sessionLock
= new SignalSessionLock() {
160 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
163 public Lock
acquire() {
165 return LEGACY_LOCK
::unlock
;
168 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
171 account
.getSignalProtocolStore(),
174 final var avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
175 final var attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
176 final var stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
178 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
179 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
180 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
181 account
.getProfileStore()::getProfileKey
,
182 this::getRecipientProfile
,
183 this::getSenderCertificate
);
184 this.profileHelper
= new ProfileHelper(account
,
187 account
.getProfileStore()::getProfileKey
,
188 unidentifiedAccessHelper
::getAccessFor
,
189 this::resolveSignalServiceAddress
);
190 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
191 this::getRecipientProfile
,
192 account
::getSelfRecipientId
,
193 dependencies
.getGroupsV2Operations(),
194 dependencies
.getGroupsV2Api(),
195 this::resolveSignalServiceAddress
);
196 this.sendHelper
= new SendHelper(account
,
198 unidentifiedAccessHelper
,
199 this::resolveSignalServiceAddress
,
200 account
.getRecipientStore(),
201 this::handleIdentityFailure
,
203 this::refreshRegisteredUser
);
204 this.groupHelper
= new GroupHelper(account
,
210 this::resolveSignalServiceAddress
,
211 account
.getRecipientStore());
212 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
213 this.contactHelper
= new ContactHelper(account
);
214 this.syncHelper
= new SyncHelper(account
,
219 this::resolveSignalServiceAddress
);
220 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
222 this.context
= new Context(account
,
231 var jobExecutor
= new JobExecutor(context
);
233 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
235 account
.getRecipientStore(),
236 this::resolveSignalServiceAddress
,
241 this::getRecipientProfile
,
246 public String
getSelfNumber() {
247 return account
.getUsername();
251 public void checkAccountState() throws IOException
{
252 if (account
.getLastReceiveTimestamp() == 0) {
253 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
255 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
256 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
259 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
263 preKeyHelper
.refreshPreKeysIfNecessary();
264 if (account
.getUuid() == null) {
265 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
267 updateAccountAttributes(null);
271 * This is used for checking a set of phone numbers for registration on Signal
273 * @param numbers The set of phone number in question
274 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
275 * @throws IOException if its unable to get the contacts to check if they're registered
278 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
279 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
281 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
282 } catch (InvalidNumberException e
) {
287 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
288 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
290 .filter(s
-> !s
.isEmpty())
291 .collect(Collectors
.toSet()));
293 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
294 final var number
= canonicalizedNumbers
.get(n
);
295 final var uuid
= registeredUsers
.get(number
);
296 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
301 public void updateAccountAttributes(String deviceName
) throws IOException
{
302 final String encryptedDeviceName
;
303 if (deviceName
== null) {
304 encryptedDeviceName
= account
.getEncryptedDeviceName();
306 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
307 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
308 account
.setEncryptedDeviceName(encryptedDeviceName
);
310 dependencies
.getAccountManager()
311 .setAccountAttributes(encryptedDeviceName
,
313 account
.getLocalRegistrationId(),
316 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
317 account
.getSelfUnidentifiedAccessKey(),
318 account
.isUnrestrictedUnidentifiedAccess(),
320 account
.isDiscoverableByPhoneNumber());
324 public void updateConfiguration(
325 final Boolean readReceipts
,
326 final Boolean unidentifiedDeliveryIndicators
,
327 final Boolean typingIndicators
,
328 final Boolean linkPreviews
329 ) throws IOException
, NotMasterDeviceException
{
330 if (!account
.isMasterDevice()) {
331 throw new NotMasterDeviceException();
334 final var configurationStore
= account
.getConfigurationStore();
335 if (readReceipts
!= null) {
336 configurationStore
.setReadReceipts(readReceipts
);
338 if (unidentifiedDeliveryIndicators
!= null) {
339 configurationStore
.setUnidentifiedDeliveryIndicators(unidentifiedDeliveryIndicators
);
341 if (typingIndicators
!= null) {
342 configurationStore
.setTypingIndicators(typingIndicators
);
344 if (linkPreviews
!= null) {
345 configurationStore
.setLinkPreviews(linkPreviews
);
347 syncHelper
.sendConfigurationMessage();
351 public List
<Boolean
> getConfiguration() throws IOException
, NotMasterDeviceException
{
352 if (!account
.isMasterDevice()) {
353 throw new NotMasterDeviceException();
355 final var configurationStore
= account
.getConfigurationStore();
356 final Boolean readReceipts
= configurationStore
.getReadReceipts();
357 final Boolean unidentifiedDeliveryIndicators
= configurationStore
.getUnidentifiedDeliveryIndicators();
358 final Boolean typingIndicators
= configurationStore
.getTypingIndicators();
359 final Boolean linkPreviews
= configurationStore
.getLinkPreviews();
360 return List
.of(readReceipts
, unidentifiedDeliveryIndicators
, typingIndicators
, linkPreviews
);
364 * @param givenName if null, the previous givenName will be kept
365 * @param familyName if null, the previous familyName will be kept
366 * @param about if null, the previous about text will be kept
367 * @param aboutEmoji if null, the previous about emoji will be kept
368 * @param avatar if avatar is null the image from the local avatar store is used (if present),
371 public void setProfile(
372 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
373 ) throws IOException
{
374 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
375 syncHelper
.sendSyncFetchProfileMessage();
379 public void unregister() throws IOException
{
380 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
381 // If this is the master device, other users can't send messages to this number anymore.
382 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
383 dependencies
.getAccountManager().setGcmId(Optional
.absent());
385 account
.setRegistered(false);
389 public void deleteAccount() throws IOException
{
391 pinHelper
.removeRegistrationLockPin();
392 } catch (UnauthenticatedResponseException e
) {
393 logger
.warn("Failed to remove registration lock pin");
395 account
.setRegistrationLockPin(null, null);
397 dependencies
.getAccountManager().deleteAccount();
399 account
.setRegistered(false);
403 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
404 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
408 public List
<Device
> getLinkedDevices() throws IOException
{
409 var devices
= dependencies
.getAccountManager().getDevices();
410 account
.setMultiDevice(devices
.size() > 1);
411 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
412 return devices
.stream().map(d
-> {
413 String deviceName
= d
.getName();
414 if (deviceName
!= null) {
416 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
417 } catch (IOException e
) {
418 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
421 return new Device(d
.getId(),
425 d
.getId() == account
.getDeviceId());
426 }).collect(Collectors
.toList());
430 public void removeLinkedDevices(long deviceId
) throws IOException
{
431 dependencies
.getAccountManager().removeDevice(deviceId
);
432 var devices
= dependencies
.getAccountManager().getDevices();
433 account
.setMultiDevice(devices
.size() > 1);
437 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
438 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
440 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
443 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
444 var identityKeyPair
= account
.getIdentityKeyPair();
445 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
447 dependencies
.getAccountManager()
448 .addDevice(deviceIdentifier
,
451 Optional
.of(account
.getProfileKey().serialize()),
453 account
.setMultiDevice(true);
457 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
458 if (!account
.isMasterDevice()) {
459 throw new RuntimeException("Only master device can set a PIN");
461 if (pin
.isPresent()) {
462 final var masterKey
= account
.getPinMasterKey() != null
463 ? account
.getPinMasterKey()
464 : KeyUtils
.createMasterKey();
466 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
468 account
.setRegistrationLockPin(pin
.get(), masterKey
);
471 pinHelper
.removeRegistrationLockPin();
473 account
.setRegistrationLockPin(null, null);
477 void refreshPreKeys() throws IOException
{
478 preKeyHelper
.refreshPreKeys();
482 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
483 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
486 private Profile
getRecipientProfile(RecipientId recipientId
) {
487 return profileHelper
.getRecipientProfile(recipientId
);
491 public List
<Group
> getGroups() {
492 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
495 private Group
toGroup(final GroupInfo groupInfo
) {
496 if (groupInfo
== null) {
500 return new Group(groupInfo
.getGroupId(),
501 groupInfo
.getTitle(),
502 groupInfo
.getDescription(),
503 groupInfo
.getGroupInviteLink(),
504 groupInfo
.getMembers()
506 .map(account
.getRecipientStore()::resolveRecipientAddress
)
507 .collect(Collectors
.toSet()),
508 groupInfo
.getPendingMembers()
510 .map(account
.getRecipientStore()::resolveRecipientAddress
)
511 .collect(Collectors
.toSet()),
512 groupInfo
.getRequestingMembers()
514 .map(account
.getRecipientStore()::resolveRecipientAddress
)
515 .collect(Collectors
.toSet()),
516 groupInfo
.getAdminMembers()
518 .map(account
.getRecipientStore()::resolveRecipientAddress
)
519 .collect(Collectors
.toSet()),
520 groupInfo
.isBlocked(),
521 groupInfo
.getMessageExpirationTime(),
522 groupInfo
.isAnnouncementGroup(),
523 groupInfo
.isMember(account
.getSelfRecipientId()));
527 public SendGroupMessageResults
quitGroup(
528 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
529 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
530 final var newAdmins
= resolveRecipients(groupAdmins
);
531 return groupHelper
.quitGroup(groupId
, newAdmins
);
535 public void deleteGroup(GroupId groupId
) throws IOException
{
536 groupHelper
.deleteGroup(groupId
);
540 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
541 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
542 ) throws IOException
, AttachmentInvalidException
{
543 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
547 public SendGroupMessageResults
updateGroup(
551 Set
<RecipientIdentifier
.Single
> members
,
552 Set
<RecipientIdentifier
.Single
> removeMembers
,
553 Set
<RecipientIdentifier
.Single
> admins
,
554 Set
<RecipientIdentifier
.Single
> removeAdmins
,
555 boolean resetGroupLink
,
556 GroupLinkState groupLinkState
,
557 GroupPermission addMemberPermission
,
558 GroupPermission editDetailsPermission
,
560 Integer expirationTimer
,
561 Boolean isAnnouncementGroup
562 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
563 return groupHelper
.updateGroup(groupId
,
566 members
== null ?
null : resolveRecipients(members
),
567 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
568 admins
== null ?
null : resolveRecipients(admins
),
569 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
573 editDetailsPermission
,
576 isAnnouncementGroup
);
580 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
581 GroupInviteLinkUrl inviteLinkUrl
582 ) throws IOException
, GroupLinkNotActiveException
{
583 return groupHelper
.joinGroup(inviteLinkUrl
);
586 private SendMessageResults
sendMessage(
587 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
588 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
589 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
590 long timestamp
= System
.currentTimeMillis();
591 messageBuilder
.withTimestamp(timestamp
);
592 for (final var recipient
: recipients
) {
593 if (recipient
instanceof RecipientIdentifier
.Single
) {
594 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
595 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
596 results
.put(recipient
, List
.of(result
));
597 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
598 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
599 results
.put(recipient
, List
.of(result
));
600 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
601 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
602 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
603 results
.put(recipient
, result
);
606 return new SendMessageResults(timestamp
, results
);
609 private void sendTypingMessage(
610 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
611 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
612 final var timestamp
= System
.currentTimeMillis();
613 for (var recipient
: recipients
) {
614 if (recipient
instanceof RecipientIdentifier
.Single
) {
615 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
616 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
617 sendHelper
.sendTypingMessage(message
, recipientId
);
618 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
619 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
620 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
621 sendHelper
.sendGroupTypingMessage(message
, groupId
);
627 public void sendTypingMessage(
628 TypingAction action
, Set
<RecipientIdentifier
> recipients
629 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
630 sendTypingMessage(action
.toSignalService(), recipients
);
634 public void sendReadReceipt(
635 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
636 ) throws IOException
, UntrustedIdentityException
{
637 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
639 System
.currentTimeMillis());
641 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
645 public void sendViewedReceipt(
646 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
647 ) throws IOException
, UntrustedIdentityException
{
648 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
650 System
.currentTimeMillis());
652 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
656 public SendMessageResults
sendMessage(
657 Message message
, Set
<RecipientIdentifier
> recipients
658 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
659 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
660 applyMessage(messageBuilder
, message
);
661 return sendMessage(messageBuilder
, recipients
);
664 private void applyMessage(
665 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
666 ) throws AttachmentInvalidException
, IOException
{
667 messageBuilder
.withBody(message
.getMessageText());
668 final var attachments
= message
.getAttachments();
669 if (attachments
!= null) {
670 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
675 public SendMessageResults
sendRemoteDeleteMessage(
676 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
677 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
678 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
679 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
680 return sendMessage(messageBuilder
, recipients
);
684 public SendMessageResults
sendMessageReaction(
687 RecipientIdentifier
.Single targetAuthor
,
688 long targetSentTimestamp
,
689 Set
<RecipientIdentifier
> recipients
690 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
691 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
692 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
694 resolveSignalServiceAddress(targetAuthorRecipientId
),
695 targetSentTimestamp
);
696 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
697 return sendMessage(messageBuilder
, recipients
);
701 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
702 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
705 return sendMessage(messageBuilder
,
706 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
707 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
708 throw new AssertionError(e
);
710 for (var recipient
: recipients
) {
711 final var recipientId
= resolveRecipient(recipient
);
712 account
.getSessionStore().deleteAllSessions(recipientId
);
718 public void setContactName(
719 RecipientIdentifier
.Single recipient
, String name
720 ) throws NotMasterDeviceException
, UnregisteredUserException
{
721 if (!account
.isMasterDevice()) {
722 throw new NotMasterDeviceException();
724 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
728 public void setContactBlocked(
729 RecipientIdentifier
.Single recipient
, boolean blocked
730 ) throws NotMasterDeviceException
, IOException
{
731 if (!account
.isMasterDevice()) {
732 throw new NotMasterDeviceException();
734 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
735 // TODO cycle our profile key
736 syncHelper
.sendBlockedList();
740 public void setGroupBlocked(
741 final GroupId groupId
, final boolean blocked
742 ) throws GroupNotFoundException
, IOException
{
743 groupHelper
.setGroupBlocked(groupId
, blocked
);
744 // TODO cycle our profile key
745 syncHelper
.sendBlockedList();
749 * Change the expiration timer for a contact
752 public void setExpirationTimer(
753 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
754 ) throws IOException
{
755 var recipientId
= resolveRecipient(recipient
);
756 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
757 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
759 sendMessage(messageBuilder
, Set
.of(recipient
));
760 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
761 throw new AssertionError(e
);
766 * Upload the sticker pack from path.
768 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
769 * @return if successful, returns the URL to install the sticker pack in the signal app
772 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
773 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
775 var messageSender
= dependencies
.getMessageSender();
777 var packKey
= KeyUtils
.createStickerUploadKey();
778 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
779 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
781 var sticker
= new Sticker(packId
, packKey
);
782 account
.getStickerStore().updateSticker(sticker
);
785 return new URI("https",
789 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
791 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
792 } catch (URISyntaxException e
) {
793 throw new AssertionError(e
);
798 public void requestAllSyncData() throws IOException
{
799 syncHelper
.requestAllSyncData();
800 retrieveRemoteStorage();
803 void retrieveRemoteStorage() throws IOException
{
804 if (account
.getStorageKey() != null) {
805 storageHelper
.readDataFromStorage();
809 private byte[] getSenderCertificate() {
812 if (account
.isPhoneNumberShared()) {
813 certificate
= dependencies
.getAccountManager().getSenderCertificate();
815 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
817 } catch (IOException e
) {
818 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
821 // TODO cache for a day
825 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
826 final var address
= resolveSignalServiceAddress(recipientId
);
827 if (!address
.getNumber().isPresent()) {
830 final var number
= address
.getNumber().get();
831 final var uuid
= getRegisteredUser(number
);
832 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
835 private UUID
getRegisteredUser(final String number
) throws IOException
{
836 final Map
<String
, UUID
> uuidMap
;
838 uuidMap
= getRegisteredUsers(Set
.of(number
));
839 } catch (NumberFormatException e
) {
840 throw new UnregisteredUserException(number
, e
);
842 final var uuid
= uuidMap
.get(number
);
844 throw new UnregisteredUserException(number
, null);
849 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
850 final Map
<String
, UUID
> registeredUsers
;
852 registeredUsers
= dependencies
.getAccountManager()
853 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
855 serviceEnvironmentConfig
.getCdsMrenclave());
856 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
857 throw new IOException(e
);
860 // Store numbers as recipients so we have the number/uuid association
861 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
863 return registeredUsers
;
866 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
867 Set
<HandleAction
> queuedActions
= new HashSet
<>();
868 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
869 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
870 if (actions
!= null) {
871 queuedActions
.addAll(actions
);
874 handleQueuedActions(queuedActions
);
877 private List
<HandleAction
> retryFailedReceivedMessage(
878 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
880 var envelope
= cachedMessage
.loadEnvelope();
881 if (envelope
== null) {
882 cachedMessage
.delete();
886 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
887 final var actions
= result
.first();
888 final var exception
= result
.second();
890 if (exception
instanceof UntrustedIdentityException
) {
891 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
892 // Envelope is more than a month old, cleaning up.
893 cachedMessage
.delete();
896 if (!envelope
.hasSourceUuid()) {
897 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
898 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
900 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
901 } catch (IOException ioException
) {
902 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
908 // If successful and for all other errors that are not recoverable, delete the cached message
909 cachedMessage
.delete();
914 public void receiveMessages(
917 boolean returnOnTimeout
,
918 boolean ignoreAttachments
,
919 ReceiveMessageHandler handler
920 ) throws IOException
{
921 retryFailedReceivedMessages(handler
, ignoreAttachments
);
923 Set
<HandleAction
> queuedActions
= new HashSet
<>();
925 final var signalWebSocket
= dependencies
.getSignalWebSocket();
926 signalWebSocket
.connect();
928 hasCaughtUpWithOldMessages
= false;
930 while (!Thread
.interrupted()) {
931 SignalServiceEnvelope envelope
;
932 final CachedMessage
[] cachedMessage
= {null};
933 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
934 logger
.debug("Checking for new message from server");
936 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
937 final var recipientId
= envelope1
.hasSourceUuid()
938 ?
resolveRecipient(envelope1
.getSourceAddress())
940 // store message on disk, before acknowledging receipt to the server
941 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
943 if (result
.isPresent()) {
944 envelope
= result
.get();
945 logger
.debug("New message received from server");
947 logger
.debug("Received indicator that server queue is empty");
948 handleQueuedActions(queuedActions
);
949 queuedActions
.clear();
951 hasCaughtUpWithOldMessages
= true;
952 synchronized (this) {
956 // Continue to wait another timeout for new messages
959 } catch (AssertionError e
) {
960 if (e
.getCause() instanceof InterruptedException
) {
961 Thread
.currentThread().interrupt();
966 } catch (WebSocketUnavailableException e
) {
967 logger
.debug("Pipe unexpectedly unavailable, connecting");
968 signalWebSocket
.connect();
970 } catch (TimeoutException e
) {
971 if (returnOnTimeout
) return;
975 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
976 queuedActions
.addAll(result
.first());
977 final var exception
= result
.second();
979 if (hasCaughtUpWithOldMessages
) {
980 handleQueuedActions(queuedActions
);
982 if (cachedMessage
[0] != null) {
983 if (exception
instanceof UntrustedIdentityException
) {
984 final var address
= ((UntrustedIdentityException
) exception
).getSender();
985 final var recipientId
= resolveRecipient(address
);
986 if (!envelope
.hasSourceUuid()) {
988 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
989 } catch (IOException ioException
) {
990 logger
.warn("Failed to move cached message to recipient folder: {}",
991 ioException
.getMessage());
995 cachedMessage
[0].delete();
999 handleQueuedActions(queuedActions
);
1003 public boolean hasCaughtUpWithOldMessages() {
1004 return hasCaughtUpWithOldMessages
;
1007 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1008 var interrupted
= false;
1009 for (var action
: queuedActions
) {
1011 action
.execute(context
);
1012 } catch (Throwable e
) {
1013 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1014 && e
.getCause() instanceof InterruptedException
) {
1018 logger
.warn("Message action failed.", e
);
1022 Thread
.currentThread().interrupt();
1027 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1028 final RecipientId recipientId
;
1030 recipientId
= resolveRecipient(recipient
);
1031 } catch (UnregisteredUserException e
) {
1034 return contactHelper
.isContactBlocked(recipientId
);
1038 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
1039 return attachmentHelper
.getAttachmentFile(attachmentId
);
1043 public void sendContacts() throws IOException
{
1044 syncHelper
.sendContacts();
1048 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1049 return account
.getContactStore()
1052 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1053 .collect(Collectors
.toList());
1057 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1058 final RecipientId recipientId
;
1060 recipientId
= resolveRecipient(recipient
);
1061 } catch (UnregisteredUserException e
) {
1065 final var contact
= account
.getContactStore().getContact(recipientId
);
1066 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1067 return contact
.getName();
1070 final var profile
= getRecipientProfile(recipientId
);
1071 if (profile
!= null) {
1072 return profile
.getDisplayName();
1079 public Group
getGroup(GroupId groupId
) {
1080 return toGroup(groupHelper
.getGroup(groupId
));
1083 public GroupInfo
getGroupInfo(GroupId groupId
) {
1084 return groupHelper
.getGroup(groupId
);
1088 public List
<Identity
> getIdentities() {
1089 return account
.getIdentityKeyStore()
1092 .map(this::toIdentity
)
1093 .collect(Collectors
.toList());
1096 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1097 if (identityInfo
== null) {
1101 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1102 return new Identity(address
,
1103 identityInfo
.getIdentityKey(),
1104 computeSafetyNumber(address
.toSignalServiceAddress(), identityInfo
.getIdentityKey()),
1105 computeSafetyNumberForScanning(address
.toSignalServiceAddress(), identityInfo
.getIdentityKey()),
1106 identityInfo
.getTrustLevel(),
1107 identityInfo
.getDateAdded());
1111 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1112 IdentityInfo identity
;
1114 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1115 } catch (UnregisteredUserException e
) {
1118 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1122 * Trust this the identity with this fingerprint
1124 * @param recipient username of the identity
1125 * @param fingerprint Fingerprint
1128 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1129 RecipientId recipientId
;
1131 recipientId
= resolveRecipient(recipient
);
1132 } catch (UnregisteredUserException e
) {
1135 return trustIdentity(recipientId
,
1136 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1137 TrustLevel
.TRUSTED_VERIFIED
);
1141 * Trust this the identity with this safety number
1143 * @param recipient username of the identity
1144 * @param safetyNumber Safety number
1147 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1148 RecipientId recipientId
;
1150 recipientId
= resolveRecipient(recipient
);
1151 } catch (UnregisteredUserException e
) {
1154 var address
= resolveSignalServiceAddress(recipientId
);
1155 return trustIdentity(recipientId
,
1156 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1157 TrustLevel
.TRUSTED_VERIFIED
);
1161 * Trust this the identity with this scannable safety number
1163 * @param recipient username of the identity
1164 * @param safetyNumber Scannable safety number
1167 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1168 RecipientId recipientId
;
1170 recipientId
= resolveRecipient(recipient
);
1171 } catch (UnregisteredUserException e
) {
1174 var address
= resolveSignalServiceAddress(recipientId
);
1175 return trustIdentity(recipientId
, identityKey
-> {
1176 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1178 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1179 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1182 }, TrustLevel
.TRUSTED_VERIFIED
);
1186 * Trust all keys of this identity without verification
1188 * @param recipient username of the identity
1191 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1192 RecipientId recipientId
;
1194 recipientId
= resolveRecipient(recipient
);
1195 } catch (UnregisteredUserException e
) {
1198 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1201 private boolean trustIdentity(
1202 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1204 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1205 if (identity
== null) {
1209 if (!verifier
.apply(identity
.getIdentityKey())) {
1213 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1215 var address
= resolveSignalServiceAddress(recipientId
);
1216 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1217 } catch (IOException e
) {
1218 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1224 private void handleIdentityFailure(
1225 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1227 final var identityKey
= identityFailure
.getIdentityKey();
1228 if (identityKey
!= null) {
1229 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1231 account
.getSessionStore().archiveSessions(recipientId
);
1234 // Retrieve profile to get the current identity key from the server
1235 profileHelper
.refreshRecipientProfile(recipientId
);
1240 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1241 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1242 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1245 private byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1246 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1247 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1250 private Fingerprint
computeSafetyNumberFingerprint(
1251 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1253 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1254 account
.getSelfAddress(),
1255 account
.getIdentityKeyPair().getPublicKey(),
1261 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1262 return resolveSignalServiceAddress(resolveRecipient(address
));
1265 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1266 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1267 if (address
.getUuid().isPresent()) {
1268 return address
.toSignalServiceAddress();
1271 // Address in recipient store doesn't have a uuid, this shouldn't happen
1272 // Try to retrieve the uuid from the server
1273 final var number
= address
.getNumber().get();
1276 uuid
= getRegisteredUser(number
);
1277 } catch (IOException e
) {
1278 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1279 // Return SignalServiceAddress with unknown UUID
1280 return address
.toSignalServiceAddress();
1282 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1285 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1286 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1287 for (var number
: recipients
) {
1288 final var recipientId
= resolveRecipient(number
);
1289 recipientIds
.add(recipientId
);
1291 return recipientIds
;
1294 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1295 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1296 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1298 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1299 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1301 return getRegisteredUser(number
);
1302 } catch (IOException e
) {
1309 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1310 return account
.getRecipientStore().resolveRecipient(address
);
1313 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1314 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1318 public void close() throws IOException
{
1322 private void close(boolean closeAccount
) throws IOException
{
1323 executor
.shutdown();
1325 dependencies
.getSignalWebSocket().disconnect();
1327 if (closeAccount
&& account
!= null) {