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
.ArrayList
;
99 import java
.util
.Collection
;
100 import java
.util
.HashMap
;
101 import java
.util
.HashSet
;
102 import java
.util
.List
;
103 import java
.util
.Map
;
104 import java
.util
.Set
;
105 import java
.util
.UUID
;
106 import java
.util
.concurrent
.ExecutorService
;
107 import java
.util
.concurrent
.Executors
;
108 import java
.util
.concurrent
.TimeUnit
;
109 import java
.util
.concurrent
.TimeoutException
;
110 import java
.util
.concurrent
.locks
.ReentrantLock
;
111 import java
.util
.stream
.Collectors
;
112 import java
.util
.stream
.Stream
;
114 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
116 public class ManagerImpl
implements Manager
{
118 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
120 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
121 private final SignalDependencies dependencies
;
123 private SignalAccount account
;
125 private final ExecutorService executor
= Executors
.newCachedThreadPool();
127 private final ProfileHelper profileHelper
;
128 private final PinHelper pinHelper
;
129 private final StorageHelper storageHelper
;
130 private final SendHelper sendHelper
;
131 private final SyncHelper syncHelper
;
132 private final AttachmentHelper attachmentHelper
;
133 private final GroupHelper groupHelper
;
134 private final ContactHelper contactHelper
;
135 private final IncomingMessageHandler incomingMessageHandler
;
136 private final PreKeyHelper preKeyHelper
;
137 private final IdentityHelper identityHelper
;
139 private final Context context
;
140 private boolean hasCaughtUpWithOldMessages
= false;
141 private boolean ignoreAttachments
= false;
143 private Thread receiveThread
;
144 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
145 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
146 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
147 private boolean isReceivingSynchronous
;
150 SignalAccount account
,
151 PathConfig pathConfig
,
152 ServiceEnvironmentConfig serviceEnvironmentConfig
,
155 this.account
= account
;
156 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
158 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
159 account
.getAccount(),
160 account
.getPassword(),
161 account
.getDeviceId());
162 final var sessionLock
= new SignalSessionLock() {
163 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
166 public Lock
acquire() {
168 return LEGACY_LOCK
::unlock
;
171 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
174 account
.getSignalProtocolStore(),
177 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
178 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
179 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
181 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
182 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
183 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
,
185 account
::getProfileKey
,
186 this::getRecipientProfile
);
187 this.profileHelper
= new ProfileHelper(account
,
190 unidentifiedAccessHelper
::getAccessFor
,
191 this::resolveSignalServiceAddress
);
192 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
193 this::getRecipientProfile
,
194 account
::getSelfRecipientId
,
195 dependencies
.getGroupsV2Operations(),
196 dependencies
.getGroupsV2Api(),
197 this::resolveSignalServiceAddress
);
198 this.sendHelper
= new SendHelper(account
,
200 unidentifiedAccessHelper
,
201 this::resolveSignalServiceAddress
,
202 account
.getRecipientStore(),
203 this::handleIdentityFailure
,
205 this::refreshRegisteredUser
);
206 this.groupHelper
= new GroupHelper(account
,
212 this::resolveSignalServiceAddress
,
213 account
.getRecipientStore());
214 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
215 this.contactHelper
= new ContactHelper(account
);
216 this.syncHelper
= new SyncHelper(account
,
221 this::resolveSignalServiceAddress
);
222 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
224 this.context
= new Context(account
,
233 var jobExecutor
= new JobExecutor(context
);
235 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
237 account
.getRecipientStore(),
238 this::resolveSignalServiceAddress
,
243 this::getRecipientProfile
,
245 this.identityHelper
= new IdentityHelper(account
,
247 this::resolveSignalServiceAddress
,
253 public String
getSelfNumber() {
254 return account
.getAccount();
258 public void checkAccountState() throws IOException
{
259 if (account
.getLastReceiveTimestamp() == 0) {
260 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
262 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
263 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
266 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
270 preKeyHelper
.refreshPreKeysIfNecessary();
271 if (account
.getAci() == null) {
272 account
.setAci(dependencies
.getAccountManager().getOwnAci());
274 updateAccountAttributes(null);
278 * This is used for checking a set of phone numbers for registration on Signal
280 * @param numbers The set of phone number in question
281 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
282 * @throws IOException if its unable to get the contacts to check if they're registered
285 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
286 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
288 return PhoneNumberFormatter
.formatNumber(n
, account
.getAccount());
289 } catch (InvalidNumberException e
) {
294 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
295 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
297 .filter(s
-> !s
.isEmpty())
298 .collect(Collectors
.toSet()));
300 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
301 final var number
= canonicalizedNumbers
.get(n
);
302 final var aci
= registeredUsers
.get(number
);
303 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
308 public void updateAccountAttributes(String deviceName
) throws IOException
{
309 final String encryptedDeviceName
;
310 if (deviceName
== null) {
311 encryptedDeviceName
= account
.getEncryptedDeviceName();
313 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
314 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
315 account
.setEncryptedDeviceName(encryptedDeviceName
);
317 dependencies
.getAccountManager()
318 .setAccountAttributes(encryptedDeviceName
,
320 account
.getLocalRegistrationId(),
323 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
324 account
.getSelfUnidentifiedAccessKey(),
325 account
.isUnrestrictedUnidentifiedAccess(),
327 account
.isDiscoverableByPhoneNumber());
331 public Configuration
getConfiguration() {
332 final var configurationStore
= account
.getConfigurationStore();
333 return new Configuration(java
.util
.Optional
.ofNullable(configurationStore
.getReadReceipts()),
334 java
.util
.Optional
.ofNullable(configurationStore
.getUnidentifiedDeliveryIndicators()),
335 java
.util
.Optional
.ofNullable(configurationStore
.getTypingIndicators()),
336 java
.util
.Optional
.ofNullable(configurationStore
.getLinkPreviews()));
340 public void updateConfiguration(
341 Configuration configuration
342 ) throws IOException
, NotMasterDeviceException
{
343 if (!account
.isMasterDevice()) {
344 throw new NotMasterDeviceException();
347 final var configurationStore
= account
.getConfigurationStore();
348 if (configuration
.readReceipts().isPresent()) {
349 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
351 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
352 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
354 if (configuration
.typingIndicators().isPresent()) {
355 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
357 if (configuration
.linkPreviews().isPresent()) {
358 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
360 syncHelper
.sendConfigurationMessage();
364 * @param givenName if null, the previous givenName will be kept
365 * @param familyName if null, the previous familyName will be kept
366 * @param about if null, the previous about text will be kept
367 * @param aboutEmoji if null, the previous about emoji will be kept
368 * @param avatar if avatar is null the image from the local avatar store is used (if present),
371 public void setProfile(
372 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
373 ) throws IOException
{
374 profileHelper
.setProfile(givenName
,
378 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
379 syncHelper
.sendSyncFetchProfileMessage();
383 public void unregister() throws IOException
{
384 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
385 // If this is the master device, other users can't send messages to this number anymore.
386 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
387 dependencies
.getAccountManager().setGcmId(Optional
.absent());
389 account
.setRegistered(false);
394 public void deleteAccount() throws IOException
{
396 pinHelper
.removeRegistrationLockPin();
397 } catch (IOException e
) {
398 logger
.warn("Failed to remove registration lock pin");
400 account
.setRegistrationLockPin(null, null);
402 dependencies
.getAccountManager().deleteAccount();
404 account
.setRegistered(false);
409 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
410 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
412 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
416 public List
<Device
> getLinkedDevices() throws IOException
{
417 var devices
= dependencies
.getAccountManager().getDevices();
418 account
.setMultiDevice(devices
.size() > 1);
419 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
420 return devices
.stream().map(d
-> {
421 String deviceName
= d
.getName();
422 if (deviceName
!= null) {
424 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
425 } catch (IOException e
) {
426 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
429 return new Device(d
.getId(),
433 d
.getId() == account
.getDeviceId());
434 }).collect(Collectors
.toList());
438 public void removeLinkedDevices(long deviceId
) throws IOException
{
439 dependencies
.getAccountManager().removeDevice(deviceId
);
440 var devices
= dependencies
.getAccountManager().getDevices();
441 account
.setMultiDevice(devices
.size() > 1);
445 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
446 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
448 addDevice(info
.deviceIdentifier(), info
.deviceKey());
451 private void addDevice(
452 String deviceIdentifier
, ECPublicKey deviceKey
453 ) throws IOException
, InvalidDeviceLinkException
{
454 var identityKeyPair
= account
.getIdentityKeyPair();
455 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
458 dependencies
.getAccountManager()
459 .addDevice(deviceIdentifier
,
462 Optional
.of(account
.getProfileKey().serialize()),
464 } catch (InvalidKeyException e
) {
465 throw new InvalidDeviceLinkException("Invalid device link", e
);
467 account
.setMultiDevice(true);
471 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
{
472 if (!account
.isMasterDevice()) {
473 throw new RuntimeException("Only master device can set a PIN");
475 if (pin
.isPresent()) {
476 final var masterKey
= account
.getPinMasterKey() != null
477 ? account
.getPinMasterKey()
478 : KeyUtils
.createMasterKey();
480 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
482 account
.setRegistrationLockPin(pin
.get(), masterKey
);
485 pinHelper
.removeRegistrationLockPin();
487 account
.setRegistrationLockPin(null, null);
491 void refreshPreKeys() throws IOException
{
492 preKeyHelper
.refreshPreKeys();
496 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
{
497 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
500 private Profile
getRecipientProfile(RecipientId recipientId
) {
501 return profileHelper
.getRecipientProfile(recipientId
);
505 public List
<Group
> getGroups() {
506 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
509 private Group
toGroup(final GroupInfo groupInfo
) {
510 if (groupInfo
== null) {
514 return new Group(groupInfo
.getGroupId(),
515 groupInfo
.getTitle(),
516 groupInfo
.getDescription(),
517 groupInfo
.getGroupInviteLink(),
518 groupInfo
.getMembers()
520 .map(account
.getRecipientStore()::resolveRecipientAddress
)
521 .collect(Collectors
.toSet()),
522 groupInfo
.getPendingMembers()
524 .map(account
.getRecipientStore()::resolveRecipientAddress
)
525 .collect(Collectors
.toSet()),
526 groupInfo
.getRequestingMembers()
528 .map(account
.getRecipientStore()::resolveRecipientAddress
)
529 .collect(Collectors
.toSet()),
530 groupInfo
.getAdminMembers()
532 .map(account
.getRecipientStore()::resolveRecipientAddress
)
533 .collect(Collectors
.toSet()),
534 groupInfo
.isBlocked(),
535 groupInfo
.getMessageExpirationTimer(),
536 groupInfo
.getPermissionAddMember(),
537 groupInfo
.getPermissionEditDetails(),
538 groupInfo
.getPermissionSendMessage(),
539 groupInfo
.isMember(account
.getSelfRecipientId()),
540 groupInfo
.isAdmin(account
.getSelfRecipientId()));
544 public SendGroupMessageResults
quitGroup(
545 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
546 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
547 final var newAdmins
= resolveRecipients(groupAdmins
);
548 return groupHelper
.quitGroup(groupId
, newAdmins
);
552 public void deleteGroup(GroupId groupId
) throws IOException
{
553 groupHelper
.deleteGroup(groupId
);
557 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
558 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
559 ) throws IOException
, AttachmentInvalidException
{
560 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
564 public SendGroupMessageResults
updateGroup(
565 final GroupId groupId
, final UpdateGroup updateGroup
566 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
567 return groupHelper
.updateGroup(groupId
,
568 updateGroup
.getName(),
569 updateGroup
.getDescription(),
570 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
571 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
572 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
573 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
574 updateGroup
.isResetGroupLink(),
575 updateGroup
.getGroupLinkState(),
576 updateGroup
.getAddMemberPermission(),
577 updateGroup
.getEditDetailsPermission(),
578 updateGroup
.getAvatarFile(),
579 updateGroup
.getExpirationTimer(),
580 updateGroup
.getIsAnnouncementGroup());
584 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
585 GroupInviteLinkUrl inviteLinkUrl
586 ) throws IOException
, InactiveGroupLinkException
{
587 return groupHelper
.joinGroup(inviteLinkUrl
);
590 private SendMessageResults
sendMessage(
591 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
592 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
593 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
594 long timestamp
= System
.currentTimeMillis();
595 messageBuilder
.withTimestamp(timestamp
);
596 for (final var recipient
: recipients
) {
597 if (recipient
instanceof RecipientIdentifier
.Single single
) {
598 final var recipientId
= resolveRecipient(single
);
599 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
600 results
.put(recipient
,
601 List
.of(SendMessageResult
.from(result
,
602 account
.getRecipientStore(),
603 account
.getRecipientStore()::resolveRecipientAddress
)));
604 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
605 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
606 results
.put(recipient
,
607 List
.of(SendMessageResult
.from(result
,
608 account
.getRecipientStore(),
609 account
.getRecipientStore()::resolveRecipientAddress
)));
610 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
611 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, group
.groupId());
612 results
.put(recipient
,
614 .map(sendMessageResult
-> SendMessageResult
.from(sendMessageResult
,
615 account
.getRecipientStore(),
616 account
.getRecipientStore()::resolveRecipientAddress
))
617 .collect(Collectors
.toList()));
620 return new SendMessageResults(timestamp
, results
);
623 private void sendTypingMessage(
624 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
625 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
626 final var timestamp
= System
.currentTimeMillis();
627 for (var recipient
: recipients
) {
628 if (recipient
instanceof RecipientIdentifier
.Single
) {
629 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
630 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
631 sendHelper
.sendTypingMessage(message
, recipientId
);
632 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
633 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
634 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
635 sendHelper
.sendGroupTypingMessage(message
, groupId
);
641 public void sendTypingMessage(
642 TypingAction action
, Set
<RecipientIdentifier
> recipients
643 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
644 sendTypingMessage(action
.toSignalService(), recipients
);
648 public void sendReadReceipt(
649 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
650 ) throws IOException
, UntrustedIdentityException
{
651 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
653 System
.currentTimeMillis());
655 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
659 public void sendViewedReceipt(
660 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
661 ) throws IOException
, UntrustedIdentityException
{
662 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
664 System
.currentTimeMillis());
666 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
670 public SendMessageResults
sendMessage(
671 Message message
, Set
<RecipientIdentifier
> recipients
672 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
673 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
674 applyMessage(messageBuilder
, message
);
675 return sendMessage(messageBuilder
, recipients
);
678 private void applyMessage(
679 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
680 ) throws AttachmentInvalidException
, IOException
{
681 messageBuilder
.withBody(message
.messageText());
682 final var attachments
= message
.attachments();
683 if (attachments
!= null) {
684 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
689 public SendMessageResults
sendRemoteDeleteMessage(
690 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
691 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
692 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
693 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
694 return sendMessage(messageBuilder
, recipients
);
698 public SendMessageResults
sendMessageReaction(
701 RecipientIdentifier
.Single targetAuthor
,
702 long targetSentTimestamp
,
703 Set
<RecipientIdentifier
> recipients
704 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
705 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
706 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
708 resolveSignalServiceAddress(targetAuthorRecipientId
),
709 targetSentTimestamp
);
710 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
711 return sendMessage(messageBuilder
, recipients
);
715 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
716 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
719 return sendMessage(messageBuilder
,
720 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
721 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
722 throw new AssertionError(e
);
724 for (var recipient
: recipients
) {
725 final var recipientId
= resolveRecipient(recipient
);
726 account
.getSessionStore().deleteAllSessions(recipientId
);
732 public void setContactName(
733 RecipientIdentifier
.Single recipient
, String name
734 ) throws NotMasterDeviceException
, IOException
{
735 if (!account
.isMasterDevice()) {
736 throw new NotMasterDeviceException();
738 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
742 public void setContactBlocked(
743 RecipientIdentifier
.Single recipient
, boolean blocked
744 ) throws NotMasterDeviceException
, IOException
{
745 if (!account
.isMasterDevice()) {
746 throw new NotMasterDeviceException();
748 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
749 // TODO cycle our profile key
750 syncHelper
.sendBlockedList();
754 public void setGroupBlocked(
755 final GroupId groupId
, final boolean blocked
756 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
757 if (!account
.isMasterDevice()) {
758 throw new NotMasterDeviceException();
760 groupHelper
.setGroupBlocked(groupId
, blocked
);
761 // TODO cycle our profile key
762 syncHelper
.sendBlockedList();
766 * Change the expiration timer for a contact
769 public void setExpirationTimer(
770 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
771 ) throws IOException
{
772 var recipientId
= resolveRecipient(recipient
);
773 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
774 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
776 sendMessage(messageBuilder
, Set
.of(recipient
));
777 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
778 throw new AssertionError(e
);
783 * Upload the sticker pack from path.
785 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
786 * @return if successful, returns the URL to install the sticker pack in the signal app
789 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
790 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
792 var messageSender
= dependencies
.getMessageSender();
794 var packKey
= KeyUtils
.createStickerUploadKey();
795 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
796 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
798 var sticker
= new Sticker(packId
, packKey
);
799 account
.getStickerStore().updateSticker(sticker
);
802 return new URI("https",
806 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
808 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
809 } catch (URISyntaxException e
) {
810 throw new AssertionError(e
);
815 public void requestAllSyncData() throws IOException
{
816 syncHelper
.requestAllSyncData();
817 retrieveRemoteStorage();
820 void retrieveRemoteStorage() throws IOException
{
821 if (account
.getStorageKey() != null) {
822 storageHelper
.readDataFromStorage();
826 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
827 final var address
= resolveSignalServiceAddress(recipientId
);
828 if (!address
.getNumber().isPresent()) {
831 final var number
= address
.getNumber().get();
832 final var uuid
= getRegisteredUser(number
);
833 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
836 private ACI
getRegisteredUser(final String number
) throws IOException
{
837 final Map
<String
, ACI
> aciMap
;
839 aciMap
= getRegisteredUsers(Set
.of(number
));
840 } catch (NumberFormatException e
) {
841 throw new IOException(number
, e
);
843 final var uuid
= aciMap
.get(number
);
845 throw new IOException(number
, null);
850 private Map
<String
, ACI
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
851 final Map
<String
, ACI
> registeredUsers
;
853 registeredUsers
= dependencies
.getAccountManager()
854 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
856 serviceEnvironmentConfig
.getCdsMrenclave());
857 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
858 throw new IOException(e
);
861 // Store numbers as recipients, so we have the number/uuid association
862 registeredUsers
.forEach((number
, aci
) -> resolveRecipientTrusted(new SignalServiceAddress(aci
, number
)));
864 return registeredUsers
;
867 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
868 Set
<HandleAction
> queuedActions
= new HashSet
<>();
869 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
870 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
871 if (actions
!= null) {
872 queuedActions
.addAll(actions
);
875 handleQueuedActions(queuedActions
);
878 private List
<HandleAction
> retryFailedReceivedMessage(
879 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
881 var envelope
= cachedMessage
.loadEnvelope();
882 if (envelope
== null) {
883 cachedMessage
.delete();
887 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
888 final var actions
= result
.first();
889 final var exception
= result
.second();
891 if (exception
instanceof UntrustedIdentityException
) {
892 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
893 // Envelope is more than a month old, cleaning up.
894 cachedMessage
.delete();
897 if (!envelope
.hasSourceUuid()) {
898 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
899 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
901 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
902 } catch (IOException ioException
) {
903 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
909 // If successful and for all other errors that are not recoverable, delete the cached message
910 cachedMessage
.delete();
915 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
916 if (isReceivingSynchronous
) {
917 throw new IllegalStateException("Already receiving message synchronously.");
919 synchronized (messageHandlers
) {
920 if (isWeakListener
) {
921 weakHandlers
.add(handler
);
923 messageHandlers
.add(handler
);
924 startReceiveThreadIfRequired();
929 private void startReceiveThreadIfRequired() {
930 if (receiveThread
!= null) {
933 receiveThread
= new Thread(() -> {
934 logger
.debug("Starting receiving messages");
935 while (!Thread
.interrupted()) {
937 receiveMessagesInternal(1L, TimeUnit
.HOURS
, false, (envelope
, e
) -> {
938 synchronized (messageHandlers
) {
939 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
941 h
.handleMessage(envelope
, e
);
942 } catch (Exception ex
) {
943 logger
.warn("Message handler failed, ignoring", ex
);
949 } catch (IOException e
) {
950 logger
.warn("Receiving messages failed, retrying", e
);
953 logger
.debug("Finished receiving messages");
954 hasCaughtUpWithOldMessages
= false;
955 synchronized (messageHandlers
) {
956 receiveThread
= null;
958 // Check if in the meantime another handler has been registered
959 if (!messageHandlers
.isEmpty()) {
960 logger
.debug("Another handler has been registered, starting receive thread again");
961 startReceiveThreadIfRequired();
966 receiveThread
.start();
970 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
972 synchronized (messageHandlers
) {
973 weakHandlers
.remove(handler
);
974 messageHandlers
.remove(handler
);
975 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
978 thread
= receiveThread
;
979 receiveThread
= null;
982 stopReceiveThread(thread
);
985 private void stopReceiveThread(final Thread thread
) {
989 } catch (InterruptedException ignored
) {
994 public boolean isReceiving() {
995 if (isReceivingSynchronous
) {
998 synchronized (messageHandlers
) {
999 return messageHandlers
.size() > 0;
1004 public void receiveMessages(long timeout
, TimeUnit unit
, ReceiveMessageHandler handler
) throws IOException
{
1005 receiveMessages(timeout
, unit
, true, handler
);
1009 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
1010 receiveMessages(1L, TimeUnit
.HOURS
, false, handler
);
1013 private void receiveMessages(
1014 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1015 ) throws IOException
{
1016 if (isReceiving()) {
1017 throw new IllegalStateException("Already receiving message.");
1019 isReceivingSynchronous
= true;
1020 receiveThread
= Thread
.currentThread();
1022 receiveMessagesInternal(timeout
, unit
, returnOnTimeout
, handler
);
1024 receiveThread
= null;
1025 hasCaughtUpWithOldMessages
= false;
1026 isReceivingSynchronous
= false;
1030 private void receiveMessagesInternal(
1031 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1032 ) throws IOException
{
1033 retryFailedReceivedMessages(handler
);
1035 // Use a Map here because java Set doesn't have a get method ...
1036 Map
<HandleAction
, HandleAction
> queuedActions
= new HashMap
<>();
1038 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1039 signalWebSocket
.connect();
1041 hasCaughtUpWithOldMessages
= false;
1042 var backOffCounter
= 0;
1043 final var MAX_BACKOFF_COUNTER
= 9;
1045 while (!Thread
.interrupted()) {
1046 SignalServiceEnvelope envelope
;
1047 final CachedMessage
[] cachedMessage
= {null};
1048 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1049 logger
.debug("Checking for new message from server");
1051 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1052 final var recipientId
= envelope1
.hasSourceUuid()
1053 ?
resolveRecipient(envelope1
.getSourceAddress())
1055 // store message on disk, before acknowledging receipt to the server
1056 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1060 if (result
.isPresent()) {
1061 envelope
= result
.get();
1062 logger
.debug("New message received from server");
1064 logger
.debug("Received indicator that server queue is empty");
1065 handleQueuedActions(queuedActions
.keySet());
1066 queuedActions
.clear();
1068 hasCaughtUpWithOldMessages
= true;
1069 synchronized (this) {
1073 // Continue to wait another timeout for new messages
1076 } catch (AssertionError e
) {
1077 if (e
.getCause() instanceof InterruptedException
) {
1078 Thread
.currentThread().interrupt();
1083 } catch (IOException e
) {
1084 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1085 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1086 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1087 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1088 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1090 Thread
.sleep(sleepMilliseconds
);
1091 } catch (InterruptedException interruptedException
) {
1094 hasCaughtUpWithOldMessages
= false;
1095 signalWebSocket
.connect();
1099 } catch (TimeoutException e
) {
1101 if (returnOnTimeout
) return;
1105 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
1106 for (final var h
: result
.first()) {
1107 final var existingAction
= queuedActions
.get(h
);
1108 if (existingAction
== null) {
1109 queuedActions
.put(h
, h
);
1111 existingAction
.mergeOther(h
);
1114 final var exception
= result
.second();
1116 if (hasCaughtUpWithOldMessages
) {
1117 handleQueuedActions(queuedActions
.keySet());
1118 queuedActions
.clear();
1120 if (cachedMessage
[0] != null) {
1121 if (exception
instanceof UntrustedIdentityException
) {
1122 logger
.debug("Keeping message with untrusted identity in message cache");
1123 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1124 final var recipientId
= resolveRecipient(address
);
1125 if (!envelope
.hasSourceUuid()) {
1127 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1128 } catch (IOException ioException
) {
1129 logger
.warn("Failed to move cached message to recipient folder: {}",
1130 ioException
.getMessage());
1134 cachedMessage
[0].delete();
1138 handleQueuedActions(queuedActions
.keySet());
1139 queuedActions
.clear();
1140 dependencies
.getSignalWebSocket().disconnect();
1144 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1145 this.ignoreAttachments
= ignoreAttachments
;
1149 public boolean hasCaughtUpWithOldMessages() {
1150 return hasCaughtUpWithOldMessages
;
1153 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1154 logger
.debug("Handling message actions");
1155 var interrupted
= false;
1156 for (var action
: queuedActions
) {
1158 action
.execute(context
);
1159 } catch (Throwable e
) {
1160 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1161 && e
.getCause() instanceof InterruptedException
) {
1165 logger
.warn("Message action failed.", e
);
1169 Thread
.currentThread().interrupt();
1174 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1175 final RecipientId recipientId
;
1177 recipientId
= resolveRecipient(recipient
);
1178 } catch (IOException e
) {
1181 return contactHelper
.isContactBlocked(recipientId
);
1185 public void sendContacts() throws IOException
{
1186 syncHelper
.sendContacts();
1190 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1191 return account
.getContactStore()
1194 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1195 .collect(Collectors
.toList());
1199 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1200 final RecipientId recipientId
;
1202 recipientId
= resolveRecipient(recipient
);
1203 } catch (IOException e
) {
1207 final var contact
= account
.getContactStore().getContact(recipientId
);
1208 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1209 return contact
.getName();
1212 final var profile
= getRecipientProfile(recipientId
);
1213 if (profile
!= null) {
1214 return profile
.getDisplayName();
1221 public Group
getGroup(GroupId groupId
) {
1222 return toGroup(groupHelper
.getGroup(groupId
));
1225 private GroupInfo
getGroupInfo(GroupId groupId
) {
1226 return groupHelper
.getGroup(groupId
);
1230 public List
<Identity
> getIdentities() {
1231 return account
.getIdentityKeyStore()
1234 .map(this::toIdentity
)
1235 .collect(Collectors
.toList());
1238 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1239 if (identityInfo
== null) {
1243 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1244 final var scannableFingerprint
= identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1245 identityInfo
.getIdentityKey());
1246 return new Identity(address
,
1247 identityInfo
.getIdentityKey(),
1248 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1249 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1250 identityInfo
.getTrustLevel(),
1251 identityInfo
.getDateAdded());
1255 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1256 IdentityInfo identity
;
1258 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1259 } catch (IOException e
) {
1262 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1266 * Trust this the identity with this fingerprint
1268 * @param recipient account of the identity
1269 * @param fingerprint Fingerprint
1272 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1273 RecipientId recipientId
;
1275 recipientId
= resolveRecipient(recipient
);
1276 } catch (IOException e
) {
1279 return identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1283 * Trust this the identity with this safety number
1285 * @param recipient account of the identity
1286 * @param safetyNumber Safety number
1289 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1290 RecipientId recipientId
;
1292 recipientId
= resolveRecipient(recipient
);
1293 } catch (IOException e
) {
1296 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1300 * Trust this the identity with this scannable safety number
1302 * @param recipient account of the identity
1303 * @param safetyNumber Scannable safety number
1306 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1307 RecipientId recipientId
;
1309 recipientId
= resolveRecipient(recipient
);
1310 } catch (IOException e
) {
1313 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1317 * Trust all keys of this identity without verification
1319 * @param recipient account of the identity
1322 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1323 RecipientId recipientId
;
1325 recipientId
= resolveRecipient(recipient
);
1326 } catch (IOException e
) {
1329 return identityHelper
.trustIdentityAllKeys(recipientId
);
1333 public void addClosedListener(final Runnable listener
) {
1334 synchronized (closedListeners
) {
1335 closedListeners
.add(listener
);
1339 private void handleIdentityFailure(
1340 final RecipientId recipientId
,
1341 final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
.IdentityFailure identityFailure
1343 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1346 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1347 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1348 if (address
.getUuid().isPresent()) {
1349 return address
.toSignalServiceAddress();
1352 // Address in recipient store doesn't have a uuid, this shouldn't happen
1353 // Try to retrieve the uuid from the server
1354 final var number
= address
.getNumber().get();
1357 aci
= getRegisteredUser(number
);
1358 } catch (IOException e
) {
1359 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1360 // Return SignalServiceAddress with unknown UUID
1361 return address
.toSignalServiceAddress();
1363 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(aci
));
1366 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
1367 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1368 for (var number
: recipients
) {
1369 final var recipientId
= resolveRecipient(number
);
1370 recipientIds
.add(recipientId
);
1372 return recipientIds
;
1375 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
1376 if (recipient
instanceof RecipientIdentifier
.Uuid uuidRecipient
) {
1377 return account
.getRecipientStore().resolveRecipient(ACI
.from(uuidRecipient
.uuid()));
1379 final var number
= ((RecipientIdentifier
.Number
) recipient
).number();
1380 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1382 return getRegisteredUser(number
);
1383 } catch (IOException e
) {
1390 private RecipientId
resolveRecipient(RecipientAddress address
) {
1391 return account
.getRecipientStore().resolveRecipient(address
);
1394 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1395 return account
.getRecipientStore().resolveRecipient(address
);
1398 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1399 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1403 public void close() throws IOException
{
1405 synchronized (messageHandlers
) {
1406 weakHandlers
.clear();
1407 messageHandlers
.clear();
1408 thread
= receiveThread
;
1409 receiveThread
= null;
1411 if (thread
!= null) {
1412 stopReceiveThread(thread
);
1414 executor
.shutdown();
1416 dependencies
.getSignalWebSocket().disconnect();
1418 synchronized (closedListeners
) {
1419 closedListeners
.forEach(Runnable
::run
);
1420 closedListeners
.clear();
1423 if (account
!= null) {