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
));
686 if (message
.mentions().size() > 0) {
687 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
688 for (final var m
: message
.mentions()) {
689 final var recipientId
= resolveRecipient(m
.recipient());
690 mentions
.add(new SignalServiceDataMessage
.Mention(resolveSignalServiceAddress(recipientId
).getAci(),
694 messageBuilder
.withMentions(mentions
);
699 public SendMessageResults
sendRemoteDeleteMessage(
700 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
701 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
702 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
703 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
704 return sendMessage(messageBuilder
, recipients
);
708 public SendMessageResults
sendMessageReaction(
711 RecipientIdentifier
.Single targetAuthor
,
712 long targetSentTimestamp
,
713 Set
<RecipientIdentifier
> recipients
714 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
715 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
716 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
718 resolveSignalServiceAddress(targetAuthorRecipientId
),
719 targetSentTimestamp
);
720 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
721 return sendMessage(messageBuilder
, recipients
);
725 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
726 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
729 return sendMessage(messageBuilder
,
730 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
731 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
732 throw new AssertionError(e
);
734 for (var recipient
: recipients
) {
735 final var recipientId
= resolveRecipient(recipient
);
736 account
.getSessionStore().deleteAllSessions(recipientId
);
742 public void setContactName(
743 RecipientIdentifier
.Single recipient
, String name
744 ) throws NotMasterDeviceException
, IOException
{
745 if (!account
.isMasterDevice()) {
746 throw new NotMasterDeviceException();
748 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
752 public void setContactBlocked(
753 RecipientIdentifier
.Single recipient
, boolean blocked
754 ) throws NotMasterDeviceException
, IOException
{
755 if (!account
.isMasterDevice()) {
756 throw new NotMasterDeviceException();
758 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
759 // TODO cycle our profile key
760 syncHelper
.sendBlockedList();
764 public void setGroupBlocked(
765 final GroupId groupId
, final boolean blocked
766 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
767 if (!account
.isMasterDevice()) {
768 throw new NotMasterDeviceException();
770 groupHelper
.setGroupBlocked(groupId
, blocked
);
771 // TODO cycle our profile key
772 syncHelper
.sendBlockedList();
776 * Change the expiration timer for a contact
779 public void setExpirationTimer(
780 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
781 ) throws IOException
{
782 var recipientId
= resolveRecipient(recipient
);
783 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
784 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
786 sendMessage(messageBuilder
, Set
.of(recipient
));
787 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
788 throw new AssertionError(e
);
793 * Upload the sticker pack from path.
795 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
796 * @return if successful, returns the URL to install the sticker pack in the signal app
799 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
800 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
802 var messageSender
= dependencies
.getMessageSender();
804 var packKey
= KeyUtils
.createStickerUploadKey();
805 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
806 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
808 var sticker
= new Sticker(packId
, packKey
);
809 account
.getStickerStore().updateSticker(sticker
);
812 return new URI("https",
816 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
818 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
819 } catch (URISyntaxException e
) {
820 throw new AssertionError(e
);
825 public void requestAllSyncData() throws IOException
{
826 syncHelper
.requestAllSyncData();
827 retrieveRemoteStorage();
830 void retrieveRemoteStorage() throws IOException
{
831 if (account
.getStorageKey() != null) {
832 storageHelper
.readDataFromStorage();
836 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
837 final var address
= resolveSignalServiceAddress(recipientId
);
838 if (!address
.getNumber().isPresent()) {
841 final var number
= address
.getNumber().get();
842 final var uuid
= getRegisteredUser(number
);
843 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
846 private ACI
getRegisteredUser(final String number
) throws IOException
{
847 final Map
<String
, ACI
> aciMap
;
849 aciMap
= getRegisteredUsers(Set
.of(number
));
850 } catch (NumberFormatException e
) {
851 throw new IOException(number
, e
);
853 final var uuid
= aciMap
.get(number
);
855 throw new IOException(number
, null);
860 private Map
<String
, ACI
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
861 final Map
<String
, ACI
> registeredUsers
;
863 registeredUsers
= dependencies
.getAccountManager()
864 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
866 serviceEnvironmentConfig
.getCdsMrenclave());
867 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
868 throw new IOException(e
);
871 // Store numbers as recipients, so we have the number/uuid association
872 registeredUsers
.forEach((number
, aci
) -> resolveRecipientTrusted(new SignalServiceAddress(aci
, number
)));
874 return registeredUsers
;
877 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
878 Set
<HandleAction
> queuedActions
= new HashSet
<>();
879 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
880 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
881 if (actions
!= null) {
882 queuedActions
.addAll(actions
);
885 handleQueuedActions(queuedActions
);
888 private List
<HandleAction
> retryFailedReceivedMessage(
889 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
891 var envelope
= cachedMessage
.loadEnvelope();
892 if (envelope
== null) {
893 cachedMessage
.delete();
897 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
898 final var actions
= result
.first();
899 final var exception
= result
.second();
901 if (exception
instanceof UntrustedIdentityException
) {
902 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
903 // Envelope is more than a month old, cleaning up.
904 cachedMessage
.delete();
907 if (!envelope
.hasSourceUuid()) {
908 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
909 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
911 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
912 } catch (IOException ioException
) {
913 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
919 // If successful and for all other errors that are not recoverable, delete the cached message
920 cachedMessage
.delete();
925 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
926 if (isReceivingSynchronous
) {
927 throw new IllegalStateException("Already receiving message synchronously.");
929 synchronized (messageHandlers
) {
930 if (isWeakListener
) {
931 weakHandlers
.add(handler
);
933 messageHandlers
.add(handler
);
934 startReceiveThreadIfRequired();
939 private void startReceiveThreadIfRequired() {
940 if (receiveThread
!= null) {
943 receiveThread
= new Thread(() -> {
944 logger
.debug("Starting receiving messages");
945 while (!Thread
.interrupted()) {
947 receiveMessagesInternal(1L, TimeUnit
.HOURS
, false, (envelope
, e
) -> {
948 synchronized (messageHandlers
) {
949 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
951 h
.handleMessage(envelope
, e
);
952 } catch (Exception ex
) {
953 logger
.warn("Message handler failed, ignoring", ex
);
959 } catch (IOException e
) {
960 logger
.warn("Receiving messages failed, retrying", e
);
963 logger
.debug("Finished receiving messages");
964 hasCaughtUpWithOldMessages
= false;
965 synchronized (messageHandlers
) {
966 receiveThread
= null;
968 // Check if in the meantime another handler has been registered
969 if (!messageHandlers
.isEmpty()) {
970 logger
.debug("Another handler has been registered, starting receive thread again");
971 startReceiveThreadIfRequired();
976 receiveThread
.start();
980 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
982 synchronized (messageHandlers
) {
983 weakHandlers
.remove(handler
);
984 messageHandlers
.remove(handler
);
985 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
988 thread
= receiveThread
;
989 receiveThread
= null;
992 stopReceiveThread(thread
);
995 private void stopReceiveThread(final Thread thread
) {
999 } catch (InterruptedException ignored
) {
1004 public boolean isReceiving() {
1005 if (isReceivingSynchronous
) {
1008 synchronized (messageHandlers
) {
1009 return messageHandlers
.size() > 0;
1014 public void receiveMessages(long timeout
, TimeUnit unit
, ReceiveMessageHandler handler
) throws IOException
{
1015 receiveMessages(timeout
, unit
, true, handler
);
1019 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
1020 receiveMessages(1L, TimeUnit
.HOURS
, false, handler
);
1023 private void receiveMessages(
1024 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1025 ) throws IOException
{
1026 if (isReceiving()) {
1027 throw new IllegalStateException("Already receiving message.");
1029 isReceivingSynchronous
= true;
1030 receiveThread
= Thread
.currentThread();
1032 receiveMessagesInternal(timeout
, unit
, returnOnTimeout
, handler
);
1034 receiveThread
= null;
1035 hasCaughtUpWithOldMessages
= false;
1036 isReceivingSynchronous
= false;
1040 private void receiveMessagesInternal(
1041 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1042 ) throws IOException
{
1043 retryFailedReceivedMessages(handler
);
1045 // Use a Map here because java Set doesn't have a get method ...
1046 Map
<HandleAction
, HandleAction
> queuedActions
= new HashMap
<>();
1048 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1049 signalWebSocket
.connect();
1051 hasCaughtUpWithOldMessages
= false;
1052 var backOffCounter
= 0;
1053 final var MAX_BACKOFF_COUNTER
= 9;
1055 while (!Thread
.interrupted()) {
1056 SignalServiceEnvelope envelope
;
1057 final CachedMessage
[] cachedMessage
= {null};
1058 final var nowMillis
= System
.currentTimeMillis();
1059 if (nowMillis
- account
.getLastReceiveTimestamp() > 60000) {
1060 account
.setLastReceiveTimestamp(nowMillis
);
1062 logger
.debug("Checking for new message from server");
1064 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1065 final var recipientId
= envelope1
.hasSourceUuid()
1066 ?
resolveRecipient(envelope1
.getSourceAddress())
1068 // store message on disk, before acknowledging receipt to the server
1069 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1073 if (result
.isPresent()) {
1074 envelope
= result
.get();
1075 logger
.debug("New message received from server");
1077 logger
.debug("Received indicator that server queue is empty");
1078 handleQueuedActions(queuedActions
.keySet());
1079 queuedActions
.clear();
1081 hasCaughtUpWithOldMessages
= true;
1082 synchronized (this) {
1086 // Continue to wait another timeout for new messages
1089 } catch (AssertionError e
) {
1090 if (e
.getCause() instanceof InterruptedException
) {
1091 Thread
.currentThread().interrupt();
1096 } catch (IOException e
) {
1097 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1098 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1099 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1100 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1101 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1103 Thread
.sleep(sleepMilliseconds
);
1104 } catch (InterruptedException interruptedException
) {
1107 hasCaughtUpWithOldMessages
= false;
1108 signalWebSocket
.connect();
1112 } catch (TimeoutException e
) {
1114 if (returnOnTimeout
) return;
1118 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
1119 for (final var h
: result
.first()) {
1120 final var existingAction
= queuedActions
.get(h
);
1121 if (existingAction
== null) {
1122 queuedActions
.put(h
, h
);
1124 existingAction
.mergeOther(h
);
1127 final var exception
= result
.second();
1129 if (hasCaughtUpWithOldMessages
) {
1130 handleQueuedActions(queuedActions
.keySet());
1131 queuedActions
.clear();
1133 if (cachedMessage
[0] != null) {
1134 if (exception
instanceof UntrustedIdentityException
) {
1135 logger
.debug("Keeping message with untrusted identity in message cache");
1136 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1137 final var recipientId
= resolveRecipient(address
);
1138 if (!envelope
.hasSourceUuid()) {
1140 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1141 } catch (IOException ioException
) {
1142 logger
.warn("Failed to move cached message to recipient folder: {}",
1143 ioException
.getMessage());
1147 cachedMessage
[0].delete();
1151 handleQueuedActions(queuedActions
.keySet());
1152 queuedActions
.clear();
1153 dependencies
.getSignalWebSocket().disconnect();
1157 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1158 this.ignoreAttachments
= ignoreAttachments
;
1162 public boolean hasCaughtUpWithOldMessages() {
1163 return hasCaughtUpWithOldMessages
;
1166 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1167 logger
.debug("Handling message actions");
1168 var interrupted
= false;
1169 for (var action
: queuedActions
) {
1171 action
.execute(context
);
1172 } catch (Throwable e
) {
1173 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1174 && e
.getCause() instanceof InterruptedException
) {
1178 logger
.warn("Message action failed.", e
);
1182 Thread
.currentThread().interrupt();
1187 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1188 final RecipientId recipientId
;
1190 recipientId
= resolveRecipient(recipient
);
1191 } catch (IOException e
) {
1194 return contactHelper
.isContactBlocked(recipientId
);
1198 public void sendContacts() throws IOException
{
1199 syncHelper
.sendContacts();
1203 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1204 return account
.getContactStore()
1207 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1208 .collect(Collectors
.toList());
1212 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1213 final RecipientId recipientId
;
1215 recipientId
= resolveRecipient(recipient
);
1216 } catch (IOException e
) {
1220 final var contact
= account
.getContactStore().getContact(recipientId
);
1221 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1222 return contact
.getName();
1225 final var profile
= getRecipientProfile(recipientId
);
1226 if (profile
!= null) {
1227 return profile
.getDisplayName();
1234 public Group
getGroup(GroupId groupId
) {
1235 return toGroup(groupHelper
.getGroup(groupId
));
1238 private GroupInfo
getGroupInfo(GroupId groupId
) {
1239 return groupHelper
.getGroup(groupId
);
1243 public List
<Identity
> getIdentities() {
1244 return account
.getIdentityKeyStore()
1247 .map(this::toIdentity
)
1248 .collect(Collectors
.toList());
1251 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1252 if (identityInfo
== null) {
1256 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1257 final var scannableFingerprint
= identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1258 identityInfo
.getIdentityKey());
1259 return new Identity(address
,
1260 identityInfo
.getIdentityKey(),
1261 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1262 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1263 identityInfo
.getTrustLevel(),
1264 identityInfo
.getDateAdded());
1268 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1269 IdentityInfo identity
;
1271 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1272 } catch (IOException e
) {
1275 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1279 * Trust this the identity with this fingerprint
1281 * @param recipient account of the identity
1282 * @param fingerprint Fingerprint
1285 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1286 RecipientId recipientId
;
1288 recipientId
= resolveRecipient(recipient
);
1289 } catch (IOException e
) {
1292 return identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1296 * Trust this the identity with this safety number
1298 * @param recipient account of the identity
1299 * @param safetyNumber Safety number
1302 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1303 RecipientId recipientId
;
1305 recipientId
= resolveRecipient(recipient
);
1306 } catch (IOException e
) {
1309 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1313 * Trust this the identity with this scannable safety number
1315 * @param recipient account of the identity
1316 * @param safetyNumber Scannable safety number
1319 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1320 RecipientId recipientId
;
1322 recipientId
= resolveRecipient(recipient
);
1323 } catch (IOException e
) {
1326 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1330 * Trust all keys of this identity without verification
1332 * @param recipient account of the identity
1335 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1336 RecipientId recipientId
;
1338 recipientId
= resolveRecipient(recipient
);
1339 } catch (IOException e
) {
1342 return identityHelper
.trustIdentityAllKeys(recipientId
);
1346 public void addClosedListener(final Runnable listener
) {
1347 synchronized (closedListeners
) {
1348 closedListeners
.add(listener
);
1352 private void handleIdentityFailure(
1353 final RecipientId recipientId
,
1354 final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
.IdentityFailure identityFailure
1356 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1359 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1360 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1361 if (address
.getUuid().isPresent()) {
1362 return address
.toSignalServiceAddress();
1365 // Address in recipient store doesn't have a uuid, this shouldn't happen
1366 // Try to retrieve the uuid from the server
1367 final var number
= address
.getNumber().get();
1370 aci
= getRegisteredUser(number
);
1371 } catch (IOException e
) {
1372 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1373 // Return SignalServiceAddress with unknown UUID
1374 return address
.toSignalServiceAddress();
1376 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(aci
));
1379 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
1380 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1381 for (var number
: recipients
) {
1382 final var recipientId
= resolveRecipient(number
);
1383 recipientIds
.add(recipientId
);
1385 return recipientIds
;
1388 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
1389 if (recipient
instanceof RecipientIdentifier
.Uuid uuidRecipient
) {
1390 return account
.getRecipientStore().resolveRecipient(ACI
.from(uuidRecipient
.uuid()));
1392 final var number
= ((RecipientIdentifier
.Number
) recipient
).number();
1393 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1395 return getRegisteredUser(number
);
1396 } catch (IOException e
) {
1403 private RecipientId
resolveRecipient(RecipientAddress address
) {
1404 return account
.getRecipientStore().resolveRecipient(address
);
1407 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1408 return account
.getRecipientStore().resolveRecipient(address
);
1411 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1412 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1416 public void close() throws IOException
{
1418 synchronized (messageHandlers
) {
1419 weakHandlers
.clear();
1420 messageHandlers
.clear();
1421 thread
= receiveThread
;
1422 receiveThread
= null;
1424 if (thread
!= null) {
1425 stopReceiveThread(thread
);
1427 executor
.shutdown();
1429 dependencies
.getSignalWebSocket().disconnect();
1431 synchronized (closedListeners
) {
1432 closedListeners
.forEach(Runnable
::run
);
1433 closedListeners
.clear();
1436 if (account
!= null) {