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
,
181 account
::getProfileKey
,
182 this::getRecipientProfile
);
183 this.profileHelper
= new ProfileHelper(account
,
186 unidentifiedAccessHelper
::getAccessFor
,
187 this::resolveSignalServiceAddress
);
188 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
189 this::getRecipientProfile
,
190 account
::getSelfRecipientId
,
191 dependencies
.getGroupsV2Operations(),
192 dependencies
.getGroupsV2Api(),
193 this::resolveSignalServiceAddress
);
194 this.sendHelper
= new SendHelper(account
,
196 unidentifiedAccessHelper
,
197 this::resolveSignalServiceAddress
,
198 account
.getRecipientStore(),
199 this::handleIdentityFailure
,
201 this::refreshRegisteredUser
);
202 this.groupHelper
= new GroupHelper(account
,
208 this::resolveSignalServiceAddress
,
209 account
.getRecipientStore());
210 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
211 this.contactHelper
= new ContactHelper(account
);
212 this.syncHelper
= new SyncHelper(account
,
217 this::resolveSignalServiceAddress
);
218 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
220 this.context
= new Context(account
,
229 var jobExecutor
= new JobExecutor(context
);
231 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
233 account
.getRecipientStore(),
234 this::resolveSignalServiceAddress
,
239 this::getRecipientProfile
,
244 public String
getSelfNumber() {
245 return account
.getUsername();
249 public void checkAccountState() throws IOException
{
250 if (account
.getLastReceiveTimestamp() == 0) {
251 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
253 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
254 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
257 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
261 preKeyHelper
.refreshPreKeysIfNecessary();
262 if (account
.getUuid() == null) {
263 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
265 updateAccountAttributes(null);
269 * This is used for checking a set of phone numbers for registration on Signal
271 * @param numbers The set of phone number in question
272 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
273 * @throws IOException if its unable to get the contacts to check if they're registered
276 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
277 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
279 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
280 } catch (InvalidNumberException e
) {
285 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
286 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
288 .filter(s
-> !s
.isEmpty())
289 .collect(Collectors
.toSet()));
291 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
292 final var number
= canonicalizedNumbers
.get(n
);
293 final var uuid
= registeredUsers
.get(number
);
294 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
299 public void updateAccountAttributes(String deviceName
) throws IOException
{
300 final String encryptedDeviceName
;
301 if (deviceName
== null) {
302 encryptedDeviceName
= account
.getEncryptedDeviceName();
304 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
305 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
306 account
.setEncryptedDeviceName(encryptedDeviceName
);
308 dependencies
.getAccountManager()
309 .setAccountAttributes(encryptedDeviceName
,
311 account
.getLocalRegistrationId(),
314 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
315 account
.getSelfUnidentifiedAccessKey(),
316 account
.isUnrestrictedUnidentifiedAccess(),
318 account
.isDiscoverableByPhoneNumber());
322 public void updateConfiguration(
323 final Boolean readReceipts
,
324 final Boolean unidentifiedDeliveryIndicators
,
325 final Boolean typingIndicators
,
326 final Boolean linkPreviews
327 ) throws IOException
, NotMasterDeviceException
{
328 if (!account
.isMasterDevice()) {
329 throw new NotMasterDeviceException();
332 final var configurationStore
= account
.getConfigurationStore();
333 if (readReceipts
!= null) {
334 configurationStore
.setReadReceipts(readReceipts
);
336 if (unidentifiedDeliveryIndicators
!= null) {
337 configurationStore
.setUnidentifiedDeliveryIndicators(unidentifiedDeliveryIndicators
);
339 if (typingIndicators
!= null) {
340 configurationStore
.setTypingIndicators(typingIndicators
);
342 if (linkPreviews
!= null) {
343 configurationStore
.setLinkPreviews(linkPreviews
);
345 syncHelper
.sendConfigurationMessage();
349 * @param givenName if null, the previous givenName will be kept
350 * @param familyName if null, the previous familyName will be kept
351 * @param about if null, the previous about text will be kept
352 * @param aboutEmoji if null, the previous about emoji will be kept
353 * @param avatar if avatar is null the image from the local avatar store is used (if present),
356 public void setProfile(
357 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
358 ) throws IOException
{
359 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
360 syncHelper
.sendSyncFetchProfileMessage();
364 public void unregister() throws IOException
{
365 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
366 // If this is the master device, other users can't send messages to this number anymore.
367 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
368 dependencies
.getAccountManager().setGcmId(Optional
.absent());
370 account
.setRegistered(false);
374 public void deleteAccount() throws IOException
{
376 pinHelper
.removeRegistrationLockPin();
377 } catch (UnauthenticatedResponseException e
) {
378 logger
.warn("Failed to remove registration lock pin");
380 account
.setRegistrationLockPin(null, null);
382 dependencies
.getAccountManager().deleteAccount();
384 account
.setRegistered(false);
388 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
389 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
393 public List
<Device
> getLinkedDevices() throws IOException
{
394 var devices
= dependencies
.getAccountManager().getDevices();
395 account
.setMultiDevice(devices
.size() > 1);
396 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
397 return devices
.stream().map(d
-> {
398 String deviceName
= d
.getName();
399 if (deviceName
!= null) {
401 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
402 } catch (IOException e
) {
403 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
406 return new Device(d
.getId(),
410 d
.getId() == account
.getDeviceId());
411 }).collect(Collectors
.toList());
415 public void removeLinkedDevices(long deviceId
) throws IOException
{
416 dependencies
.getAccountManager().removeDevice(deviceId
);
417 var devices
= dependencies
.getAccountManager().getDevices();
418 account
.setMultiDevice(devices
.size() > 1);
422 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
423 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
425 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
428 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
429 var identityKeyPair
= account
.getIdentityKeyPair();
430 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
432 dependencies
.getAccountManager()
433 .addDevice(deviceIdentifier
,
436 Optional
.of(account
.getProfileKey().serialize()),
438 account
.setMultiDevice(true);
442 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
443 if (!account
.isMasterDevice()) {
444 throw new RuntimeException("Only master device can set a PIN");
446 if (pin
.isPresent()) {
447 final var masterKey
= account
.getPinMasterKey() != null
448 ? account
.getPinMasterKey()
449 : KeyUtils
.createMasterKey();
451 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
453 account
.setRegistrationLockPin(pin
.get(), masterKey
);
456 pinHelper
.removeRegistrationLockPin();
458 account
.setRegistrationLockPin(null, null);
462 void refreshPreKeys() throws IOException
{
463 preKeyHelper
.refreshPreKeys();
467 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
468 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
471 private Profile
getRecipientProfile(RecipientId recipientId
) {
472 return profileHelper
.getRecipientProfile(recipientId
);
476 public List
<Group
> getGroups() {
477 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
480 private Group
toGroup(final GroupInfo groupInfo
) {
481 if (groupInfo
== null) {
485 return new Group(groupInfo
.getGroupId(),
486 groupInfo
.getTitle(),
487 groupInfo
.getDescription(),
488 groupInfo
.getGroupInviteLink(),
489 groupInfo
.getMembers()
491 .map(account
.getRecipientStore()::resolveRecipientAddress
)
492 .collect(Collectors
.toSet()),
493 groupInfo
.getPendingMembers()
495 .map(account
.getRecipientStore()::resolveRecipientAddress
)
496 .collect(Collectors
.toSet()),
497 groupInfo
.getRequestingMembers()
499 .map(account
.getRecipientStore()::resolveRecipientAddress
)
500 .collect(Collectors
.toSet()),
501 groupInfo
.getAdminMembers()
503 .map(account
.getRecipientStore()::resolveRecipientAddress
)
504 .collect(Collectors
.toSet()),
505 groupInfo
.isBlocked(),
506 groupInfo
.getMessageExpirationTimer(),
507 groupInfo
.getPermissionAddMember(),
508 groupInfo
.getPermissionEditDetails(),
509 groupInfo
.getPermissionSendMessage(),
510 groupInfo
.isMember(account
.getSelfRecipientId()),
511 groupInfo
.isAdmin(account
.getSelfRecipientId()));
515 public SendGroupMessageResults
quitGroup(
516 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
517 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
518 final var newAdmins
= resolveRecipients(groupAdmins
);
519 return groupHelper
.quitGroup(groupId
, newAdmins
);
523 public void deleteGroup(GroupId groupId
) throws IOException
{
524 groupHelper
.deleteGroup(groupId
);
528 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
529 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
530 ) throws IOException
, AttachmentInvalidException
{
531 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
535 public SendGroupMessageResults
updateGroup(
536 final GroupId groupId
, final UpdateGroup updateGroup
537 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
538 return groupHelper
.updateGroup(groupId
,
539 updateGroup
.getName(),
540 updateGroup
.getDescription(),
541 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
542 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
543 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
544 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
545 updateGroup
.isResetGroupLink(),
546 updateGroup
.getGroupLinkState(),
547 updateGroup
.getAddMemberPermission(),
548 updateGroup
.getEditDetailsPermission(),
549 updateGroup
.getAvatarFile(),
550 updateGroup
.getExpirationTimer(),
551 updateGroup
.getIsAnnouncementGroup());
555 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
556 GroupInviteLinkUrl inviteLinkUrl
557 ) throws IOException
, GroupLinkNotActiveException
{
558 return groupHelper
.joinGroup(inviteLinkUrl
);
561 private SendMessageResults
sendMessage(
562 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
563 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
564 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
565 long timestamp
= System
.currentTimeMillis();
566 messageBuilder
.withTimestamp(timestamp
);
567 for (final var recipient
: recipients
) {
568 if (recipient
instanceof RecipientIdentifier
.Single
) {
569 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
570 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
571 results
.put(recipient
, List
.of(result
));
572 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
573 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
574 results
.put(recipient
, List
.of(result
));
575 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
576 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
577 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
578 results
.put(recipient
, result
);
581 return new SendMessageResults(timestamp
, results
);
584 private void sendTypingMessage(
585 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
586 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
587 final var timestamp
= System
.currentTimeMillis();
588 for (var recipient
: recipients
) {
589 if (recipient
instanceof RecipientIdentifier
.Single
) {
590 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
591 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
592 sendHelper
.sendTypingMessage(message
, recipientId
);
593 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
594 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
595 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
596 sendHelper
.sendGroupTypingMessage(message
, groupId
);
602 public void sendTypingMessage(
603 TypingAction action
, Set
<RecipientIdentifier
> recipients
604 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
605 sendTypingMessage(action
.toSignalService(), recipients
);
609 public void sendReadReceipt(
610 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
611 ) throws IOException
, UntrustedIdentityException
{
612 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
614 System
.currentTimeMillis());
616 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
620 public void sendViewedReceipt(
621 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
622 ) throws IOException
, UntrustedIdentityException
{
623 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
625 System
.currentTimeMillis());
627 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
631 public SendMessageResults
sendMessage(
632 Message message
, Set
<RecipientIdentifier
> recipients
633 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
634 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
635 applyMessage(messageBuilder
, message
);
636 return sendMessage(messageBuilder
, recipients
);
639 private void applyMessage(
640 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
641 ) throws AttachmentInvalidException
, IOException
{
642 messageBuilder
.withBody(message
.getMessageText());
643 final var attachments
= message
.getAttachments();
644 if (attachments
!= null) {
645 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
650 public SendMessageResults
sendRemoteDeleteMessage(
651 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
652 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
653 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
654 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
655 return sendMessage(messageBuilder
, recipients
);
659 public SendMessageResults
sendMessageReaction(
662 RecipientIdentifier
.Single targetAuthor
,
663 long targetSentTimestamp
,
664 Set
<RecipientIdentifier
> recipients
665 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
666 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
667 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
669 resolveSignalServiceAddress(targetAuthorRecipientId
),
670 targetSentTimestamp
);
671 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
672 return sendMessage(messageBuilder
, recipients
);
676 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
677 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
680 return sendMessage(messageBuilder
,
681 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
682 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
683 throw new AssertionError(e
);
685 for (var recipient
: recipients
) {
686 final var recipientId
= resolveRecipient(recipient
);
687 account
.getSessionStore().deleteAllSessions(recipientId
);
693 public void setContactName(
694 RecipientIdentifier
.Single recipient
, String name
695 ) throws NotMasterDeviceException
, UnregisteredUserException
{
696 if (!account
.isMasterDevice()) {
697 throw new NotMasterDeviceException();
699 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
703 public void setContactBlocked(
704 RecipientIdentifier
.Single recipient
, boolean blocked
705 ) throws NotMasterDeviceException
, IOException
{
706 if (!account
.isMasterDevice()) {
707 throw new NotMasterDeviceException();
709 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
710 // TODO cycle our profile key
711 syncHelper
.sendBlockedList();
715 public void setGroupBlocked(
716 final GroupId groupId
, final boolean blocked
717 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
718 if (!account
.isMasterDevice()) {
719 throw new NotMasterDeviceException();
721 groupHelper
.setGroupBlocked(groupId
, blocked
);
722 // TODO cycle our profile key
723 syncHelper
.sendBlockedList();
727 * Change the expiration timer for a contact
730 public void setExpirationTimer(
731 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
732 ) throws IOException
{
733 var recipientId
= resolveRecipient(recipient
);
734 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
735 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
737 sendMessage(messageBuilder
, Set
.of(recipient
));
738 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
739 throw new AssertionError(e
);
744 * Upload the sticker pack from path.
746 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
747 * @return if successful, returns the URL to install the sticker pack in the signal app
750 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
751 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
753 var messageSender
= dependencies
.getMessageSender();
755 var packKey
= KeyUtils
.createStickerUploadKey();
756 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
757 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
759 var sticker
= new Sticker(packId
, packKey
);
760 account
.getStickerStore().updateSticker(sticker
);
763 return new URI("https",
767 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
769 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
770 } catch (URISyntaxException e
) {
771 throw new AssertionError(e
);
776 public void requestAllSyncData() throws IOException
{
777 syncHelper
.requestAllSyncData();
778 retrieveRemoteStorage();
781 void retrieveRemoteStorage() throws IOException
{
782 if (account
.getStorageKey() != null) {
783 storageHelper
.readDataFromStorage();
787 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
788 final var address
= resolveSignalServiceAddress(recipientId
);
789 if (!address
.getNumber().isPresent()) {
792 final var number
= address
.getNumber().get();
793 final var uuid
= getRegisteredUser(number
);
794 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
797 private UUID
getRegisteredUser(final String number
) throws IOException
{
798 final Map
<String
, UUID
> uuidMap
;
800 uuidMap
= getRegisteredUsers(Set
.of(number
));
801 } catch (NumberFormatException e
) {
802 throw new UnregisteredUserException(number
, e
);
804 final var uuid
= uuidMap
.get(number
);
806 throw new UnregisteredUserException(number
, null);
811 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
812 final Map
<String
, UUID
> registeredUsers
;
814 registeredUsers
= dependencies
.getAccountManager()
815 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
817 serviceEnvironmentConfig
.getCdsMrenclave());
818 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
819 throw new IOException(e
);
822 // Store numbers as recipients so we have the number/uuid association
823 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
825 return registeredUsers
;
828 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
829 Set
<HandleAction
> queuedActions
= new HashSet
<>();
830 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
831 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
832 if (actions
!= null) {
833 queuedActions
.addAll(actions
);
836 handleQueuedActions(queuedActions
);
839 private List
<HandleAction
> retryFailedReceivedMessage(
840 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
842 var envelope
= cachedMessage
.loadEnvelope();
843 if (envelope
== null) {
844 cachedMessage
.delete();
848 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
849 final var actions
= result
.first();
850 final var exception
= result
.second();
852 if (exception
instanceof UntrustedIdentityException
) {
853 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
854 // Envelope is more than a month old, cleaning up.
855 cachedMessage
.delete();
858 if (!envelope
.hasSourceUuid()) {
859 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
860 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
862 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
863 } catch (IOException ioException
) {
864 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
870 // If successful and for all other errors that are not recoverable, delete the cached message
871 cachedMessage
.delete();
876 public void receiveMessages(
879 boolean returnOnTimeout
,
880 boolean ignoreAttachments
,
881 ReceiveMessageHandler handler
882 ) throws IOException
{
883 retryFailedReceivedMessages(handler
, ignoreAttachments
);
885 Set
<HandleAction
> queuedActions
= new HashSet
<>();
887 final var signalWebSocket
= dependencies
.getSignalWebSocket();
888 signalWebSocket
.connect();
890 hasCaughtUpWithOldMessages
= false;
892 while (!Thread
.interrupted()) {
893 SignalServiceEnvelope envelope
;
894 final CachedMessage
[] cachedMessage
= {null};
895 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
896 logger
.debug("Checking for new message from server");
898 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
899 final var recipientId
= envelope1
.hasSourceUuid()
900 ?
resolveRecipient(envelope1
.getSourceAddress())
902 // store message on disk, before acknowledging receipt to the server
903 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
905 if (result
.isPresent()) {
906 envelope
= result
.get();
907 logger
.debug("New message received from server");
909 logger
.debug("Received indicator that server queue is empty");
910 handleQueuedActions(queuedActions
);
911 queuedActions
.clear();
913 hasCaughtUpWithOldMessages
= true;
914 synchronized (this) {
918 // Continue to wait another timeout for new messages
921 } catch (AssertionError e
) {
922 if (e
.getCause() instanceof InterruptedException
) {
923 Thread
.currentThread().interrupt();
928 } catch (WebSocketUnavailableException e
) {
929 logger
.debug("Pipe unexpectedly unavailable, connecting");
930 signalWebSocket
.connect();
932 } catch (TimeoutException e
) {
933 if (returnOnTimeout
) return;
937 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
938 queuedActions
.addAll(result
.first());
939 final var exception
= result
.second();
941 if (hasCaughtUpWithOldMessages
) {
942 handleQueuedActions(queuedActions
);
944 if (cachedMessage
[0] != null) {
945 if (exception
instanceof UntrustedIdentityException
) {
946 final var address
= ((UntrustedIdentityException
) exception
).getSender();
947 final var recipientId
= resolveRecipient(address
);
948 if (!envelope
.hasSourceUuid()) {
950 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
951 } catch (IOException ioException
) {
952 logger
.warn("Failed to move cached message to recipient folder: {}",
953 ioException
.getMessage());
957 cachedMessage
[0].delete();
961 handleQueuedActions(queuedActions
);
965 public boolean hasCaughtUpWithOldMessages() {
966 return hasCaughtUpWithOldMessages
;
969 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
970 var interrupted
= false;
971 for (var action
: queuedActions
) {
973 action
.execute(context
);
974 } catch (Throwable e
) {
975 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
976 && e
.getCause() instanceof InterruptedException
) {
980 logger
.warn("Message action failed.", e
);
984 Thread
.currentThread().interrupt();
989 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
990 final RecipientId recipientId
;
992 recipientId
= resolveRecipient(recipient
);
993 } catch (UnregisteredUserException e
) {
996 return contactHelper
.isContactBlocked(recipientId
);
1000 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
1001 return attachmentHelper
.getAttachmentFile(attachmentId
);
1005 public void sendContacts() throws IOException
{
1006 syncHelper
.sendContacts();
1010 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1011 return account
.getContactStore()
1014 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1015 .collect(Collectors
.toList());
1019 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1020 final RecipientId recipientId
;
1022 recipientId
= resolveRecipient(recipient
);
1023 } catch (UnregisteredUserException e
) {
1027 final var contact
= account
.getContactStore().getContact(recipientId
);
1028 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1029 return contact
.getName();
1032 final var profile
= getRecipientProfile(recipientId
);
1033 if (profile
!= null) {
1034 return profile
.getDisplayName();
1041 public Group
getGroup(GroupId groupId
) {
1042 return toGroup(groupHelper
.getGroup(groupId
));
1045 public GroupInfo
getGroupInfo(GroupId groupId
) {
1046 return groupHelper
.getGroup(groupId
);
1050 public List
<Identity
> getIdentities() {
1051 return account
.getIdentityKeyStore()
1054 .map(this::toIdentity
)
1055 .collect(Collectors
.toList());
1058 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1059 if (identityInfo
== null) {
1063 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1064 return new Identity(address
,
1065 identityInfo
.getIdentityKey(),
1066 computeSafetyNumber(address
.toSignalServiceAddress(), identityInfo
.getIdentityKey()),
1067 computeSafetyNumberForScanning(address
.toSignalServiceAddress(), identityInfo
.getIdentityKey()),
1068 identityInfo
.getTrustLevel(),
1069 identityInfo
.getDateAdded());
1073 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1074 IdentityInfo identity
;
1076 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1077 } catch (UnregisteredUserException e
) {
1080 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1084 * Trust this the identity with this fingerprint
1086 * @param recipient username of the identity
1087 * @param fingerprint Fingerprint
1090 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1091 RecipientId recipientId
;
1093 recipientId
= resolveRecipient(recipient
);
1094 } catch (UnregisteredUserException e
) {
1097 return trustIdentity(recipientId
,
1098 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1099 TrustLevel
.TRUSTED_VERIFIED
);
1103 * Trust this the identity with this safety number
1105 * @param recipient username of the identity
1106 * @param safetyNumber Safety number
1109 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1110 RecipientId recipientId
;
1112 recipientId
= resolveRecipient(recipient
);
1113 } catch (UnregisteredUserException e
) {
1116 var address
= resolveSignalServiceAddress(recipientId
);
1117 return trustIdentity(recipientId
,
1118 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1119 TrustLevel
.TRUSTED_VERIFIED
);
1123 * Trust this the identity with this scannable safety number
1125 * @param recipient username of the identity
1126 * @param safetyNumber Scannable safety number
1129 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1130 RecipientId recipientId
;
1132 recipientId
= resolveRecipient(recipient
);
1133 } catch (UnregisteredUserException e
) {
1136 var address
= resolveSignalServiceAddress(recipientId
);
1137 return trustIdentity(recipientId
, identityKey
-> {
1138 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1140 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1141 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1144 }, TrustLevel
.TRUSTED_VERIFIED
);
1148 * Trust all keys of this identity without verification
1150 * @param recipient username of the identity
1153 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1154 RecipientId recipientId
;
1156 recipientId
= resolveRecipient(recipient
);
1157 } catch (UnregisteredUserException e
) {
1160 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1163 private boolean trustIdentity(
1164 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1166 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1167 if (identity
== null) {
1171 if (!verifier
.apply(identity
.getIdentityKey())) {
1175 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1177 var address
= resolveSignalServiceAddress(recipientId
);
1178 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1179 } catch (IOException e
) {
1180 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1186 private void handleIdentityFailure(
1187 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1189 final var identityKey
= identityFailure
.getIdentityKey();
1190 if (identityKey
!= null) {
1191 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1193 account
.getSessionStore().archiveSessions(recipientId
);
1196 // Retrieve profile to get the current identity key from the server
1197 profileHelper
.refreshRecipientProfile(recipientId
);
1202 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1203 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1204 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1207 private byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1208 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1209 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1212 private Fingerprint
computeSafetyNumberFingerprint(
1213 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1215 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1216 account
.getSelfAddress(),
1217 account
.getIdentityKeyPair().getPublicKey(),
1223 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1224 return resolveSignalServiceAddress(resolveRecipient(address
));
1227 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1228 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1229 if (address
.getUuid().isPresent()) {
1230 return address
.toSignalServiceAddress();
1233 // Address in recipient store doesn't have a uuid, this shouldn't happen
1234 // Try to retrieve the uuid from the server
1235 final var number
= address
.getNumber().get();
1238 uuid
= getRegisteredUser(number
);
1239 } catch (IOException e
) {
1240 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1241 // Return SignalServiceAddress with unknown UUID
1242 return address
.toSignalServiceAddress();
1244 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1247 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1248 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1249 for (var number
: recipients
) {
1250 final var recipientId
= resolveRecipient(number
);
1251 recipientIds
.add(recipientId
);
1253 return recipientIds
;
1256 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1257 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1258 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1260 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1261 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1263 return getRegisteredUser(number
);
1264 } catch (IOException e
) {
1271 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1272 return account
.getRecipientStore().resolveRecipient(address
);
1275 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1276 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1280 public void close() throws IOException
{
1284 private void close(boolean closeAccount
) throws IOException
{
1285 executor
.shutdown();
1287 dependencies
.getSignalWebSocket().disconnect();
1289 if (closeAccount
&& account
!= null) {