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
.Configuration
;
21 import org
.asamk
.signal
.manager
.api
.Device
;
22 import org
.asamk
.signal
.manager
.api
.Group
;
23 import org
.asamk
.signal
.manager
.api
.Identity
;
24 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
25 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
26 import org
.asamk
.signal
.manager
.api
.Message
;
27 import org
.asamk
.signal
.manager
.api
.Pair
;
28 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
29 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
30 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
31 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
32 import org
.asamk
.signal
.manager
.api
.TypingAction
;
33 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
34 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
35 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
36 import org
.asamk
.signal
.manager
.groups
.GroupId
;
37 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
38 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
39 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
40 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
41 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
42 import org
.asamk
.signal
.manager
.helper
.AttachmentHelper
;
43 import org
.asamk
.signal
.manager
.helper
.ContactHelper
;
44 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
45 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
46 import org
.asamk
.signal
.manager
.helper
.IdentityHelper
;
47 import org
.asamk
.signal
.manager
.helper
.IncomingMessageHandler
;
48 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
49 import org
.asamk
.signal
.manager
.helper
.PreKeyHelper
;
50 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
51 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
52 import org
.asamk
.signal
.manager
.helper
.StorageHelper
;
53 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
54 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
55 import org
.asamk
.signal
.manager
.jobs
.Context
;
56 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
57 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
58 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
59 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
60 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
61 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
62 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
63 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
64 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
65 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
66 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
67 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
68 import org
.slf4j
.Logger
;
69 import org
.slf4j
.LoggerFactory
;
70 import org
.whispersystems
.libsignal
.InvalidKeyException
;
71 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
72 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
73 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
74 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
75 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
76 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
78 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
79 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
80 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
81 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
82 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
83 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
84 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
85 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
86 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
87 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
88 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
89 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
92 import java
.io
.IOException
;
94 import java
.net
.URISyntaxException
;
95 import java
.net
.URLEncoder
;
96 import java
.nio
.charset
.StandardCharsets
;
97 import java
.security
.SignatureException
;
98 import java
.util
.Collection
;
99 import java
.util
.HashMap
;
100 import java
.util
.HashSet
;
101 import java
.util
.List
;
102 import java
.util
.Map
;
103 import java
.util
.Set
;
104 import java
.util
.UUID
;
105 import java
.util
.concurrent
.ExecutorService
;
106 import java
.util
.concurrent
.Executors
;
107 import java
.util
.concurrent
.TimeUnit
;
108 import java
.util
.concurrent
.TimeoutException
;
109 import java
.util
.concurrent
.locks
.ReentrantLock
;
110 import java
.util
.stream
.Collectors
;
112 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
114 public class ManagerImpl
implements Manager
{
116 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
118 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
119 private final SignalDependencies dependencies
;
121 private SignalAccount account
;
123 private final ExecutorService executor
= Executors
.newCachedThreadPool();
125 private final ProfileHelper profileHelper
;
126 private final PinHelper pinHelper
;
127 private final StorageHelper storageHelper
;
128 private final SendHelper sendHelper
;
129 private final SyncHelper syncHelper
;
130 private final AttachmentHelper attachmentHelper
;
131 private final GroupHelper groupHelper
;
132 private final ContactHelper contactHelper
;
133 private final IncomingMessageHandler incomingMessageHandler
;
134 private final PreKeyHelper preKeyHelper
;
135 private final IdentityHelper identityHelper
;
137 private final Context context
;
138 private boolean hasCaughtUpWithOldMessages
= false;
139 private boolean ignoreAttachments
= false;
141 private Thread receiveThread
;
142 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
143 private boolean isReceivingSynchronous
;
146 SignalAccount account
,
147 PathConfig pathConfig
,
148 ServiceEnvironmentConfig serviceEnvironmentConfig
,
151 this.account
= account
;
152 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
154 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
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
.avatarsPath());
174 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
175 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
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
,
241 this.identityHelper
= new IdentityHelper(account
,
243 this::resolveSignalServiceAddress
,
249 public String
getSelfNumber() {
250 return account
.getUsername();
254 public void checkAccountState() throws IOException
{
255 if (account
.getLastReceiveTimestamp() == 0) {
256 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
258 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
259 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
262 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
266 preKeyHelper
.refreshPreKeysIfNecessary();
267 if (account
.getAci() == null) {
268 account
.setAci(dependencies
.getAccountManager().getOwnAci());
270 updateAccountAttributes(null);
274 * This is used for checking a set of phone numbers for registration on Signal
276 * @param numbers The set of phone number in question
277 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
278 * @throws IOException if its unable to get the contacts to check if they're registered
281 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
282 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
284 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
285 } catch (InvalidNumberException e
) {
290 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
291 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
293 .filter(s
-> !s
.isEmpty())
294 .collect(Collectors
.toSet()));
296 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
297 final var number
= canonicalizedNumbers
.get(n
);
298 final var aci
= registeredUsers
.get(number
);
299 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
304 public void updateAccountAttributes(String deviceName
) throws IOException
{
305 final String encryptedDeviceName
;
306 if (deviceName
== null) {
307 encryptedDeviceName
= account
.getEncryptedDeviceName();
309 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
310 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
311 account
.setEncryptedDeviceName(encryptedDeviceName
);
313 dependencies
.getAccountManager()
314 .setAccountAttributes(encryptedDeviceName
,
316 account
.getLocalRegistrationId(),
319 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
320 account
.getSelfUnidentifiedAccessKey(),
321 account
.isUnrestrictedUnidentifiedAccess(),
323 account
.isDiscoverableByPhoneNumber());
327 public Configuration
getConfiguration() {
328 final var configurationStore
= account
.getConfigurationStore();
329 return new Configuration(java
.util
.Optional
.ofNullable(configurationStore
.getReadReceipts()),
330 java
.util
.Optional
.ofNullable(configurationStore
.getUnidentifiedDeliveryIndicators()),
331 java
.util
.Optional
.ofNullable(configurationStore
.getTypingIndicators()),
332 java
.util
.Optional
.ofNullable(configurationStore
.getLinkPreviews()));
336 public void updateConfiguration(
337 Configuration configuration
338 ) throws IOException
, NotMasterDeviceException
{
339 if (!account
.isMasterDevice()) {
340 throw new NotMasterDeviceException();
343 final var configurationStore
= account
.getConfigurationStore();
344 if (configuration
.readReceipts().isPresent()) {
345 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
347 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
348 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
350 if (configuration
.typingIndicators().isPresent()) {
351 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
353 if (configuration
.linkPreviews().isPresent()) {
354 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
356 syncHelper
.sendConfigurationMessage();
360 * @param givenName if null, the previous givenName will be kept
361 * @param familyName if null, the previous familyName will be kept
362 * @param about if null, the previous about text will be kept
363 * @param aboutEmoji if null, the previous about emoji will be kept
364 * @param avatar if avatar is null the image from the local avatar store is used (if present),
367 public void setProfile(
368 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
369 ) throws IOException
{
370 profileHelper
.setProfile(givenName
,
374 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
375 syncHelper
.sendSyncFetchProfileMessage();
379 public void unregister() throws IOException
{
380 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
381 // If this is the master device, other users can't send messages to this number anymore.
382 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
383 dependencies
.getAccountManager().setGcmId(Optional
.absent());
385 account
.setRegistered(false);
389 public void deleteAccount() throws IOException
{
391 pinHelper
.removeRegistrationLockPin();
392 } catch (IOException e
) {
393 logger
.warn("Failed to remove registration lock pin");
395 account
.setRegistrationLockPin(null, null);
397 dependencies
.getAccountManager().deleteAccount();
399 account
.setRegistered(false);
403 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
404 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
408 public List
<Device
> getLinkedDevices() throws IOException
{
409 var devices
= dependencies
.getAccountManager().getDevices();
410 account
.setMultiDevice(devices
.size() > 1);
411 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
412 return devices
.stream().map(d
-> {
413 String deviceName
= d
.getName();
414 if (deviceName
!= null) {
416 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
417 } catch (IOException e
) {
418 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
421 return new Device(d
.getId(),
425 d
.getId() == account
.getDeviceId());
426 }).collect(Collectors
.toList());
430 public void removeLinkedDevices(long deviceId
) throws IOException
{
431 dependencies
.getAccountManager().removeDevice(deviceId
);
432 var devices
= dependencies
.getAccountManager().getDevices();
433 account
.setMultiDevice(devices
.size() > 1);
437 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
438 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
440 addDevice(info
.deviceIdentifier(), info
.deviceKey());
443 private void addDevice(
444 String deviceIdentifier
, ECPublicKey deviceKey
445 ) throws IOException
, InvalidDeviceLinkException
{
446 var identityKeyPair
= account
.getIdentityKeyPair();
447 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
450 dependencies
.getAccountManager()
451 .addDevice(deviceIdentifier
,
454 Optional
.of(account
.getProfileKey().serialize()),
456 } catch (InvalidKeyException e
) {
457 throw new InvalidDeviceLinkException("Invalid device link", e
);
459 account
.setMultiDevice(true);
463 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
{
464 if (!account
.isMasterDevice()) {
465 throw new RuntimeException("Only master device can set a PIN");
467 if (pin
.isPresent()) {
468 final var masterKey
= account
.getPinMasterKey() != null
469 ? account
.getPinMasterKey()
470 : KeyUtils
.createMasterKey();
472 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
474 account
.setRegistrationLockPin(pin
.get(), masterKey
);
477 pinHelper
.removeRegistrationLockPin();
479 account
.setRegistrationLockPin(null, null);
483 void refreshPreKeys() throws IOException
{
484 preKeyHelper
.refreshPreKeys();
488 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
{
489 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
492 private Profile
getRecipientProfile(RecipientId recipientId
) {
493 return profileHelper
.getRecipientProfile(recipientId
);
497 public List
<Group
> getGroups() {
498 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
501 private Group
toGroup(final GroupInfo groupInfo
) {
502 if (groupInfo
== null) {
506 return new Group(groupInfo
.getGroupId(),
507 groupInfo
.getTitle(),
508 groupInfo
.getDescription(),
509 groupInfo
.getGroupInviteLink(),
510 groupInfo
.getMembers()
512 .map(account
.getRecipientStore()::resolveRecipientAddress
)
513 .collect(Collectors
.toSet()),
514 groupInfo
.getPendingMembers()
516 .map(account
.getRecipientStore()::resolveRecipientAddress
)
517 .collect(Collectors
.toSet()),
518 groupInfo
.getRequestingMembers()
520 .map(account
.getRecipientStore()::resolveRecipientAddress
)
521 .collect(Collectors
.toSet()),
522 groupInfo
.getAdminMembers()
524 .map(account
.getRecipientStore()::resolveRecipientAddress
)
525 .collect(Collectors
.toSet()),
526 groupInfo
.isBlocked(),
527 groupInfo
.getMessageExpirationTimer(),
528 groupInfo
.getPermissionAddMember(),
529 groupInfo
.getPermissionEditDetails(),
530 groupInfo
.getPermissionSendMessage(),
531 groupInfo
.isMember(account
.getSelfRecipientId()),
532 groupInfo
.isAdmin(account
.getSelfRecipientId()));
536 public SendGroupMessageResults
quitGroup(
537 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
538 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
539 final var newAdmins
= resolveRecipients(groupAdmins
);
540 return groupHelper
.quitGroup(groupId
, newAdmins
);
544 public void deleteGroup(GroupId groupId
) throws IOException
{
545 groupHelper
.deleteGroup(groupId
);
549 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
550 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
551 ) throws IOException
, AttachmentInvalidException
{
552 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
556 public SendGroupMessageResults
updateGroup(
557 final GroupId groupId
, final UpdateGroup updateGroup
558 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
559 return groupHelper
.updateGroup(groupId
,
560 updateGroup
.getName(),
561 updateGroup
.getDescription(),
562 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
563 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
564 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
565 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
566 updateGroup
.isResetGroupLink(),
567 updateGroup
.getGroupLinkState(),
568 updateGroup
.getAddMemberPermission(),
569 updateGroup
.getEditDetailsPermission(),
570 updateGroup
.getAvatarFile(),
571 updateGroup
.getExpirationTimer(),
572 updateGroup
.getIsAnnouncementGroup());
576 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
577 GroupInviteLinkUrl inviteLinkUrl
578 ) throws IOException
, InactiveGroupLinkException
{
579 return groupHelper
.joinGroup(inviteLinkUrl
);
582 private SendMessageResults
sendMessage(
583 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
584 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
585 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
586 long timestamp
= System
.currentTimeMillis();
587 messageBuilder
.withTimestamp(timestamp
);
588 for (final var recipient
: recipients
) {
589 if (recipient
instanceof RecipientIdentifier
.Single single
) {
590 final var recipientId
= resolveRecipient(single
);
591 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
592 results
.put(recipient
,
593 List
.of(SendMessageResult
.from(result
,
594 account
.getRecipientStore(),
595 account
.getRecipientStore()::resolveRecipientAddress
)));
596 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
597 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
598 results
.put(recipient
,
599 List
.of(SendMessageResult
.from(result
,
600 account
.getRecipientStore(),
601 account
.getRecipientStore()::resolveRecipientAddress
)));
602 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
603 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, group
.groupId());
604 results
.put(recipient
,
606 .map(sendMessageResult
-> SendMessageResult
.from(sendMessageResult
,
607 account
.getRecipientStore(),
608 account
.getRecipientStore()::resolveRecipientAddress
))
609 .collect(Collectors
.toList()));
612 return new SendMessageResults(timestamp
, results
);
615 private void sendTypingMessage(
616 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
617 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
618 final var timestamp
= System
.currentTimeMillis();
619 for (var recipient
: recipients
) {
620 if (recipient
instanceof RecipientIdentifier
.Single
) {
621 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
622 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
623 sendHelper
.sendTypingMessage(message
, recipientId
);
624 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
625 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
626 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
627 sendHelper
.sendGroupTypingMessage(message
, groupId
);
633 public void sendTypingMessage(
634 TypingAction action
, Set
<RecipientIdentifier
> recipients
635 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
636 sendTypingMessage(action
.toSignalService(), recipients
);
640 public void sendReadReceipt(
641 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
642 ) throws IOException
, UntrustedIdentityException
{
643 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
645 System
.currentTimeMillis());
647 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
651 public void sendViewedReceipt(
652 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
653 ) throws IOException
, UntrustedIdentityException
{
654 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
656 System
.currentTimeMillis());
658 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
662 public SendMessageResults
sendMessage(
663 Message message
, Set
<RecipientIdentifier
> recipients
664 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
665 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
666 applyMessage(messageBuilder
, message
);
667 return sendMessage(messageBuilder
, recipients
);
670 private void applyMessage(
671 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
672 ) throws AttachmentInvalidException
, IOException
{
673 messageBuilder
.withBody(message
.messageText());
674 final var attachments
= message
.attachments();
675 if (attachments
!= null) {
676 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
681 public SendMessageResults
sendRemoteDeleteMessage(
682 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
683 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
684 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
685 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
686 return sendMessage(messageBuilder
, recipients
);
690 public SendMessageResults
sendMessageReaction(
693 RecipientIdentifier
.Single targetAuthor
,
694 long targetSentTimestamp
,
695 Set
<RecipientIdentifier
> recipients
696 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
697 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
698 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
700 resolveSignalServiceAddress(targetAuthorRecipientId
),
701 targetSentTimestamp
);
702 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
703 return sendMessage(messageBuilder
, recipients
);
707 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
708 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
711 return sendMessage(messageBuilder
,
712 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
713 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
714 throw new AssertionError(e
);
716 for (var recipient
: recipients
) {
717 final var recipientId
= resolveRecipient(recipient
);
718 account
.getSessionStore().deleteAllSessions(recipientId
);
724 public void setContactName(
725 RecipientIdentifier
.Single recipient
, String name
726 ) throws NotMasterDeviceException
, IOException
{
727 if (!account
.isMasterDevice()) {
728 throw new NotMasterDeviceException();
730 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
734 public void setContactBlocked(
735 RecipientIdentifier
.Single recipient
, boolean blocked
736 ) throws NotMasterDeviceException
, IOException
{
737 if (!account
.isMasterDevice()) {
738 throw new NotMasterDeviceException();
740 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
741 // TODO cycle our profile key
742 syncHelper
.sendBlockedList();
746 public void setGroupBlocked(
747 final GroupId groupId
, final boolean blocked
748 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
749 if (!account
.isMasterDevice()) {
750 throw new NotMasterDeviceException();
752 groupHelper
.setGroupBlocked(groupId
, blocked
);
753 // TODO cycle our profile key
754 syncHelper
.sendBlockedList();
758 * Change the expiration timer for a contact
761 public void setExpirationTimer(
762 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
763 ) throws IOException
{
764 var recipientId
= resolveRecipient(recipient
);
765 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
766 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
768 sendMessage(messageBuilder
, Set
.of(recipient
));
769 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
770 throw new AssertionError(e
);
775 * Upload the sticker pack from path.
777 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
778 * @return if successful, returns the URL to install the sticker pack in the signal app
781 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
782 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
784 var messageSender
= dependencies
.getMessageSender();
786 var packKey
= KeyUtils
.createStickerUploadKey();
787 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
788 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
790 var sticker
= new Sticker(packId
, packKey
);
791 account
.getStickerStore().updateSticker(sticker
);
794 return new URI("https",
798 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
800 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
801 } catch (URISyntaxException e
) {
802 throw new AssertionError(e
);
807 public void requestAllSyncData() throws IOException
{
808 syncHelper
.requestAllSyncData();
809 retrieveRemoteStorage();
812 void retrieveRemoteStorage() throws IOException
{
813 if (account
.getStorageKey() != null) {
814 storageHelper
.readDataFromStorage();
818 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
819 final var address
= resolveSignalServiceAddress(recipientId
);
820 if (!address
.getNumber().isPresent()) {
823 final var number
= address
.getNumber().get();
824 final var uuid
= getRegisteredUser(number
);
825 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
828 private ACI
getRegisteredUser(final String number
) throws IOException
{
829 final Map
<String
, ACI
> aciMap
;
831 aciMap
= getRegisteredUsers(Set
.of(number
));
832 } catch (NumberFormatException e
) {
833 throw new IOException(number
, e
);
835 final var uuid
= aciMap
.get(number
);
837 throw new IOException(number
, null);
842 private Map
<String
, ACI
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
843 final Map
<String
, ACI
> registeredUsers
;
845 registeredUsers
= dependencies
.getAccountManager()
846 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
848 serviceEnvironmentConfig
.getCdsMrenclave());
849 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
850 throw new IOException(e
);
853 // Store numbers as recipients, so we have the number/uuid association
854 registeredUsers
.forEach((number
, aci
) -> resolveRecipientTrusted(new SignalServiceAddress(aci
, number
)));
856 return registeredUsers
;
859 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
860 Set
<HandleAction
> queuedActions
= new HashSet
<>();
861 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
862 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
863 if (actions
!= null) {
864 queuedActions
.addAll(actions
);
867 handleQueuedActions(queuedActions
);
870 private List
<HandleAction
> retryFailedReceivedMessage(
871 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
873 var envelope
= cachedMessage
.loadEnvelope();
874 if (envelope
== null) {
875 cachedMessage
.delete();
879 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
880 final var actions
= result
.first();
881 final var exception
= result
.second();
883 if (exception
instanceof UntrustedIdentityException
) {
884 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
885 // Envelope is more than a month old, cleaning up.
886 cachedMessage
.delete();
889 if (!envelope
.hasSourceUuid()) {
890 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
891 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
893 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
894 } catch (IOException ioException
) {
895 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
901 // If successful and for all other errors that are not recoverable, delete the cached message
902 cachedMessage
.delete();
907 public void addReceiveHandler(final ReceiveMessageHandler handler
) {
908 if (isReceivingSynchronous
) {
909 throw new IllegalStateException("Already receiving message synchronously.");
911 synchronized (messageHandlers
) {
912 messageHandlers
.add(handler
);
914 startReceiveThreadIfRequired();
918 private void startReceiveThreadIfRequired() {
919 if (receiveThread
!= null) {
922 receiveThread
= new Thread(() -> {
923 logger
.debug("Starting receiving messages");
924 while (!Thread
.interrupted()) {
926 receiveMessagesInternal(1L, TimeUnit
.HOURS
, false, (envelope
, e
) -> {
927 synchronized (messageHandlers
) {
928 for (ReceiveMessageHandler h
: messageHandlers
) {
930 h
.handleMessage(envelope
, e
);
931 } catch (Exception ex
) {
932 logger
.warn("Message handler failed, ignoring", ex
);
938 } catch (IOException e
) {
939 logger
.warn("Receiving messages failed, retrying", e
);
942 logger
.debug("Finished receiving messages");
943 hasCaughtUpWithOldMessages
= false;
944 synchronized (messageHandlers
) {
945 receiveThread
= null;
947 // Check if in the meantime another handler has been registered
948 if (!messageHandlers
.isEmpty()) {
949 logger
.debug("Another handler has been registered, starting receive thread again");
950 startReceiveThreadIfRequired();
955 receiveThread
.start();
959 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
961 synchronized (messageHandlers
) {
962 messageHandlers
.remove(handler
);
963 if (!messageHandlers
.isEmpty() || isReceivingSynchronous
) {
966 thread
= receiveThread
;
967 receiveThread
= null;
970 stopReceiveThread(thread
);
973 private void stopReceiveThread(final Thread thread
) {
977 } catch (InterruptedException ignored
) {
982 public boolean isReceiving() {
983 if (isReceivingSynchronous
) {
986 synchronized (messageHandlers
) {
987 return messageHandlers
.size() > 0;
992 public void receiveMessages(long timeout
, TimeUnit unit
, ReceiveMessageHandler handler
) throws IOException
{
993 receiveMessages(timeout
, unit
, true, handler
);
997 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
998 receiveMessages(1L, TimeUnit
.HOURS
, false, handler
);
1001 private void receiveMessages(
1002 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1003 ) throws IOException
{
1004 if (isReceiving()) {
1005 throw new IllegalStateException("Already receiving message.");
1007 isReceivingSynchronous
= true;
1008 receiveThread
= Thread
.currentThread();
1010 receiveMessagesInternal(timeout
, unit
, returnOnTimeout
, handler
);
1012 receiveThread
= null;
1013 hasCaughtUpWithOldMessages
= false;
1014 isReceivingSynchronous
= false;
1018 private void receiveMessagesInternal(
1019 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1020 ) throws IOException
{
1021 retryFailedReceivedMessages(handler
);
1023 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1025 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1026 signalWebSocket
.connect();
1028 hasCaughtUpWithOldMessages
= false;
1029 var backOffCounter
= 0;
1030 final var MAX_BACKOFF_COUNTER
= 9;
1032 while (!Thread
.interrupted()) {
1033 SignalServiceEnvelope envelope
;
1034 final CachedMessage
[] cachedMessage
= {null};
1035 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1036 logger
.debug("Checking for new message from server");
1038 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1039 final var recipientId
= envelope1
.hasSourceUuid()
1040 ?
resolveRecipient(envelope1
.getSourceAddress())
1042 // store message on disk, before acknowledging receipt to the server
1043 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1047 if (result
.isPresent()) {
1048 envelope
= result
.get();
1049 logger
.debug("New message received from server");
1051 logger
.debug("Received indicator that server queue is empty");
1052 handleQueuedActions(queuedActions
);
1053 queuedActions
.clear();
1055 hasCaughtUpWithOldMessages
= true;
1056 synchronized (this) {
1060 // Continue to wait another timeout for new messages
1063 } catch (AssertionError e
) {
1064 if (e
.getCause() instanceof InterruptedException
) {
1065 Thread
.currentThread().interrupt();
1070 } catch (IOException e
) {
1071 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1072 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1073 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1074 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1075 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1077 Thread
.sleep(sleepMilliseconds
);
1078 } catch (InterruptedException interruptedException
) {
1081 hasCaughtUpWithOldMessages
= false;
1082 signalWebSocket
.connect();
1086 } catch (TimeoutException e
) {
1088 if (returnOnTimeout
) return;
1092 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
1093 queuedActions
.addAll(result
.first());
1094 final var exception
= result
.second();
1096 if (hasCaughtUpWithOldMessages
) {
1097 handleQueuedActions(queuedActions
);
1098 queuedActions
.clear();
1100 if (cachedMessage
[0] != null) {
1101 if (exception
instanceof UntrustedIdentityException
) {
1102 logger
.debug("Keeping message with untrusted identity in message cache");
1103 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1104 final var recipientId
= resolveRecipient(address
);
1105 if (!envelope
.hasSourceUuid()) {
1107 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1108 } catch (IOException ioException
) {
1109 logger
.warn("Failed to move cached message to recipient folder: {}",
1110 ioException
.getMessage());
1114 cachedMessage
[0].delete();
1118 handleQueuedActions(queuedActions
);
1119 queuedActions
.clear();
1120 dependencies
.getSignalWebSocket().disconnect();
1124 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1125 this.ignoreAttachments
= ignoreAttachments
;
1129 public boolean hasCaughtUpWithOldMessages() {
1130 return hasCaughtUpWithOldMessages
;
1133 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1134 logger
.debug("Handling message actions");
1135 var interrupted
= false;
1136 for (var action
: queuedActions
) {
1138 action
.execute(context
);
1139 } catch (Throwable e
) {
1140 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1141 && e
.getCause() instanceof InterruptedException
) {
1145 logger
.warn("Message action failed.", e
);
1149 Thread
.currentThread().interrupt();
1154 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1155 final RecipientId recipientId
;
1157 recipientId
= resolveRecipient(recipient
);
1158 } catch (IOException e
) {
1161 return contactHelper
.isContactBlocked(recipientId
);
1165 public void sendContacts() throws IOException
{
1166 syncHelper
.sendContacts();
1170 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1171 return account
.getContactStore()
1174 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1175 .collect(Collectors
.toList());
1179 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1180 final RecipientId recipientId
;
1182 recipientId
= resolveRecipient(recipient
);
1183 } catch (IOException e
) {
1187 final var contact
= account
.getContactStore().getContact(recipientId
);
1188 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1189 return contact
.getName();
1192 final var profile
= getRecipientProfile(recipientId
);
1193 if (profile
!= null) {
1194 return profile
.getDisplayName();
1201 public Group
getGroup(GroupId groupId
) {
1202 return toGroup(groupHelper
.getGroup(groupId
));
1205 private GroupInfo
getGroupInfo(GroupId groupId
) {
1206 return groupHelper
.getGroup(groupId
);
1210 public List
<Identity
> getIdentities() {
1211 return account
.getIdentityKeyStore()
1214 .map(this::toIdentity
)
1215 .collect(Collectors
.toList());
1218 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1219 if (identityInfo
== null) {
1223 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1224 final var scannableFingerprint
= identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1225 identityInfo
.getIdentityKey());
1226 return new Identity(address
,
1227 identityInfo
.getIdentityKey(),
1228 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1229 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1230 identityInfo
.getTrustLevel(),
1231 identityInfo
.getDateAdded());
1235 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1236 IdentityInfo identity
;
1238 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1239 } catch (IOException e
) {
1242 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1246 * Trust this the identity with this fingerprint
1248 * @param recipient username of the identity
1249 * @param fingerprint Fingerprint
1252 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1253 RecipientId recipientId
;
1255 recipientId
= resolveRecipient(recipient
);
1256 } catch (IOException e
) {
1259 return identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1263 * Trust this the identity with this safety number
1265 * @param recipient username of the identity
1266 * @param safetyNumber Safety number
1269 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1270 RecipientId recipientId
;
1272 recipientId
= resolveRecipient(recipient
);
1273 } catch (IOException e
) {
1276 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1280 * Trust this the identity with this scannable safety number
1282 * @param recipient username of the identity
1283 * @param safetyNumber Scannable safety number
1286 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1287 RecipientId recipientId
;
1289 recipientId
= resolveRecipient(recipient
);
1290 } catch (IOException e
) {
1293 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1297 * Trust all keys of this identity without verification
1299 * @param recipient username of the identity
1302 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1303 RecipientId recipientId
;
1305 recipientId
= resolveRecipient(recipient
);
1306 } catch (IOException e
) {
1309 return identityHelper
.trustIdentityAllKeys(recipientId
);
1312 private void handleIdentityFailure(
1313 final RecipientId recipientId
,
1314 final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
.IdentityFailure identityFailure
1316 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1319 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1320 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1321 if (address
.getUuid().isPresent()) {
1322 return address
.toSignalServiceAddress();
1325 // Address in recipient store doesn't have a uuid, this shouldn't happen
1326 // Try to retrieve the uuid from the server
1327 final var number
= address
.getNumber().get();
1330 aci
= getRegisteredUser(number
);
1331 } catch (IOException e
) {
1332 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1333 // Return SignalServiceAddress with unknown UUID
1334 return address
.toSignalServiceAddress();
1336 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(aci
));
1339 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
1340 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1341 for (var number
: recipients
) {
1342 final var recipientId
= resolveRecipient(number
);
1343 recipientIds
.add(recipientId
);
1345 return recipientIds
;
1348 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
1349 if (recipient
instanceof RecipientIdentifier
.Uuid uuidRecipient
) {
1350 return account
.getRecipientStore().resolveRecipient(ACI
.from(uuidRecipient
.uuid()));
1352 final var number
= ((RecipientIdentifier
.Number
) recipient
).number();
1353 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1355 return getRegisteredUser(number
);
1356 } catch (IOException e
) {
1363 private RecipientId
resolveRecipient(RecipientAddress address
) {
1364 return account
.getRecipientStore().resolveRecipient(address
);
1367 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1368 return account
.getRecipientStore().resolveRecipient(address
);
1371 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1372 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1376 public void close() throws IOException
{
1380 private void close(boolean closeAccount
) throws IOException
{
1382 synchronized (messageHandlers
) {
1383 messageHandlers
.clear();
1384 thread
= receiveThread
;
1385 receiveThread
= null;
1387 if (thread
!= null) {
1388 stopReceiveThread(thread
);
1390 executor
.shutdown();
1392 dependencies
.getSignalWebSocket().disconnect();
1394 if (closeAccount
&& account
!= null) {