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 it's 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 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getAccount());
289 if (!canonicalizedNumber
.equals(n
)) {
290 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
292 return canonicalizedNumber
;
293 } catch (InvalidNumberException e
) {
298 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
299 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
301 .filter(s
-> !s
.isEmpty())
302 .collect(Collectors
.toSet()));
304 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
305 final var number
= canonicalizedNumbers
.get(n
);
306 final var aci
= registeredUsers
.get(number
);
307 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
312 public void updateAccountAttributes(String deviceName
) throws IOException
{
313 final String encryptedDeviceName
;
314 if (deviceName
== null) {
315 encryptedDeviceName
= account
.getEncryptedDeviceName();
317 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
318 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
319 account
.setEncryptedDeviceName(encryptedDeviceName
);
321 dependencies
.getAccountManager()
322 .setAccountAttributes(encryptedDeviceName
,
324 account
.getLocalRegistrationId(),
327 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
328 account
.getSelfUnidentifiedAccessKey(),
329 account
.isUnrestrictedUnidentifiedAccess(),
331 account
.isDiscoverableByPhoneNumber());
335 public Configuration
getConfiguration() {
336 final var configurationStore
= account
.getConfigurationStore();
337 return new Configuration(java
.util
.Optional
.ofNullable(configurationStore
.getReadReceipts()),
338 java
.util
.Optional
.ofNullable(configurationStore
.getUnidentifiedDeliveryIndicators()),
339 java
.util
.Optional
.ofNullable(configurationStore
.getTypingIndicators()),
340 java
.util
.Optional
.ofNullable(configurationStore
.getLinkPreviews()));
344 public void updateConfiguration(
345 Configuration configuration
346 ) throws IOException
, NotMasterDeviceException
{
347 if (!account
.isMasterDevice()) {
348 throw new NotMasterDeviceException();
351 final var configurationStore
= account
.getConfigurationStore();
352 if (configuration
.readReceipts().isPresent()) {
353 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
355 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
356 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
358 if (configuration
.typingIndicators().isPresent()) {
359 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
361 if (configuration
.linkPreviews().isPresent()) {
362 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
364 syncHelper
.sendConfigurationMessage();
368 * @param givenName if null, the previous givenName will be kept
369 * @param familyName if null, the previous familyName will be kept
370 * @param about if null, the previous about text will be kept
371 * @param aboutEmoji if null, the previous about emoji will be kept
372 * @param avatar if avatar is null the image from the local avatar store is used (if present),
375 public void setProfile(
376 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
377 ) throws IOException
{
378 profileHelper
.setProfile(givenName
,
382 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
383 syncHelper
.sendSyncFetchProfileMessage();
387 public void unregister() throws IOException
{
388 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
389 // If this is the master device, other users can't send messages to this number anymore.
390 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
391 dependencies
.getAccountManager().setGcmId(Optional
.absent());
393 account
.setRegistered(false);
398 public void deleteAccount() throws IOException
{
400 pinHelper
.removeRegistrationLockPin();
401 } catch (IOException e
) {
402 logger
.warn("Failed to remove registration lock pin");
404 account
.setRegistrationLockPin(null, null);
406 dependencies
.getAccountManager().deleteAccount();
408 account
.setRegistered(false);
413 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
414 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
416 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
420 public List
<Device
> getLinkedDevices() throws IOException
{
421 var devices
= dependencies
.getAccountManager().getDevices();
422 account
.setMultiDevice(devices
.size() > 1);
423 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
424 return devices
.stream().map(d
-> {
425 String deviceName
= d
.getName();
426 if (deviceName
!= null) {
428 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
429 } catch (IOException e
) {
430 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
433 return new Device(d
.getId(),
437 d
.getId() == account
.getDeviceId());
438 }).collect(Collectors
.toList());
442 public void removeLinkedDevices(long deviceId
) throws IOException
{
443 dependencies
.getAccountManager().removeDevice(deviceId
);
444 var devices
= dependencies
.getAccountManager().getDevices();
445 account
.setMultiDevice(devices
.size() > 1);
449 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
450 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
452 addDevice(info
.deviceIdentifier(), info
.deviceKey());
455 private void addDevice(
456 String deviceIdentifier
, ECPublicKey deviceKey
457 ) throws IOException
, InvalidDeviceLinkException
{
458 var identityKeyPair
= account
.getIdentityKeyPair();
459 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
462 dependencies
.getAccountManager()
463 .addDevice(deviceIdentifier
,
466 Optional
.of(account
.getProfileKey().serialize()),
468 } catch (InvalidKeyException e
) {
469 throw new InvalidDeviceLinkException("Invalid device link", e
);
471 account
.setMultiDevice(true);
475 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
{
476 if (!account
.isMasterDevice()) {
477 throw new RuntimeException("Only master device can set a PIN");
479 if (pin
.isPresent()) {
480 final var masterKey
= account
.getPinMasterKey() != null
481 ? account
.getPinMasterKey()
482 : KeyUtils
.createMasterKey();
484 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
486 account
.setRegistrationLockPin(pin
.get(), masterKey
);
489 pinHelper
.removeRegistrationLockPin();
491 account
.setRegistrationLockPin(null, null);
495 void refreshPreKeys() throws IOException
{
496 preKeyHelper
.refreshPreKeys();
500 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
{
501 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
504 private Profile
getRecipientProfile(RecipientId recipientId
) {
505 return profileHelper
.getRecipientProfile(recipientId
);
509 public List
<Group
> getGroups() {
510 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
513 private Group
toGroup(final GroupInfo groupInfo
) {
514 if (groupInfo
== null) {
518 return new Group(groupInfo
.getGroupId(),
519 groupInfo
.getTitle(),
520 groupInfo
.getDescription(),
521 groupInfo
.getGroupInviteLink(),
522 groupInfo
.getMembers()
524 .map(account
.getRecipientStore()::resolveRecipientAddress
)
525 .collect(Collectors
.toSet()),
526 groupInfo
.getPendingMembers()
528 .map(account
.getRecipientStore()::resolveRecipientAddress
)
529 .collect(Collectors
.toSet()),
530 groupInfo
.getRequestingMembers()
532 .map(account
.getRecipientStore()::resolveRecipientAddress
)
533 .collect(Collectors
.toSet()),
534 groupInfo
.getAdminMembers()
536 .map(account
.getRecipientStore()::resolveRecipientAddress
)
537 .collect(Collectors
.toSet()),
538 groupInfo
.isBlocked(),
539 groupInfo
.getMessageExpirationTimer(),
540 groupInfo
.getPermissionAddMember(),
541 groupInfo
.getPermissionEditDetails(),
542 groupInfo
.getPermissionSendMessage(),
543 groupInfo
.isMember(account
.getSelfRecipientId()),
544 groupInfo
.isAdmin(account
.getSelfRecipientId()));
548 public SendGroupMessageResults
quitGroup(
549 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
550 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
551 final var newAdmins
= resolveRecipients(groupAdmins
);
552 return groupHelper
.quitGroup(groupId
, newAdmins
);
556 public void deleteGroup(GroupId groupId
) throws IOException
{
557 groupHelper
.deleteGroup(groupId
);
561 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
562 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
563 ) throws IOException
, AttachmentInvalidException
{
564 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
568 public SendGroupMessageResults
updateGroup(
569 final GroupId groupId
, final UpdateGroup updateGroup
570 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
571 return groupHelper
.updateGroup(groupId
,
572 updateGroup
.getName(),
573 updateGroup
.getDescription(),
574 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
575 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
576 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
577 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
578 updateGroup
.isResetGroupLink(),
579 updateGroup
.getGroupLinkState(),
580 updateGroup
.getAddMemberPermission(),
581 updateGroup
.getEditDetailsPermission(),
582 updateGroup
.getAvatarFile(),
583 updateGroup
.getExpirationTimer(),
584 updateGroup
.getIsAnnouncementGroup());
588 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
589 GroupInviteLinkUrl inviteLinkUrl
590 ) throws IOException
, InactiveGroupLinkException
{
591 return groupHelper
.joinGroup(inviteLinkUrl
);
594 private SendMessageResults
sendMessage(
595 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
596 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
597 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
598 long timestamp
= System
.currentTimeMillis();
599 messageBuilder
.withTimestamp(timestamp
);
600 for (final var recipient
: recipients
) {
601 if (recipient
instanceof RecipientIdentifier
.Single single
) {
602 final var recipientId
= resolveRecipient(single
);
603 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
604 results
.put(recipient
,
605 List
.of(SendMessageResult
.from(result
,
606 account
.getRecipientStore(),
607 account
.getRecipientStore()::resolveRecipientAddress
)));
608 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
609 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
610 results
.put(recipient
,
611 List
.of(SendMessageResult
.from(result
,
612 account
.getRecipientStore(),
613 account
.getRecipientStore()::resolveRecipientAddress
)));
614 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
615 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, group
.groupId());
616 results
.put(recipient
,
618 .map(sendMessageResult
-> SendMessageResult
.from(sendMessageResult
,
619 account
.getRecipientStore(),
620 account
.getRecipientStore()::resolveRecipientAddress
))
621 .collect(Collectors
.toList()));
624 return new SendMessageResults(timestamp
, results
);
627 private SendMessageResults
sendTypingMessage(
628 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
629 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
630 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
631 final var timestamp
= System
.currentTimeMillis();
632 for (var recipient
: recipients
) {
633 if (recipient
instanceof RecipientIdentifier
.Single
) {
634 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
635 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
636 final var result
= sendHelper
.sendTypingMessage(message
, recipientId
);
637 results
.put(recipient
,
638 List
.of(SendMessageResult
.from(result
,
639 account
.getRecipientStore(),
640 account
.getRecipientStore()::resolveRecipientAddress
)));
641 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
642 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
643 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
644 final var result
= sendHelper
.sendGroupTypingMessage(message
, groupId
);
645 results
.put(recipient
,
647 .map(r
-> SendMessageResult
.from(r
,
648 account
.getRecipientStore(),
649 account
.getRecipientStore()::resolveRecipientAddress
))
650 .collect(Collectors
.toList()));
653 return new SendMessageResults(timestamp
, results
);
657 public SendMessageResults
sendTypingMessage(
658 TypingAction action
, Set
<RecipientIdentifier
> recipients
659 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
660 return sendTypingMessage(action
.toSignalService(), recipients
);
664 public SendMessageResults
sendReadReceipt(
665 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
666 ) throws IOException
{
667 final var timestamp
= System
.currentTimeMillis();
668 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
672 final var result
= sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
673 return new SendMessageResults(timestamp
,
675 List
.of(SendMessageResult
.from(result
,
676 account
.getRecipientStore(),
677 account
.getRecipientStore()::resolveRecipientAddress
))));
681 public SendMessageResults
sendViewedReceipt(
682 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
683 ) throws IOException
{
684 final var timestamp
= System
.currentTimeMillis();
685 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
689 final var result
= sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
690 return new SendMessageResults(timestamp
,
692 List
.of(SendMessageResult
.from(result
,
693 account
.getRecipientStore(),
694 account
.getRecipientStore()::resolveRecipientAddress
))));
698 public SendMessageResults
sendMessage(
699 Message message
, Set
<RecipientIdentifier
> recipients
700 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
701 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
702 applyMessage(messageBuilder
, message
);
703 return sendMessage(messageBuilder
, recipients
);
706 private void applyMessage(
707 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
708 ) throws AttachmentInvalidException
, IOException
{
709 messageBuilder
.withBody(message
.messageText());
710 final var attachments
= message
.attachments();
711 if (attachments
!= null) {
712 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
714 if (message
.mentions().size() > 0) {
715 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
717 if (message
.quote().isPresent()) {
718 final var quote
= message
.quote().get();
719 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
720 resolveSignalServiceAddress(resolveRecipient(quote
.author())),
723 resolveMentions(quote
.mentions())));
727 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
{
728 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
729 for (final var m
: mentionList
) {
730 final var recipientId
= resolveRecipient(m
.recipient());
731 mentions
.add(new SignalServiceDataMessage
.Mention(resolveSignalServiceAddress(recipientId
).getAci(),
739 public SendMessageResults
sendRemoteDeleteMessage(
740 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
741 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
742 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
743 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
744 return sendMessage(messageBuilder
, recipients
);
748 public SendMessageResults
sendMessageReaction(
751 RecipientIdentifier
.Single targetAuthor
,
752 long targetSentTimestamp
,
753 Set
<RecipientIdentifier
> recipients
754 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
755 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
756 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
758 resolveSignalServiceAddress(targetAuthorRecipientId
),
759 targetSentTimestamp
);
760 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
761 return sendMessage(messageBuilder
, recipients
);
765 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
766 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
769 return sendMessage(messageBuilder
,
770 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
771 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
772 throw new AssertionError(e
);
774 for (var recipient
: recipients
) {
775 final var recipientId
= resolveRecipient(recipient
);
776 account
.getSessionStore().deleteAllSessions(recipientId
);
782 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
783 account
.removeRecipient(resolveRecipient(recipient
));
787 public void deleteContact(final RecipientIdentifier
.Single recipient
) throws IOException
{
788 account
.getContactStore().deleteContact(resolveRecipient(recipient
));
792 public void setContactName(
793 RecipientIdentifier
.Single recipient
, String name
794 ) throws NotMasterDeviceException
, IOException
{
795 if (!account
.isMasterDevice()) {
796 throw new NotMasterDeviceException();
798 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
802 public void setContactBlocked(
803 RecipientIdentifier
.Single recipient
, boolean blocked
804 ) throws NotMasterDeviceException
, IOException
{
805 if (!account
.isMasterDevice()) {
806 throw new NotMasterDeviceException();
808 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
809 // TODO cycle our profile key
810 syncHelper
.sendBlockedList();
814 public void setGroupBlocked(
815 final GroupId groupId
, final boolean blocked
816 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
817 if (!account
.isMasterDevice()) {
818 throw new NotMasterDeviceException();
820 groupHelper
.setGroupBlocked(groupId
, blocked
);
821 // TODO cycle our profile key
822 syncHelper
.sendBlockedList();
826 * Change the expiration timer for a contact
829 public void setExpirationTimer(
830 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
831 ) throws IOException
{
832 var recipientId
= resolveRecipient(recipient
);
833 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
834 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
836 sendMessage(messageBuilder
, Set
.of(recipient
));
837 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
838 throw new AssertionError(e
);
843 * Upload the sticker pack from path.
845 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
846 * @return if successful, returns the URL to install the sticker pack in the signal app
849 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
850 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
852 var messageSender
= dependencies
.getMessageSender();
854 var packKey
= KeyUtils
.createStickerUploadKey();
855 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
856 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
858 var sticker
= new Sticker(packId
, packKey
);
859 account
.getStickerStore().updateSticker(sticker
);
862 return new URI("https",
866 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
868 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
869 } catch (URISyntaxException e
) {
870 throw new AssertionError(e
);
875 public void requestAllSyncData() throws IOException
{
876 syncHelper
.requestAllSyncData();
877 retrieveRemoteStorage();
880 void retrieveRemoteStorage() throws IOException
{
881 if (account
.getStorageKey() != null) {
882 storageHelper
.readDataFromStorage();
886 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
887 final var address
= resolveSignalServiceAddress(recipientId
);
888 if (!address
.getNumber().isPresent()) {
891 final var number
= address
.getNumber().get();
892 final var uuid
= getRegisteredUser(number
);
893 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
896 private ACI
getRegisteredUser(final String number
) throws IOException
{
897 final Map
<String
, ACI
> aciMap
;
899 aciMap
= getRegisteredUsers(Set
.of(number
));
900 } catch (NumberFormatException e
) {
901 throw new IOException(number
, e
);
903 final var uuid
= aciMap
.get(number
);
905 throw new IOException(number
, null);
910 private Map
<String
, ACI
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
911 final Map
<String
, ACI
> registeredUsers
;
913 registeredUsers
= dependencies
.getAccountManager()
914 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
916 serviceEnvironmentConfig
.getCdsMrenclave());
917 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
918 throw new IOException(e
);
921 // Store numbers as recipients, so we have the number/uuid association
922 registeredUsers
.forEach((number
, aci
) -> resolveRecipientTrusted(new SignalServiceAddress(aci
, number
)));
924 return registeredUsers
;
927 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
928 Set
<HandleAction
> queuedActions
= new HashSet
<>();
929 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
930 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
931 if (actions
!= null) {
932 queuedActions
.addAll(actions
);
935 handleQueuedActions(queuedActions
);
938 private List
<HandleAction
> retryFailedReceivedMessage(
939 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
941 var envelope
= cachedMessage
.loadEnvelope();
942 if (envelope
== null) {
943 cachedMessage
.delete();
947 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
948 final var actions
= result
.first();
949 final var exception
= result
.second();
951 if (exception
instanceof UntrustedIdentityException
) {
952 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
953 // Envelope is more than a month old, cleaning up.
954 cachedMessage
.delete();
957 if (!envelope
.hasSourceUuid()) {
958 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
959 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
961 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
962 } catch (IOException ioException
) {
963 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
969 // If successful and for all other errors that are not recoverable, delete the cached message
970 cachedMessage
.delete();
975 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
976 if (isReceivingSynchronous
) {
977 throw new IllegalStateException("Already receiving message synchronously.");
979 synchronized (messageHandlers
) {
980 if (isWeakListener
) {
981 weakHandlers
.add(handler
);
983 messageHandlers
.add(handler
);
984 startReceiveThreadIfRequired();
989 private void startReceiveThreadIfRequired() {
990 if (receiveThread
!= null) {
993 receiveThread
= new Thread(() -> {
994 logger
.debug("Starting receiving messages");
995 while (!Thread
.interrupted()) {
997 receiveMessagesInternal(1L, TimeUnit
.HOURS
, false, (envelope
, e
) -> {
998 synchronized (messageHandlers
) {
999 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
1001 h
.handleMessage(envelope
, e
);
1002 } catch (Exception ex
) {
1003 logger
.warn("Message handler failed, ignoring", ex
);
1009 } catch (IOException e
) {
1010 logger
.warn("Receiving messages failed, retrying", e
);
1013 logger
.debug("Finished receiving messages");
1014 hasCaughtUpWithOldMessages
= false;
1015 synchronized (messageHandlers
) {
1016 receiveThread
= null;
1018 // Check if in the meantime another handler has been registered
1019 if (!messageHandlers
.isEmpty()) {
1020 logger
.debug("Another handler has been registered, starting receive thread again");
1021 startReceiveThreadIfRequired();
1026 receiveThread
.start();
1030 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
1031 final Thread thread
;
1032 synchronized (messageHandlers
) {
1033 weakHandlers
.remove(handler
);
1034 messageHandlers
.remove(handler
);
1035 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
1038 thread
= receiveThread
;
1039 receiveThread
= null;
1042 stopReceiveThread(thread
);
1045 private void stopReceiveThread(final Thread thread
) {
1049 } catch (InterruptedException ignored
) {
1054 public boolean isReceiving() {
1055 if (isReceivingSynchronous
) {
1058 synchronized (messageHandlers
) {
1059 return messageHandlers
.size() > 0;
1064 public void receiveMessages(long timeout
, TimeUnit unit
, ReceiveMessageHandler handler
) throws IOException
{
1065 receiveMessages(timeout
, unit
, true, handler
);
1069 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
1070 receiveMessages(1L, TimeUnit
.HOURS
, false, handler
);
1073 private void receiveMessages(
1074 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1075 ) throws IOException
{
1076 if (isReceiving()) {
1077 throw new IllegalStateException("Already receiving message.");
1079 isReceivingSynchronous
= true;
1080 receiveThread
= Thread
.currentThread();
1082 receiveMessagesInternal(timeout
, unit
, returnOnTimeout
, handler
);
1084 receiveThread
= null;
1085 hasCaughtUpWithOldMessages
= false;
1086 isReceivingSynchronous
= false;
1090 private void receiveMessagesInternal(
1091 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1092 ) throws IOException
{
1093 retryFailedReceivedMessages(handler
);
1095 // Use a Map here because java Set doesn't have a get method ...
1096 Map
<HandleAction
, HandleAction
> queuedActions
= new HashMap
<>();
1098 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1099 signalWebSocket
.connect();
1101 hasCaughtUpWithOldMessages
= false;
1102 var backOffCounter
= 0;
1103 final var MAX_BACKOFF_COUNTER
= 9;
1105 while (!Thread
.interrupted()) {
1106 SignalServiceEnvelope envelope
;
1107 final CachedMessage
[] cachedMessage
= {null};
1108 final var nowMillis
= System
.currentTimeMillis();
1109 if (nowMillis
- account
.getLastReceiveTimestamp() > 60000) {
1110 account
.setLastReceiveTimestamp(nowMillis
);
1112 logger
.debug("Checking for new message from server");
1114 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1115 final var recipientId
= envelope1
.hasSourceUuid()
1116 ?
resolveRecipient(envelope1
.getSourceAddress())
1118 // store message on disk, before acknowledging receipt to the server
1119 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1123 if (result
.isPresent()) {
1124 envelope
= result
.get();
1125 logger
.debug("New message received from server");
1127 logger
.debug("Received indicator that server queue is empty");
1128 handleQueuedActions(queuedActions
.keySet());
1129 queuedActions
.clear();
1131 hasCaughtUpWithOldMessages
= true;
1132 synchronized (this) {
1136 // Continue to wait another timeout for new messages
1139 } catch (AssertionError e
) {
1140 if (e
.getCause() instanceof InterruptedException
) {
1141 Thread
.currentThread().interrupt();
1146 } catch (IOException e
) {
1147 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1148 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1149 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1150 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1151 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1153 Thread
.sleep(sleepMilliseconds
);
1154 } catch (InterruptedException interruptedException
) {
1157 hasCaughtUpWithOldMessages
= false;
1158 signalWebSocket
.connect();
1162 } catch (TimeoutException e
) {
1164 if (returnOnTimeout
) return;
1168 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
1169 for (final var h
: result
.first()) {
1170 final var existingAction
= queuedActions
.get(h
);
1171 if (existingAction
== null) {
1172 queuedActions
.put(h
, h
);
1174 existingAction
.mergeOther(h
);
1177 final var exception
= result
.second();
1179 if (hasCaughtUpWithOldMessages
) {
1180 handleQueuedActions(queuedActions
.keySet());
1181 queuedActions
.clear();
1183 if (cachedMessage
[0] != null) {
1184 if (exception
instanceof UntrustedIdentityException
) {
1185 logger
.debug("Keeping message with untrusted identity in message cache");
1186 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1187 final var recipientId
= resolveRecipient(address
);
1188 if (!envelope
.hasSourceUuid()) {
1190 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1191 } catch (IOException ioException
) {
1192 logger
.warn("Failed to move cached message to recipient folder: {}",
1193 ioException
.getMessage());
1197 cachedMessage
[0].delete();
1201 handleQueuedActions(queuedActions
.keySet());
1202 queuedActions
.clear();
1203 dependencies
.getSignalWebSocket().disconnect();
1207 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1208 this.ignoreAttachments
= ignoreAttachments
;
1212 public boolean hasCaughtUpWithOldMessages() {
1213 return hasCaughtUpWithOldMessages
;
1216 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1217 logger
.debug("Handling message actions");
1218 var interrupted
= false;
1219 for (var action
: queuedActions
) {
1221 action
.execute(context
);
1222 } catch (Throwable e
) {
1223 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1224 && e
.getCause() instanceof InterruptedException
) {
1228 logger
.warn("Message action failed.", e
);
1232 Thread
.currentThread().interrupt();
1237 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1238 final RecipientId recipientId
;
1240 recipientId
= resolveRecipient(recipient
);
1241 } catch (IOException e
) {
1244 return contactHelper
.isContactBlocked(recipientId
);
1248 public void sendContacts() throws IOException
{
1249 syncHelper
.sendContacts();
1253 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1254 return account
.getContactStore()
1257 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1258 .collect(Collectors
.toList());
1262 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1263 final RecipientId recipientId
;
1265 recipientId
= resolveRecipient(recipient
);
1266 } catch (IOException e
) {
1270 final var contact
= account
.getContactStore().getContact(recipientId
);
1271 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1272 return contact
.getName();
1275 final var profile
= getRecipientProfile(recipientId
);
1276 if (profile
!= null) {
1277 return profile
.getDisplayName();
1284 public Group
getGroup(GroupId groupId
) {
1285 return toGroup(groupHelper
.getGroup(groupId
));
1288 private GroupInfo
getGroupInfo(GroupId groupId
) {
1289 return groupHelper
.getGroup(groupId
);
1293 public List
<Identity
> getIdentities() {
1294 return account
.getIdentityKeyStore()
1297 .map(this::toIdentity
)
1298 .collect(Collectors
.toList());
1301 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1302 if (identityInfo
== null) {
1306 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1307 final var scannableFingerprint
= identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1308 identityInfo
.getIdentityKey());
1309 return new Identity(address
,
1310 identityInfo
.getIdentityKey(),
1311 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1312 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1313 identityInfo
.getTrustLevel(),
1314 identityInfo
.getDateAdded());
1318 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1319 IdentityInfo identity
;
1321 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1322 } catch (IOException e
) {
1325 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1329 * Trust this the identity with this fingerprint
1331 * @param recipient account of the identity
1332 * @param fingerprint Fingerprint
1335 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1336 RecipientId recipientId
;
1338 recipientId
= resolveRecipient(recipient
);
1339 } catch (IOException e
) {
1342 return identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1346 * Trust this the identity with this safety number
1348 * @param recipient account of the identity
1349 * @param safetyNumber Safety number
1352 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1353 RecipientId recipientId
;
1355 recipientId
= resolveRecipient(recipient
);
1356 } catch (IOException e
) {
1359 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1363 * Trust this the identity with this scannable safety number
1365 * @param recipient account of the identity
1366 * @param safetyNumber Scannable safety number
1369 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1370 RecipientId recipientId
;
1372 recipientId
= resolveRecipient(recipient
);
1373 } catch (IOException e
) {
1376 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1380 * Trust all keys of this identity without verification
1382 * @param recipient account of the identity
1385 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1386 RecipientId recipientId
;
1388 recipientId
= resolveRecipient(recipient
);
1389 } catch (IOException e
) {
1392 return identityHelper
.trustIdentityAllKeys(recipientId
);
1396 public void addClosedListener(final Runnable listener
) {
1397 synchronized (closedListeners
) {
1398 closedListeners
.add(listener
);
1402 private void handleIdentityFailure(
1403 final RecipientId recipientId
,
1404 final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
.IdentityFailure identityFailure
1406 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1409 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1410 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1411 if (address
.getUuid().isPresent()) {
1412 return address
.toSignalServiceAddress();
1415 // Address in recipient store doesn't have a uuid, this shouldn't happen
1416 // Try to retrieve the uuid from the server
1417 final var number
= address
.getNumber().get();
1420 aci
= getRegisteredUser(number
);
1421 } catch (IOException e
) {
1422 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1423 // Return SignalServiceAddress with unknown UUID
1424 return address
.toSignalServiceAddress();
1426 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(aci
));
1429 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
1430 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1431 for (var number
: recipients
) {
1432 final var recipientId
= resolveRecipient(number
);
1433 recipientIds
.add(recipientId
);
1435 return recipientIds
;
1438 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
1439 if (recipient
instanceof RecipientIdentifier
.Uuid uuidRecipient
) {
1440 return account
.getRecipientStore().resolveRecipient(ACI
.from(uuidRecipient
.uuid()));
1442 final var number
= ((RecipientIdentifier
.Number
) recipient
).number();
1443 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1445 return getRegisteredUser(number
);
1446 } catch (IOException e
) {
1453 private RecipientId
resolveRecipient(RecipientAddress address
) {
1454 return account
.getRecipientStore().resolveRecipient(address
);
1457 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1458 return account
.getRecipientStore().resolveRecipient(address
);
1461 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1462 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1466 public void close() throws IOException
{
1468 synchronized (messageHandlers
) {
1469 weakHandlers
.clear();
1470 messageHandlers
.clear();
1471 thread
= receiveThread
;
1472 receiveThread
= null;
1474 if (thread
!= null) {
1475 stopReceiveThread(thread
);
1477 executor
.shutdown();
1479 dependencies
.getSignalWebSocket().disconnect();
1481 synchronized (closedListeners
) {
1482 closedListeners
.forEach(Runnable
::run
);
1483 closedListeners
.clear();
1486 if (account
!= null) {