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
;
111 import java
.util
.stream
.Stream
;
113 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
115 public class ManagerImpl
implements Manager
{
117 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
119 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
120 private final SignalDependencies dependencies
;
122 private SignalAccount account
;
124 private final ExecutorService executor
= Executors
.newCachedThreadPool();
126 private final ProfileHelper profileHelper
;
127 private final PinHelper pinHelper
;
128 private final StorageHelper storageHelper
;
129 private final SendHelper sendHelper
;
130 private final SyncHelper syncHelper
;
131 private final AttachmentHelper attachmentHelper
;
132 private final GroupHelper groupHelper
;
133 private final ContactHelper contactHelper
;
134 private final IncomingMessageHandler incomingMessageHandler
;
135 private final PreKeyHelper preKeyHelper
;
136 private final IdentityHelper identityHelper
;
138 private final Context context
;
139 private boolean hasCaughtUpWithOldMessages
= false;
140 private boolean ignoreAttachments
= false;
142 private Thread receiveThread
;
143 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
144 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
145 private boolean isReceivingSynchronous
;
148 SignalAccount account
,
149 PathConfig pathConfig
,
150 ServiceEnvironmentConfig serviceEnvironmentConfig
,
153 this.account
= account
;
154 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
156 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
157 account
.getUsername(),
158 account
.getPassword(),
159 account
.getDeviceId());
160 final var sessionLock
= new SignalSessionLock() {
161 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
164 public Lock
acquire() {
166 return LEGACY_LOCK
::unlock
;
169 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
172 account
.getSignalProtocolStore(),
175 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
176 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
177 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
179 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
180 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
181 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
,
183 account
::getProfileKey
,
184 this::getRecipientProfile
);
185 this.profileHelper
= new ProfileHelper(account
,
188 unidentifiedAccessHelper
::getAccessFor
,
189 this::resolveSignalServiceAddress
);
190 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
191 this::getRecipientProfile
,
192 account
::getSelfRecipientId
,
193 dependencies
.getGroupsV2Operations(),
194 dependencies
.getGroupsV2Api(),
195 this::resolveSignalServiceAddress
);
196 this.sendHelper
= new SendHelper(account
,
198 unidentifiedAccessHelper
,
199 this::resolveSignalServiceAddress
,
200 account
.getRecipientStore(),
201 this::handleIdentityFailure
,
203 this::refreshRegisteredUser
);
204 this.groupHelper
= new GroupHelper(account
,
210 this::resolveSignalServiceAddress
,
211 account
.getRecipientStore());
212 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
213 this.contactHelper
= new ContactHelper(account
);
214 this.syncHelper
= new SyncHelper(account
,
219 this::resolveSignalServiceAddress
);
220 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
222 this.context
= new Context(account
,
231 var jobExecutor
= new JobExecutor(context
);
233 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
235 account
.getRecipientStore(),
236 this::resolveSignalServiceAddress
,
241 this::getRecipientProfile
,
243 this.identityHelper
= new IdentityHelper(account
,
245 this::resolveSignalServiceAddress
,
251 public String
getSelfNumber() {
252 return account
.getUsername();
256 public void checkAccountState() throws IOException
{
257 if (account
.getLastReceiveTimestamp() == 0) {
258 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
260 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
261 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
264 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
268 preKeyHelper
.refreshPreKeysIfNecessary();
269 if (account
.getAci() == null) {
270 account
.setAci(dependencies
.getAccountManager().getOwnAci());
272 updateAccountAttributes(null);
276 * This is used for checking a set of phone numbers for registration on Signal
278 * @param numbers The set of phone number in question
279 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
280 * @throws IOException if its unable to get the contacts to check if they're registered
283 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
284 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
286 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
287 } catch (InvalidNumberException e
) {
292 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
293 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
295 .filter(s
-> !s
.isEmpty())
296 .collect(Collectors
.toSet()));
298 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
299 final var number
= canonicalizedNumbers
.get(n
);
300 final var aci
= registeredUsers
.get(number
);
301 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
306 public void updateAccountAttributes(String deviceName
) throws IOException
{
307 final String encryptedDeviceName
;
308 if (deviceName
== null) {
309 encryptedDeviceName
= account
.getEncryptedDeviceName();
311 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
312 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
313 account
.setEncryptedDeviceName(encryptedDeviceName
);
315 dependencies
.getAccountManager()
316 .setAccountAttributes(encryptedDeviceName
,
318 account
.getLocalRegistrationId(),
321 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
322 account
.getSelfUnidentifiedAccessKey(),
323 account
.isUnrestrictedUnidentifiedAccess(),
325 account
.isDiscoverableByPhoneNumber());
329 public Configuration
getConfiguration() {
330 final var configurationStore
= account
.getConfigurationStore();
331 return new Configuration(java
.util
.Optional
.ofNullable(configurationStore
.getReadReceipts()),
332 java
.util
.Optional
.ofNullable(configurationStore
.getUnidentifiedDeliveryIndicators()),
333 java
.util
.Optional
.ofNullable(configurationStore
.getTypingIndicators()),
334 java
.util
.Optional
.ofNullable(configurationStore
.getLinkPreviews()));
338 public void updateConfiguration(
339 Configuration configuration
340 ) throws IOException
, NotMasterDeviceException
{
341 if (!account
.isMasterDevice()) {
342 throw new NotMasterDeviceException();
345 final var configurationStore
= account
.getConfigurationStore();
346 if (configuration
.readReceipts().isPresent()) {
347 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
349 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
350 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
352 if (configuration
.typingIndicators().isPresent()) {
353 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
355 if (configuration
.linkPreviews().isPresent()) {
356 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
358 syncHelper
.sendConfigurationMessage();
362 * @param givenName if null, the previous givenName will be kept
363 * @param familyName if null, the previous familyName will be kept
364 * @param about if null, the previous about text will be kept
365 * @param aboutEmoji if null, the previous about emoji will be kept
366 * @param avatar if avatar is null the image from the local avatar store is used (if present),
369 public void setProfile(
370 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
371 ) throws IOException
{
372 profileHelper
.setProfile(givenName
,
376 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
377 syncHelper
.sendSyncFetchProfileMessage();
381 public void unregister() throws IOException
{
382 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
383 // If this is the master device, other users can't send messages to this number anymore.
384 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
385 dependencies
.getAccountManager().setGcmId(Optional
.absent());
387 account
.setRegistered(false);
391 public void deleteAccount() throws IOException
{
393 pinHelper
.removeRegistrationLockPin();
394 } catch (IOException e
) {
395 logger
.warn("Failed to remove registration lock pin");
397 account
.setRegistrationLockPin(null, null);
399 dependencies
.getAccountManager().deleteAccount();
401 account
.setRegistered(false);
405 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
406 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
408 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
412 public List
<Device
> getLinkedDevices() throws IOException
{
413 var devices
= dependencies
.getAccountManager().getDevices();
414 account
.setMultiDevice(devices
.size() > 1);
415 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
416 return devices
.stream().map(d
-> {
417 String deviceName
= d
.getName();
418 if (deviceName
!= null) {
420 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
421 } catch (IOException e
) {
422 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
425 return new Device(d
.getId(),
429 d
.getId() == account
.getDeviceId());
430 }).collect(Collectors
.toList());
434 public void removeLinkedDevices(long deviceId
) throws IOException
{
435 dependencies
.getAccountManager().removeDevice(deviceId
);
436 var devices
= dependencies
.getAccountManager().getDevices();
437 account
.setMultiDevice(devices
.size() > 1);
441 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
442 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
444 addDevice(info
.deviceIdentifier(), info
.deviceKey());
447 private void addDevice(
448 String deviceIdentifier
, ECPublicKey deviceKey
449 ) throws IOException
, InvalidDeviceLinkException
{
450 var identityKeyPair
= account
.getIdentityKeyPair();
451 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
454 dependencies
.getAccountManager()
455 .addDevice(deviceIdentifier
,
458 Optional
.of(account
.getProfileKey().serialize()),
460 } catch (InvalidKeyException e
) {
461 throw new InvalidDeviceLinkException("Invalid device link", e
);
463 account
.setMultiDevice(true);
467 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
{
468 if (!account
.isMasterDevice()) {
469 throw new RuntimeException("Only master device can set a PIN");
471 if (pin
.isPresent()) {
472 final var masterKey
= account
.getPinMasterKey() != null
473 ? account
.getPinMasterKey()
474 : KeyUtils
.createMasterKey();
476 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
478 account
.setRegistrationLockPin(pin
.get(), masterKey
);
481 pinHelper
.removeRegistrationLockPin();
483 account
.setRegistrationLockPin(null, null);
487 void refreshPreKeys() throws IOException
{
488 preKeyHelper
.refreshPreKeys();
492 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
{
493 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
496 private Profile
getRecipientProfile(RecipientId recipientId
) {
497 return profileHelper
.getRecipientProfile(recipientId
);
501 public List
<Group
> getGroups() {
502 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
505 private Group
toGroup(final GroupInfo groupInfo
) {
506 if (groupInfo
== null) {
510 return new Group(groupInfo
.getGroupId(),
511 groupInfo
.getTitle(),
512 groupInfo
.getDescription(),
513 groupInfo
.getGroupInviteLink(),
514 groupInfo
.getMembers()
516 .map(account
.getRecipientStore()::resolveRecipientAddress
)
517 .collect(Collectors
.toSet()),
518 groupInfo
.getPendingMembers()
520 .map(account
.getRecipientStore()::resolveRecipientAddress
)
521 .collect(Collectors
.toSet()),
522 groupInfo
.getRequestingMembers()
524 .map(account
.getRecipientStore()::resolveRecipientAddress
)
525 .collect(Collectors
.toSet()),
526 groupInfo
.getAdminMembers()
528 .map(account
.getRecipientStore()::resolveRecipientAddress
)
529 .collect(Collectors
.toSet()),
530 groupInfo
.isBlocked(),
531 groupInfo
.getMessageExpirationTimer(),
532 groupInfo
.getPermissionAddMember(),
533 groupInfo
.getPermissionEditDetails(),
534 groupInfo
.getPermissionSendMessage(),
535 groupInfo
.isMember(account
.getSelfRecipientId()),
536 groupInfo
.isAdmin(account
.getSelfRecipientId()));
540 public SendGroupMessageResults
quitGroup(
541 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
542 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
543 final var newAdmins
= resolveRecipients(groupAdmins
);
544 return groupHelper
.quitGroup(groupId
, newAdmins
);
548 public void deleteGroup(GroupId groupId
) throws IOException
{
549 groupHelper
.deleteGroup(groupId
);
553 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
554 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
555 ) throws IOException
, AttachmentInvalidException
{
556 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
560 public SendGroupMessageResults
updateGroup(
561 final GroupId groupId
, final UpdateGroup updateGroup
562 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
563 return groupHelper
.updateGroup(groupId
,
564 updateGroup
.getName(),
565 updateGroup
.getDescription(),
566 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
567 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
568 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
569 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
570 updateGroup
.isResetGroupLink(),
571 updateGroup
.getGroupLinkState(),
572 updateGroup
.getAddMemberPermission(),
573 updateGroup
.getEditDetailsPermission(),
574 updateGroup
.getAvatarFile(),
575 updateGroup
.getExpirationTimer(),
576 updateGroup
.getIsAnnouncementGroup());
580 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
581 GroupInviteLinkUrl inviteLinkUrl
582 ) throws IOException
, InactiveGroupLinkException
{
583 return groupHelper
.joinGroup(inviteLinkUrl
);
586 private SendMessageResults
sendMessage(
587 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
588 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
589 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
590 long timestamp
= System
.currentTimeMillis();
591 messageBuilder
.withTimestamp(timestamp
);
592 for (final var recipient
: recipients
) {
593 if (recipient
instanceof RecipientIdentifier
.Single single
) {
594 final var recipientId
= resolveRecipient(single
);
595 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
596 results
.put(recipient
,
597 List
.of(SendMessageResult
.from(result
,
598 account
.getRecipientStore(),
599 account
.getRecipientStore()::resolveRecipientAddress
)));
600 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
601 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
602 results
.put(recipient
,
603 List
.of(SendMessageResult
.from(result
,
604 account
.getRecipientStore(),
605 account
.getRecipientStore()::resolveRecipientAddress
)));
606 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
607 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, group
.groupId());
608 results
.put(recipient
,
610 .map(sendMessageResult
-> SendMessageResult
.from(sendMessageResult
,
611 account
.getRecipientStore(),
612 account
.getRecipientStore()::resolveRecipientAddress
))
613 .collect(Collectors
.toList()));
616 return new SendMessageResults(timestamp
, results
);
619 private void sendTypingMessage(
620 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
621 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
622 final var timestamp
= System
.currentTimeMillis();
623 for (var recipient
: recipients
) {
624 if (recipient
instanceof RecipientIdentifier
.Single
) {
625 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
626 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
627 sendHelper
.sendTypingMessage(message
, recipientId
);
628 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
629 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
630 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
631 sendHelper
.sendGroupTypingMessage(message
, groupId
);
637 public void sendTypingMessage(
638 TypingAction action
, Set
<RecipientIdentifier
> recipients
639 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
640 sendTypingMessage(action
.toSignalService(), recipients
);
644 public void sendReadReceipt(
645 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
646 ) throws IOException
, UntrustedIdentityException
{
647 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
649 System
.currentTimeMillis());
651 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
655 public void sendViewedReceipt(
656 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
657 ) throws IOException
, UntrustedIdentityException
{
658 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
660 System
.currentTimeMillis());
662 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
666 public SendMessageResults
sendMessage(
667 Message message
, Set
<RecipientIdentifier
> recipients
668 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
669 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
670 applyMessage(messageBuilder
, message
);
671 return sendMessage(messageBuilder
, recipients
);
674 private void applyMessage(
675 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
676 ) throws AttachmentInvalidException
, IOException
{
677 messageBuilder
.withBody(message
.messageText());
678 final var attachments
= message
.attachments();
679 if (attachments
!= null) {
680 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
685 public SendMessageResults
sendRemoteDeleteMessage(
686 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
687 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
688 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
689 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
690 return sendMessage(messageBuilder
, recipients
);
694 public SendMessageResults
sendMessageReaction(
697 RecipientIdentifier
.Single targetAuthor
,
698 long targetSentTimestamp
,
699 Set
<RecipientIdentifier
> recipients
700 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
701 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
702 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
704 resolveSignalServiceAddress(targetAuthorRecipientId
),
705 targetSentTimestamp
);
706 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
707 return sendMessage(messageBuilder
, recipients
);
711 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
712 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
715 return sendMessage(messageBuilder
,
716 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
717 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
718 throw new AssertionError(e
);
720 for (var recipient
: recipients
) {
721 final var recipientId
= resolveRecipient(recipient
);
722 account
.getSessionStore().deleteAllSessions(recipientId
);
728 public void setContactName(
729 RecipientIdentifier
.Single recipient
, String name
730 ) throws NotMasterDeviceException
, IOException
{
731 if (!account
.isMasterDevice()) {
732 throw new NotMasterDeviceException();
734 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
738 public void setContactBlocked(
739 RecipientIdentifier
.Single recipient
, boolean blocked
740 ) throws NotMasterDeviceException
, IOException
{
741 if (!account
.isMasterDevice()) {
742 throw new NotMasterDeviceException();
744 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
745 // TODO cycle our profile key
746 syncHelper
.sendBlockedList();
750 public void setGroupBlocked(
751 final GroupId groupId
, final boolean blocked
752 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
753 if (!account
.isMasterDevice()) {
754 throw new NotMasterDeviceException();
756 groupHelper
.setGroupBlocked(groupId
, blocked
);
757 // TODO cycle our profile key
758 syncHelper
.sendBlockedList();
762 * Change the expiration timer for a contact
765 public void setExpirationTimer(
766 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
767 ) throws IOException
{
768 var recipientId
= resolveRecipient(recipient
);
769 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
770 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
772 sendMessage(messageBuilder
, Set
.of(recipient
));
773 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
774 throw new AssertionError(e
);
779 * Upload the sticker pack from path.
781 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
782 * @return if successful, returns the URL to install the sticker pack in the signal app
785 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
786 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
788 var messageSender
= dependencies
.getMessageSender();
790 var packKey
= KeyUtils
.createStickerUploadKey();
791 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
792 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
794 var sticker
= new Sticker(packId
, packKey
);
795 account
.getStickerStore().updateSticker(sticker
);
798 return new URI("https",
802 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
804 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
805 } catch (URISyntaxException e
) {
806 throw new AssertionError(e
);
811 public void requestAllSyncData() throws IOException
{
812 syncHelper
.requestAllSyncData();
813 retrieveRemoteStorage();
816 void retrieveRemoteStorage() throws IOException
{
817 if (account
.getStorageKey() != null) {
818 storageHelper
.readDataFromStorage();
822 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
823 final var address
= resolveSignalServiceAddress(recipientId
);
824 if (!address
.getNumber().isPresent()) {
827 final var number
= address
.getNumber().get();
828 final var uuid
= getRegisteredUser(number
);
829 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
832 private ACI
getRegisteredUser(final String number
) throws IOException
{
833 final Map
<String
, ACI
> aciMap
;
835 aciMap
= getRegisteredUsers(Set
.of(number
));
836 } catch (NumberFormatException e
) {
837 throw new IOException(number
, e
);
839 final var uuid
= aciMap
.get(number
);
841 throw new IOException(number
, null);
846 private Map
<String
, ACI
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
847 final Map
<String
, ACI
> registeredUsers
;
849 registeredUsers
= dependencies
.getAccountManager()
850 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
852 serviceEnvironmentConfig
.getCdsMrenclave());
853 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
854 throw new IOException(e
);
857 // Store numbers as recipients, so we have the number/uuid association
858 registeredUsers
.forEach((number
, aci
) -> resolveRecipientTrusted(new SignalServiceAddress(aci
, number
)));
860 return registeredUsers
;
863 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
864 Set
<HandleAction
> queuedActions
= new HashSet
<>();
865 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
866 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
867 if (actions
!= null) {
868 queuedActions
.addAll(actions
);
871 handleQueuedActions(queuedActions
);
874 private List
<HandleAction
> retryFailedReceivedMessage(
875 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
877 var envelope
= cachedMessage
.loadEnvelope();
878 if (envelope
== null) {
879 cachedMessage
.delete();
883 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
884 final var actions
= result
.first();
885 final var exception
= result
.second();
887 if (exception
instanceof UntrustedIdentityException
) {
888 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
889 // Envelope is more than a month old, cleaning up.
890 cachedMessage
.delete();
893 if (!envelope
.hasSourceUuid()) {
894 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
895 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
897 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
898 } catch (IOException ioException
) {
899 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
905 // If successful and for all other errors that are not recoverable, delete the cached message
906 cachedMessage
.delete();
911 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
912 if (isReceivingSynchronous
) {
913 throw new IllegalStateException("Already receiving message synchronously.");
915 synchronized (messageHandlers
) {
916 if (isWeakListener
) {
917 weakHandlers
.add(handler
);
919 messageHandlers
.add(handler
);
920 startReceiveThreadIfRequired();
925 private void startReceiveThreadIfRequired() {
926 if (receiveThread
!= null) {
929 receiveThread
= new Thread(() -> {
930 logger
.debug("Starting receiving messages");
931 while (!Thread
.interrupted()) {
933 receiveMessagesInternal(1L, TimeUnit
.HOURS
, false, (envelope
, e
) -> {
934 synchronized (messageHandlers
) {
935 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
937 h
.handleMessage(envelope
, e
);
938 } catch (Exception ex
) {
939 logger
.warn("Message handler failed, ignoring", ex
);
945 } catch (IOException e
) {
946 logger
.warn("Receiving messages failed, retrying", e
);
949 logger
.debug("Finished receiving messages");
950 hasCaughtUpWithOldMessages
= false;
951 synchronized (messageHandlers
) {
952 receiveThread
= null;
954 // Check if in the meantime another handler has been registered
955 if (!messageHandlers
.isEmpty()) {
956 logger
.debug("Another handler has been registered, starting receive thread again");
957 startReceiveThreadIfRequired();
962 receiveThread
.start();
966 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
968 synchronized (messageHandlers
) {
969 weakHandlers
.remove(handler
);
970 messageHandlers
.remove(handler
);
971 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
974 thread
= receiveThread
;
975 receiveThread
= null;
978 stopReceiveThread(thread
);
981 private void stopReceiveThread(final Thread thread
) {
985 } catch (InterruptedException ignored
) {
990 public boolean isReceiving() {
991 if (isReceivingSynchronous
) {
994 synchronized (messageHandlers
) {
995 return messageHandlers
.size() > 0;
1000 public void receiveMessages(long timeout
, TimeUnit unit
, ReceiveMessageHandler handler
) throws IOException
{
1001 receiveMessages(timeout
, unit
, true, handler
);
1005 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
1006 receiveMessages(1L, TimeUnit
.HOURS
, false, handler
);
1009 private void receiveMessages(
1010 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1011 ) throws IOException
{
1012 if (isReceiving()) {
1013 throw new IllegalStateException("Already receiving message.");
1015 isReceivingSynchronous
= true;
1016 receiveThread
= Thread
.currentThread();
1018 receiveMessagesInternal(timeout
, unit
, returnOnTimeout
, handler
);
1020 receiveThread
= null;
1021 hasCaughtUpWithOldMessages
= false;
1022 isReceivingSynchronous
= false;
1026 private void receiveMessagesInternal(
1027 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1028 ) throws IOException
{
1029 retryFailedReceivedMessages(handler
);
1031 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1033 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1034 signalWebSocket
.connect();
1036 hasCaughtUpWithOldMessages
= false;
1037 var backOffCounter
= 0;
1038 final var MAX_BACKOFF_COUNTER
= 9;
1040 while (!Thread
.interrupted()) {
1041 SignalServiceEnvelope envelope
;
1042 final CachedMessage
[] cachedMessage
= {null};
1043 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1044 logger
.debug("Checking for new message from server");
1046 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1047 final var recipientId
= envelope1
.hasSourceUuid()
1048 ?
resolveRecipient(envelope1
.getSourceAddress())
1050 // store message on disk, before acknowledging receipt to the server
1051 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1055 if (result
.isPresent()) {
1056 envelope
= result
.get();
1057 logger
.debug("New message received from server");
1059 logger
.debug("Received indicator that server queue is empty");
1060 handleQueuedActions(queuedActions
);
1061 queuedActions
.clear();
1063 hasCaughtUpWithOldMessages
= true;
1064 synchronized (this) {
1068 // Continue to wait another timeout for new messages
1071 } catch (AssertionError e
) {
1072 if (e
.getCause() instanceof InterruptedException
) {
1073 Thread
.currentThread().interrupt();
1078 } catch (IOException e
) {
1079 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1080 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1081 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1082 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1083 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1085 Thread
.sleep(sleepMilliseconds
);
1086 } catch (InterruptedException interruptedException
) {
1089 hasCaughtUpWithOldMessages
= false;
1090 signalWebSocket
.connect();
1094 } catch (TimeoutException e
) {
1096 if (returnOnTimeout
) return;
1100 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
1101 queuedActions
.addAll(result
.first());
1102 final var exception
= result
.second();
1104 if (hasCaughtUpWithOldMessages
) {
1105 handleQueuedActions(queuedActions
);
1106 queuedActions
.clear();
1108 if (cachedMessage
[0] != null) {
1109 if (exception
instanceof UntrustedIdentityException
) {
1110 logger
.debug("Keeping message with untrusted identity in message cache");
1111 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1112 final var recipientId
= resolveRecipient(address
);
1113 if (!envelope
.hasSourceUuid()) {
1115 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1116 } catch (IOException ioException
) {
1117 logger
.warn("Failed to move cached message to recipient folder: {}",
1118 ioException
.getMessage());
1122 cachedMessage
[0].delete();
1126 handleQueuedActions(queuedActions
);
1127 queuedActions
.clear();
1128 dependencies
.getSignalWebSocket().disconnect();
1132 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1133 this.ignoreAttachments
= ignoreAttachments
;
1137 public boolean hasCaughtUpWithOldMessages() {
1138 return hasCaughtUpWithOldMessages
;
1141 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1142 logger
.debug("Handling message actions");
1143 var interrupted
= false;
1144 for (var action
: queuedActions
) {
1146 action
.execute(context
);
1147 } catch (Throwable e
) {
1148 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1149 && e
.getCause() instanceof InterruptedException
) {
1153 logger
.warn("Message action failed.", e
);
1157 Thread
.currentThread().interrupt();
1162 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1163 final RecipientId recipientId
;
1165 recipientId
= resolveRecipient(recipient
);
1166 } catch (IOException e
) {
1169 return contactHelper
.isContactBlocked(recipientId
);
1173 public void sendContacts() throws IOException
{
1174 syncHelper
.sendContacts();
1178 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1179 return account
.getContactStore()
1182 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1183 .collect(Collectors
.toList());
1187 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1188 final RecipientId recipientId
;
1190 recipientId
= resolveRecipient(recipient
);
1191 } catch (IOException e
) {
1195 final var contact
= account
.getContactStore().getContact(recipientId
);
1196 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1197 return contact
.getName();
1200 final var profile
= getRecipientProfile(recipientId
);
1201 if (profile
!= null) {
1202 return profile
.getDisplayName();
1209 public Group
getGroup(GroupId groupId
) {
1210 return toGroup(groupHelper
.getGroup(groupId
));
1213 private GroupInfo
getGroupInfo(GroupId groupId
) {
1214 return groupHelper
.getGroup(groupId
);
1218 public List
<Identity
> getIdentities() {
1219 return account
.getIdentityKeyStore()
1222 .map(this::toIdentity
)
1223 .collect(Collectors
.toList());
1226 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1227 if (identityInfo
== null) {
1231 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1232 final var scannableFingerprint
= identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1233 identityInfo
.getIdentityKey());
1234 return new Identity(address
,
1235 identityInfo
.getIdentityKey(),
1236 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1237 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1238 identityInfo
.getTrustLevel(),
1239 identityInfo
.getDateAdded());
1243 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1244 IdentityInfo identity
;
1246 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1247 } catch (IOException e
) {
1250 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1254 * Trust this the identity with this fingerprint
1256 * @param recipient username of the identity
1257 * @param fingerprint Fingerprint
1260 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1261 RecipientId recipientId
;
1263 recipientId
= resolveRecipient(recipient
);
1264 } catch (IOException e
) {
1267 return identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1271 * Trust this the identity with this safety number
1273 * @param recipient username of the identity
1274 * @param safetyNumber Safety number
1277 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1278 RecipientId recipientId
;
1280 recipientId
= resolveRecipient(recipient
);
1281 } catch (IOException e
) {
1284 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1288 * Trust this the identity with this scannable safety number
1290 * @param recipient username of the identity
1291 * @param safetyNumber Scannable safety number
1294 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1295 RecipientId recipientId
;
1297 recipientId
= resolveRecipient(recipient
);
1298 } catch (IOException e
) {
1301 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1305 * Trust all keys of this identity without verification
1307 * @param recipient username of the identity
1310 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1311 RecipientId recipientId
;
1313 recipientId
= resolveRecipient(recipient
);
1314 } catch (IOException e
) {
1317 return identityHelper
.trustIdentityAllKeys(recipientId
);
1320 private void handleIdentityFailure(
1321 final RecipientId recipientId
,
1322 final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
.IdentityFailure identityFailure
1324 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1327 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1328 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1329 if (address
.getUuid().isPresent()) {
1330 return address
.toSignalServiceAddress();
1333 // Address in recipient store doesn't have a uuid, this shouldn't happen
1334 // Try to retrieve the uuid from the server
1335 final var number
= address
.getNumber().get();
1338 aci
= getRegisteredUser(number
);
1339 } catch (IOException e
) {
1340 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1341 // Return SignalServiceAddress with unknown UUID
1342 return address
.toSignalServiceAddress();
1344 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(aci
));
1347 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
1348 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1349 for (var number
: recipients
) {
1350 final var recipientId
= resolveRecipient(number
);
1351 recipientIds
.add(recipientId
);
1353 return recipientIds
;
1356 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
1357 if (recipient
instanceof RecipientIdentifier
.Uuid uuidRecipient
) {
1358 return account
.getRecipientStore().resolveRecipient(ACI
.from(uuidRecipient
.uuid()));
1360 final var number
= ((RecipientIdentifier
.Number
) recipient
).number();
1361 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1363 return getRegisteredUser(number
);
1364 } catch (IOException e
) {
1371 private RecipientId
resolveRecipient(RecipientAddress address
) {
1372 return account
.getRecipientStore().resolveRecipient(address
);
1375 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1376 return account
.getRecipientStore().resolveRecipient(address
);
1379 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1380 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1384 public void close() throws IOException
{
1388 private void close(boolean closeAccount
) throws IOException
{
1390 synchronized (messageHandlers
) {
1391 weakHandlers
.clear();
1392 messageHandlers
.clear();
1393 thread
= receiveThread
;
1394 receiveThread
= null;
1396 if (thread
!= null) {
1397 stopReceiveThread(thread
);
1399 executor
.shutdown();
1401 dependencies
.getSignalWebSocket().disconnect();
1403 if (closeAccount
&& account
!= null) {