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
.api
.UpdateGroup
;
29 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
30 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
31 import org
.asamk
.signal
.manager
.groups
.GroupId
;
32 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
33 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
34 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
35 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
36 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
37 import org
.asamk
.signal
.manager
.helper
.AttachmentHelper
;
38 import org
.asamk
.signal
.manager
.helper
.ContactHelper
;
39 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
40 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
41 import org
.asamk
.signal
.manager
.helper
.IncomingMessageHandler
;
42 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
43 import org
.asamk
.signal
.manager
.helper
.PreKeyHelper
;
44 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
45 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
46 import org
.asamk
.signal
.manager
.helper
.StorageHelper
;
47 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
48 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
49 import org
.asamk
.signal
.manager
.jobs
.Context
;
50 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
51 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
52 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
53 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
57 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
58 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
59 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
60 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
61 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
62 import org
.asamk
.signal
.manager
.util
.Utils
;
63 import org
.slf4j
.Logger
;
64 import org
.slf4j
.LoggerFactory
;
65 import org
.whispersystems
.libsignal
.IdentityKey
;
66 import org
.whispersystems
.libsignal
.InvalidKeyException
;
67 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
68 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
69 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
70 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
71 import org
.whispersystems
.libsignal
.util
.Pair
;
72 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
73 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
74 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
75 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
76 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
78 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
79 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
80 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
81 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
82 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
83 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
84 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
85 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
86 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
87 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
88 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
89 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
90 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
91 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
92 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
95 import java
.io
.IOException
;
97 import java
.net
.URISyntaxException
;
98 import java
.net
.URLEncoder
;
99 import java
.nio
.charset
.StandardCharsets
;
100 import java
.security
.SignatureException
;
101 import java
.util
.Arrays
;
102 import java
.util
.Collection
;
103 import java
.util
.Date
;
104 import java
.util
.HashMap
;
105 import java
.util
.HashSet
;
106 import java
.util
.List
;
107 import java
.util
.Map
;
108 import java
.util
.Set
;
109 import java
.util
.UUID
;
110 import java
.util
.concurrent
.ExecutorService
;
111 import java
.util
.concurrent
.Executors
;
112 import java
.util
.concurrent
.TimeUnit
;
113 import java
.util
.concurrent
.TimeoutException
;
114 import java
.util
.concurrent
.locks
.ReentrantLock
;
115 import java
.util
.function
.Function
;
116 import java
.util
.stream
.Collectors
;
118 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
120 public class ManagerImpl
implements Manager
{
122 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
124 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
125 private final SignalDependencies dependencies
;
127 private SignalAccount account
;
129 private final ExecutorService executor
= Executors
.newCachedThreadPool();
131 private final ProfileHelper profileHelper
;
132 private final PinHelper pinHelper
;
133 private final StorageHelper storageHelper
;
134 private final SendHelper sendHelper
;
135 private final SyncHelper syncHelper
;
136 private final AttachmentHelper attachmentHelper
;
137 private final GroupHelper groupHelper
;
138 private final ContactHelper contactHelper
;
139 private final IncomingMessageHandler incomingMessageHandler
;
140 private final PreKeyHelper preKeyHelper
;
142 private final Context context
;
143 private boolean hasCaughtUpWithOldMessages
= false;
146 SignalAccount account
,
147 PathConfig pathConfig
,
148 ServiceEnvironmentConfig serviceEnvironmentConfig
,
151 this.account
= account
;
152 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
154 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
155 account
.getUsername(),
156 account
.getPassword(),
157 account
.getDeviceId());
158 final var sessionLock
= new SignalSessionLock() {
159 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
162 public Lock
acquire() {
164 return LEGACY_LOCK
::unlock
;
167 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
170 account
.getSignalProtocolStore(),
173 final var avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
174 final var attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
175 final var stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
177 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
178 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
179 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
180 account
.getProfileStore()::getProfileKey
,
181 this::getRecipientProfile
,
182 this::getSenderCertificate
);
183 this.profileHelper
= new ProfileHelper(account
,
186 account
.getProfileStore()::getProfileKey
,
187 unidentifiedAccessHelper
::getAccessFor
,
188 this::resolveSignalServiceAddress
);
189 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
190 this::getRecipientProfile
,
191 account
::getSelfRecipientId
,
192 dependencies
.getGroupsV2Operations(),
193 dependencies
.getGroupsV2Api(),
194 this::resolveSignalServiceAddress
);
195 this.sendHelper
= new SendHelper(account
,
197 unidentifiedAccessHelper
,
198 this::resolveSignalServiceAddress
,
199 account
.getRecipientStore(),
200 this::handleIdentityFailure
,
202 this::refreshRegisteredUser
);
203 this.groupHelper
= new GroupHelper(account
,
209 this::resolveSignalServiceAddress
,
210 account
.getRecipientStore());
211 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
212 this.contactHelper
= new ContactHelper(account
);
213 this.syncHelper
= new SyncHelper(account
,
218 this::resolveSignalServiceAddress
);
219 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
221 this.context
= new Context(account
,
230 var jobExecutor
= new JobExecutor(context
);
232 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
234 account
.getRecipientStore(),
235 this::resolveSignalServiceAddress
,
240 this::getRecipientProfile
,
245 public String
getSelfNumber() {
246 return account
.getUsername();
250 public void checkAccountState() throws IOException
{
251 if (account
.getLastReceiveTimestamp() == 0) {
252 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
254 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
255 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
258 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
262 preKeyHelper
.refreshPreKeysIfNecessary();
263 if (account
.getUuid() == null) {
264 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
266 updateAccountAttributes(null);
270 * This is used for checking a set of phone numbers for registration on Signal
272 * @param numbers The set of phone number in question
273 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
274 * @throws IOException if its unable to get the contacts to check if they're registered
277 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
278 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
280 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
281 } catch (InvalidNumberException e
) {
286 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
287 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
289 .filter(s
-> !s
.isEmpty())
290 .collect(Collectors
.toSet()));
292 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
293 final var number
= canonicalizedNumbers
.get(n
);
294 final var uuid
= registeredUsers
.get(number
);
295 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
300 public void updateAccountAttributes(String deviceName
) throws IOException
{
301 final String encryptedDeviceName
;
302 if (deviceName
== null) {
303 encryptedDeviceName
= account
.getEncryptedDeviceName();
305 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
306 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
307 account
.setEncryptedDeviceName(encryptedDeviceName
);
309 dependencies
.getAccountManager()
310 .setAccountAttributes(encryptedDeviceName
,
312 account
.getLocalRegistrationId(),
315 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
316 account
.getSelfUnidentifiedAccessKey(),
317 account
.isUnrestrictedUnidentifiedAccess(),
319 account
.isDiscoverableByPhoneNumber());
323 public void updateConfiguration(
324 final Boolean readReceipts
,
325 final Boolean unidentifiedDeliveryIndicators
,
326 final Boolean typingIndicators
,
327 final Boolean linkPreviews
328 ) throws IOException
, NotMasterDeviceException
{
329 if (!account
.isMasterDevice()) {
330 throw new NotMasterDeviceException();
333 final var configurationStore
= account
.getConfigurationStore();
334 if (readReceipts
!= null) {
335 configurationStore
.setReadReceipts(readReceipts
);
337 if (unidentifiedDeliveryIndicators
!= null) {
338 configurationStore
.setUnidentifiedDeliveryIndicators(unidentifiedDeliveryIndicators
);
340 if (typingIndicators
!= null) {
341 configurationStore
.setTypingIndicators(typingIndicators
);
343 if (linkPreviews
!= null) {
344 configurationStore
.setLinkPreviews(linkPreviews
);
346 syncHelper
.sendConfigurationMessage();
350 * @param givenName if null, the previous givenName will be kept
351 * @param familyName if null, the previous familyName will be kept
352 * @param about if null, the previous about text will be kept
353 * @param aboutEmoji if null, the previous about emoji will be kept
354 * @param avatar if avatar is null the image from the local avatar store is used (if present),
357 public void setProfile(
358 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
359 ) throws IOException
{
360 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
361 syncHelper
.sendSyncFetchProfileMessage();
365 public void unregister() throws IOException
{
366 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
367 // If this is the master device, other users can't send messages to this number anymore.
368 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
369 dependencies
.getAccountManager().setGcmId(Optional
.absent());
371 account
.setRegistered(false);
375 public void deleteAccount() throws IOException
{
377 pinHelper
.removeRegistrationLockPin();
378 } catch (UnauthenticatedResponseException e
) {
379 logger
.warn("Failed to remove registration lock pin");
381 account
.setRegistrationLockPin(null, null);
383 dependencies
.getAccountManager().deleteAccount();
385 account
.setRegistered(false);
389 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
390 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
394 public List
<Device
> getLinkedDevices() throws IOException
{
395 var devices
= dependencies
.getAccountManager().getDevices();
396 account
.setMultiDevice(devices
.size() > 1);
397 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
398 return devices
.stream().map(d
-> {
399 String deviceName
= d
.getName();
400 if (deviceName
!= null) {
402 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
403 } catch (IOException e
) {
404 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
407 return new Device(d
.getId(),
411 d
.getId() == account
.getDeviceId());
412 }).collect(Collectors
.toList());
416 public void removeLinkedDevices(long deviceId
) throws IOException
{
417 dependencies
.getAccountManager().removeDevice(deviceId
);
418 var devices
= dependencies
.getAccountManager().getDevices();
419 account
.setMultiDevice(devices
.size() > 1);
423 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
424 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
426 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
429 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
430 var identityKeyPair
= account
.getIdentityKeyPair();
431 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
433 dependencies
.getAccountManager()
434 .addDevice(deviceIdentifier
,
437 Optional
.of(account
.getProfileKey().serialize()),
439 account
.setMultiDevice(true);
443 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
444 if (!account
.isMasterDevice()) {
445 throw new RuntimeException("Only master device can set a PIN");
447 if (pin
.isPresent()) {
448 final var masterKey
= account
.getPinMasterKey() != null
449 ? account
.getPinMasterKey()
450 : KeyUtils
.createMasterKey();
452 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
454 account
.setRegistrationLockPin(pin
.get(), masterKey
);
457 pinHelper
.removeRegistrationLockPin();
459 account
.setRegistrationLockPin(null, null);
463 void refreshPreKeys() throws IOException
{
464 preKeyHelper
.refreshPreKeys();
468 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
469 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
472 private Profile
getRecipientProfile(RecipientId recipientId
) {
473 return profileHelper
.getRecipientProfile(recipientId
);
477 public List
<Group
> getGroups() {
478 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
481 private Group
toGroup(final GroupInfo groupInfo
) {
482 if (groupInfo
== null) {
486 return new Group(groupInfo
.getGroupId(),
487 groupInfo
.getTitle(),
488 groupInfo
.getDescription(),
489 groupInfo
.getGroupInviteLink(),
490 groupInfo
.getMembers()
492 .map(account
.getRecipientStore()::resolveRecipientAddress
)
493 .collect(Collectors
.toSet()),
494 groupInfo
.getPendingMembers()
496 .map(account
.getRecipientStore()::resolveRecipientAddress
)
497 .collect(Collectors
.toSet()),
498 groupInfo
.getRequestingMembers()
500 .map(account
.getRecipientStore()::resolveRecipientAddress
)
501 .collect(Collectors
.toSet()),
502 groupInfo
.getAdminMembers()
504 .map(account
.getRecipientStore()::resolveRecipientAddress
)
505 .collect(Collectors
.toSet()),
506 groupInfo
.isBlocked(),
507 groupInfo
.getMessageExpirationTimer(),
508 groupInfo
.getPermissionAddMember(),
509 groupInfo
.getPermissionEditDetails(),
510 groupInfo
.getPermissionSendMessage(),
511 groupInfo
.isMember(account
.getSelfRecipientId()),
512 groupInfo
.isAdmin(account
.getSelfRecipientId()));
516 public SendGroupMessageResults
quitGroup(
517 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
518 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
519 final var newAdmins
= resolveRecipients(groupAdmins
);
520 return groupHelper
.quitGroup(groupId
, newAdmins
);
524 public void deleteGroup(GroupId groupId
) throws IOException
{
525 groupHelper
.deleteGroup(groupId
);
529 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
530 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
531 ) throws IOException
, AttachmentInvalidException
{
532 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
536 public SendGroupMessageResults
updateGroup(
537 final GroupId groupId
, final UpdateGroup updateGroup
538 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
539 return groupHelper
.updateGroup(groupId
,
540 updateGroup
.getName(),
541 updateGroup
.getDescription(),
542 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
543 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
544 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
545 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
546 updateGroup
.isResetGroupLink(),
547 updateGroup
.getGroupLinkState(),
548 updateGroup
.getAddMemberPermission(),
549 updateGroup
.getEditDetailsPermission(),
550 updateGroup
.getAvatarFile(),
551 updateGroup
.getExpirationTimer(),
552 updateGroup
.getIsAnnouncementGroup());
556 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
557 GroupInviteLinkUrl inviteLinkUrl
558 ) throws IOException
, GroupLinkNotActiveException
{
559 return groupHelper
.joinGroup(inviteLinkUrl
);
562 private SendMessageResults
sendMessage(
563 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
564 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
565 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
566 long timestamp
= System
.currentTimeMillis();
567 messageBuilder
.withTimestamp(timestamp
);
568 for (final var recipient
: recipients
) {
569 if (recipient
instanceof RecipientIdentifier
.Single
) {
570 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
571 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
572 results
.put(recipient
, List
.of(result
));
573 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
574 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
575 results
.put(recipient
, List
.of(result
));
576 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
577 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
578 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
579 results
.put(recipient
, result
);
582 return new SendMessageResults(timestamp
, results
);
585 private void sendTypingMessage(
586 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
587 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
588 final var timestamp
= System
.currentTimeMillis();
589 for (var recipient
: recipients
) {
590 if (recipient
instanceof RecipientIdentifier
.Single
) {
591 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
592 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
593 sendHelper
.sendTypingMessage(message
, recipientId
);
594 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
595 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
596 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
597 sendHelper
.sendGroupTypingMessage(message
, groupId
);
603 public void sendTypingMessage(
604 TypingAction action
, Set
<RecipientIdentifier
> recipients
605 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
606 sendTypingMessage(action
.toSignalService(), recipients
);
610 public void sendReadReceipt(
611 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
612 ) throws IOException
, UntrustedIdentityException
{
613 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
615 System
.currentTimeMillis());
617 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
621 public void sendViewedReceipt(
622 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
623 ) throws IOException
, UntrustedIdentityException
{
624 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
626 System
.currentTimeMillis());
628 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
632 public SendMessageResults
sendMessage(
633 Message message
, Set
<RecipientIdentifier
> recipients
634 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
635 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
636 applyMessage(messageBuilder
, message
);
637 return sendMessage(messageBuilder
, recipients
);
640 private void applyMessage(
641 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
642 ) throws AttachmentInvalidException
, IOException
{
643 messageBuilder
.withBody(message
.getMessageText());
644 final var attachments
= message
.getAttachments();
645 if (attachments
!= null) {
646 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
651 public SendMessageResults
sendRemoteDeleteMessage(
652 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
653 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
654 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
655 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
656 return sendMessage(messageBuilder
, recipients
);
660 public SendMessageResults
sendMessageReaction(
663 RecipientIdentifier
.Single targetAuthor
,
664 long targetSentTimestamp
,
665 Set
<RecipientIdentifier
> recipients
666 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
667 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
668 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
670 resolveSignalServiceAddress(targetAuthorRecipientId
),
671 targetSentTimestamp
);
672 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
673 return sendMessage(messageBuilder
, recipients
);
677 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
678 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
681 return sendMessage(messageBuilder
,
682 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
683 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
684 throw new AssertionError(e
);
686 for (var recipient
: recipients
) {
687 final var recipientId
= resolveRecipient(recipient
);
688 account
.getSessionStore().deleteAllSessions(recipientId
);
694 public void setContactName(
695 RecipientIdentifier
.Single recipient
, String name
696 ) throws NotMasterDeviceException
, UnregisteredUserException
{
697 if (!account
.isMasterDevice()) {
698 throw new NotMasterDeviceException();
700 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
704 public void setContactBlocked(
705 RecipientIdentifier
.Single recipient
, boolean blocked
706 ) throws NotMasterDeviceException
, IOException
{
707 if (!account
.isMasterDevice()) {
708 throw new NotMasterDeviceException();
710 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
711 // TODO cycle our profile key
712 syncHelper
.sendBlockedList();
716 public void setGroupBlocked(
717 final GroupId groupId
, final boolean blocked
718 ) throws GroupNotFoundException
, IOException
{
719 groupHelper
.setGroupBlocked(groupId
, blocked
);
720 // TODO cycle our profile key
721 syncHelper
.sendBlockedList();
725 * Change the expiration timer for a contact
728 public void setExpirationTimer(
729 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
730 ) throws IOException
{
731 var recipientId
= resolveRecipient(recipient
);
732 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
733 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
735 sendMessage(messageBuilder
, Set
.of(recipient
));
736 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
737 throw new AssertionError(e
);
742 * Upload the sticker pack from path.
744 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
745 * @return if successful, returns the URL to install the sticker pack in the signal app
748 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
749 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
751 var messageSender
= dependencies
.getMessageSender();
753 var packKey
= KeyUtils
.createStickerUploadKey();
754 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
755 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
757 var sticker
= new Sticker(packId
, packKey
);
758 account
.getStickerStore().updateSticker(sticker
);
761 return new URI("https",
765 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
767 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
768 } catch (URISyntaxException e
) {
769 throw new AssertionError(e
);
774 public void requestAllSyncData() throws IOException
{
775 syncHelper
.requestAllSyncData();
776 retrieveRemoteStorage();
779 void retrieveRemoteStorage() throws IOException
{
780 if (account
.getStorageKey() != null) {
781 storageHelper
.readDataFromStorage();
785 private byte[] getSenderCertificate() {
788 if (account
.isPhoneNumberShared()) {
789 certificate
= dependencies
.getAccountManager().getSenderCertificate();
791 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
793 } catch (IOException e
) {
794 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
797 // TODO cache for a day
801 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
802 final var address
= resolveSignalServiceAddress(recipientId
);
803 if (!address
.getNumber().isPresent()) {
806 final var number
= address
.getNumber().get();
807 final var uuid
= getRegisteredUser(number
);
808 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
811 private UUID
getRegisteredUser(final String number
) throws IOException
{
812 final Map
<String
, UUID
> uuidMap
;
814 uuidMap
= getRegisteredUsers(Set
.of(number
));
815 } catch (NumberFormatException e
) {
816 throw new UnregisteredUserException(number
, e
);
818 final var uuid
= uuidMap
.get(number
);
820 throw new UnregisteredUserException(number
, null);
825 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
826 final Map
<String
, UUID
> registeredUsers
;
828 registeredUsers
= dependencies
.getAccountManager()
829 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
831 serviceEnvironmentConfig
.getCdsMrenclave());
832 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
833 throw new IOException(e
);
836 // Store numbers as recipients so we have the number/uuid association
837 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
839 return registeredUsers
;
842 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
843 Set
<HandleAction
> queuedActions
= new HashSet
<>();
844 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
845 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
846 if (actions
!= null) {
847 queuedActions
.addAll(actions
);
850 handleQueuedActions(queuedActions
);
853 private List
<HandleAction
> retryFailedReceivedMessage(
854 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
856 var envelope
= cachedMessage
.loadEnvelope();
857 if (envelope
== null) {
858 cachedMessage
.delete();
862 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
863 final var actions
= result
.first();
864 final var exception
= result
.second();
866 if (exception
instanceof UntrustedIdentityException
) {
867 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
868 // Envelope is more than a month old, cleaning up.
869 cachedMessage
.delete();
872 if (!envelope
.hasSourceUuid()) {
873 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
874 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
876 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
877 } catch (IOException ioException
) {
878 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
884 // If successful and for all other errors that are not recoverable, delete the cached message
885 cachedMessage
.delete();
890 public void receiveMessages(
893 boolean returnOnTimeout
,
894 boolean ignoreAttachments
,
895 ReceiveMessageHandler handler
896 ) throws IOException
{
897 retryFailedReceivedMessages(handler
, ignoreAttachments
);
899 Set
<HandleAction
> queuedActions
= new HashSet
<>();
901 final var signalWebSocket
= dependencies
.getSignalWebSocket();
902 signalWebSocket
.connect();
904 hasCaughtUpWithOldMessages
= false;
906 while (!Thread
.interrupted()) {
907 SignalServiceEnvelope envelope
;
908 final CachedMessage
[] cachedMessage
= {null};
909 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
910 logger
.debug("Checking for new message from server");
912 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
913 final var recipientId
= envelope1
.hasSourceUuid()
914 ?
resolveRecipient(envelope1
.getSourceAddress())
916 // store message on disk, before acknowledging receipt to the server
917 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
919 if (result
.isPresent()) {
920 envelope
= result
.get();
921 logger
.debug("New message received from server");
923 logger
.debug("Received indicator that server queue is empty");
924 handleQueuedActions(queuedActions
);
925 queuedActions
.clear();
927 hasCaughtUpWithOldMessages
= true;
928 synchronized (this) {
932 // Continue to wait another timeout for new messages
935 } catch (AssertionError e
) {
936 if (e
.getCause() instanceof InterruptedException
) {
937 Thread
.currentThread().interrupt();
942 } catch (WebSocketUnavailableException e
) {
943 logger
.debug("Pipe unexpectedly unavailable, connecting");
944 signalWebSocket
.connect();
946 } catch (TimeoutException e
) {
947 if (returnOnTimeout
) return;
951 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
952 queuedActions
.addAll(result
.first());
953 final var exception
= result
.second();
955 if (hasCaughtUpWithOldMessages
) {
956 handleQueuedActions(queuedActions
);
958 if (cachedMessage
[0] != null) {
959 if (exception
instanceof UntrustedIdentityException
) {
960 final var address
= ((UntrustedIdentityException
) exception
).getSender();
961 final var recipientId
= resolveRecipient(address
);
962 if (!envelope
.hasSourceUuid()) {
964 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
965 } catch (IOException ioException
) {
966 logger
.warn("Failed to move cached message to recipient folder: {}",
967 ioException
.getMessage());
971 cachedMessage
[0].delete();
975 handleQueuedActions(queuedActions
);
979 public boolean hasCaughtUpWithOldMessages() {
980 return hasCaughtUpWithOldMessages
;
983 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
984 var interrupted
= false;
985 for (var action
: queuedActions
) {
987 action
.execute(context
);
988 } catch (Throwable e
) {
989 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
990 && e
.getCause() instanceof InterruptedException
) {
994 logger
.warn("Message action failed.", e
);
998 Thread
.currentThread().interrupt();
1003 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1004 final RecipientId recipientId
;
1006 recipientId
= resolveRecipient(recipient
);
1007 } catch (UnregisteredUserException e
) {
1010 return contactHelper
.isContactBlocked(recipientId
);
1014 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
1015 return attachmentHelper
.getAttachmentFile(attachmentId
);
1019 public void sendContacts() throws IOException
{
1020 syncHelper
.sendContacts();
1024 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1025 return account
.getContactStore()
1028 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1029 .collect(Collectors
.toList());
1033 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1034 final RecipientId recipientId
;
1036 recipientId
= resolveRecipient(recipient
);
1037 } catch (UnregisteredUserException e
) {
1041 final var contact
= account
.getContactStore().getContact(recipientId
);
1042 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1043 return contact
.getName();
1046 final var profile
= getRecipientProfile(recipientId
);
1047 if (profile
!= null) {
1048 return profile
.getDisplayName();
1055 public Group
getGroup(GroupId groupId
) {
1056 return toGroup(groupHelper
.getGroup(groupId
));
1059 public GroupInfo
getGroupInfo(GroupId groupId
) {
1060 return groupHelper
.getGroup(groupId
);
1064 public List
<Identity
> getIdentities() {
1065 return account
.getIdentityKeyStore()
1068 .map(this::toIdentity
)
1069 .collect(Collectors
.toList());
1072 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1073 if (identityInfo
== null) {
1077 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1078 return new Identity(address
,
1079 identityInfo
.getIdentityKey(),
1080 computeSafetyNumber(address
.toSignalServiceAddress(), identityInfo
.getIdentityKey()),
1081 computeSafetyNumberForScanning(address
.toSignalServiceAddress(), identityInfo
.getIdentityKey()),
1082 identityInfo
.getTrustLevel(),
1083 identityInfo
.getDateAdded());
1087 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1088 IdentityInfo identity
;
1090 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1091 } catch (UnregisteredUserException e
) {
1094 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1098 * Trust this the identity with this fingerprint
1100 * @param recipient username of the identity
1101 * @param fingerprint Fingerprint
1104 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1105 RecipientId recipientId
;
1107 recipientId
= resolveRecipient(recipient
);
1108 } catch (UnregisteredUserException e
) {
1111 return trustIdentity(recipientId
,
1112 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1113 TrustLevel
.TRUSTED_VERIFIED
);
1117 * Trust this the identity with this safety number
1119 * @param recipient username of the identity
1120 * @param safetyNumber Safety number
1123 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1124 RecipientId recipientId
;
1126 recipientId
= resolveRecipient(recipient
);
1127 } catch (UnregisteredUserException e
) {
1130 var address
= resolveSignalServiceAddress(recipientId
);
1131 return trustIdentity(recipientId
,
1132 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1133 TrustLevel
.TRUSTED_VERIFIED
);
1137 * Trust this the identity with this scannable safety number
1139 * @param recipient username of the identity
1140 * @param safetyNumber Scannable safety number
1143 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1144 RecipientId recipientId
;
1146 recipientId
= resolveRecipient(recipient
);
1147 } catch (UnregisteredUserException e
) {
1150 var address
= resolveSignalServiceAddress(recipientId
);
1151 return trustIdentity(recipientId
, identityKey
-> {
1152 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1154 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1155 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1158 }, TrustLevel
.TRUSTED_VERIFIED
);
1162 * Trust all keys of this identity without verification
1164 * @param recipient username of the identity
1167 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1168 RecipientId recipientId
;
1170 recipientId
= resolveRecipient(recipient
);
1171 } catch (UnregisteredUserException e
) {
1174 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1177 private boolean trustIdentity(
1178 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1180 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1181 if (identity
== null) {
1185 if (!verifier
.apply(identity
.getIdentityKey())) {
1189 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1191 var address
= resolveSignalServiceAddress(recipientId
);
1192 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1193 } catch (IOException e
) {
1194 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1200 private void handleIdentityFailure(
1201 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1203 final var identityKey
= identityFailure
.getIdentityKey();
1204 if (identityKey
!= null) {
1205 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1207 account
.getSessionStore().archiveSessions(recipientId
);
1210 // Retrieve profile to get the current identity key from the server
1211 profileHelper
.refreshRecipientProfile(recipientId
);
1216 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1217 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1218 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1221 private byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1222 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1223 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1226 private Fingerprint
computeSafetyNumberFingerprint(
1227 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1229 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1230 account
.getSelfAddress(),
1231 account
.getIdentityKeyPair().getPublicKey(),
1237 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1238 return resolveSignalServiceAddress(resolveRecipient(address
));
1241 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1242 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1243 if (address
.getUuid().isPresent()) {
1244 return address
.toSignalServiceAddress();
1247 // Address in recipient store doesn't have a uuid, this shouldn't happen
1248 // Try to retrieve the uuid from the server
1249 final var number
= address
.getNumber().get();
1252 uuid
= getRegisteredUser(number
);
1253 } catch (IOException e
) {
1254 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1255 // Return SignalServiceAddress with unknown UUID
1256 return address
.toSignalServiceAddress();
1258 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1261 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1262 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1263 for (var number
: recipients
) {
1264 final var recipientId
= resolveRecipient(number
);
1265 recipientIds
.add(recipientId
);
1267 return recipientIds
;
1270 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1271 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1272 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1274 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1275 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1277 return getRegisteredUser(number
);
1278 } catch (IOException e
) {
1285 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1286 return account
.getRecipientStore().resolveRecipient(address
);
1289 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1290 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1294 public void close() throws IOException
{
1298 private void close(boolean closeAccount
) throws IOException
{
1299 executor
.shutdown();
1301 dependencies
.getSignalWebSocket().disconnect();
1303 if (closeAccount
&& account
!= null) {