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
.push
.exceptions
.AuthorizationFailedException
;
81 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
82 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
83 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
84 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketConnectionState
;
85 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
86 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
87 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
88 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
89 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
90 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
91 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
94 import java
.io
.IOException
;
96 import java
.net
.URISyntaxException
;
97 import java
.net
.URLEncoder
;
98 import java
.nio
.charset
.StandardCharsets
;
99 import java
.security
.SignatureException
;
100 import java
.util
.ArrayList
;
101 import java
.util
.Collection
;
102 import java
.util
.HashMap
;
103 import java
.util
.HashSet
;
104 import java
.util
.List
;
105 import java
.util
.Map
;
106 import java
.util
.Set
;
107 import java
.util
.UUID
;
108 import java
.util
.concurrent
.ExecutorService
;
109 import java
.util
.concurrent
.Executors
;
110 import java
.util
.concurrent
.TimeUnit
;
111 import java
.util
.concurrent
.TimeoutException
;
112 import java
.util
.concurrent
.locks
.ReentrantLock
;
113 import java
.util
.stream
.Collectors
;
114 import java
.util
.stream
.Stream
;
116 import io
.reactivex
.rxjava3
.core
.Observable
;
117 import io
.reactivex
.rxjava3
.schedulers
.Schedulers
;
119 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
121 public class ManagerImpl
implements Manager
{
123 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
125 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
126 private final SignalDependencies dependencies
;
128 private SignalAccount account
;
130 private final ExecutorService executor
= Executors
.newCachedThreadPool();
132 private final ProfileHelper profileHelper
;
133 private final PinHelper pinHelper
;
134 private final StorageHelper storageHelper
;
135 private final SendHelper sendHelper
;
136 private final SyncHelper syncHelper
;
137 private final AttachmentHelper attachmentHelper
;
138 private final GroupHelper groupHelper
;
139 private final ContactHelper contactHelper
;
140 private final IncomingMessageHandler incomingMessageHandler
;
141 private final PreKeyHelper preKeyHelper
;
142 private final IdentityHelper identityHelper
;
144 private final Context context
;
145 private boolean hasCaughtUpWithOldMessages
= false;
146 private boolean ignoreAttachments
= false;
148 private Thread receiveThread
;
149 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
150 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
151 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
152 private boolean isReceivingSynchronous
;
155 SignalAccount account
,
156 PathConfig pathConfig
,
157 ServiceEnvironmentConfig serviceEnvironmentConfig
,
160 this.account
= account
;
161 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
163 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
164 account
.getAccount(),
165 account
.getPassword(),
166 account
.getDeviceId());
167 final var sessionLock
= new SignalSessionLock() {
168 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
171 public Lock
acquire() {
173 return LEGACY_LOCK
::unlock
;
176 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
179 account
.getSignalProtocolStore(),
182 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
183 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
184 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
186 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
187 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
188 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
,
190 account
::getProfileKey
,
191 this::getRecipientProfile
);
192 this.profileHelper
= new ProfileHelper(account
,
195 unidentifiedAccessHelper
::getAccessFor
,
196 this::resolveSignalServiceAddress
);
197 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
198 this::getRecipientProfile
,
199 account
::getSelfRecipientId
,
200 dependencies
.getGroupsV2Operations(),
201 dependencies
.getGroupsV2Api(),
202 this::resolveSignalServiceAddress
);
203 this.sendHelper
= new SendHelper(account
,
205 unidentifiedAccessHelper
,
206 this::resolveSignalServiceAddress
,
207 account
.getRecipientStore(),
208 this::handleIdentityFailure
,
210 this::refreshRegisteredUser
);
211 this.groupHelper
= new GroupHelper(account
,
217 this::resolveSignalServiceAddress
,
218 account
.getRecipientStore());
219 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
220 this.contactHelper
= new ContactHelper(account
);
221 this.syncHelper
= new SyncHelper(account
,
226 this::resolveSignalServiceAddress
);
227 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
229 this.context
= new Context(account
,
238 var jobExecutor
= new JobExecutor(context
);
240 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
242 account
.getRecipientStore(),
243 this::resolveSignalServiceAddress
,
248 this::getRecipientProfile
,
250 this.identityHelper
= new IdentityHelper(account
,
252 this::resolveSignalServiceAddress
,
258 public String
getSelfNumber() {
259 return account
.getAccount();
263 public void checkAccountState() throws IOException
{
264 if (account
.getLastReceiveTimestamp() == 0) {
265 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
267 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
268 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
271 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
276 preKeyHelper
.refreshPreKeysIfNecessary();
277 if (account
.getAci() == null) {
278 account
.setAci(ACI
.parseOrNull(dependencies
.getAccountManager().getWhoAmI().getAci()));
280 updateAccountAttributes(null);
281 } catch (AuthorizationFailedException e
) {
282 account
.setRegistered(false);
288 * This is used for checking a set of phone numbers for registration on Signal
290 * @param numbers The set of phone number in question
291 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
292 * @throws IOException if it's unable to get the contacts to check if they're registered
295 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
296 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
298 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getAccount());
299 if (!canonicalizedNumber
.equals(n
)) {
300 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
302 return canonicalizedNumber
;
303 } catch (InvalidNumberException e
) {
308 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
309 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
311 .filter(s
-> !s
.isEmpty())
312 .collect(Collectors
.toSet()));
314 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
315 final var number
= canonicalizedNumbers
.get(n
);
316 final var aci
= registeredUsers
.get(number
);
317 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
322 public void updateAccountAttributes(String deviceName
) throws IOException
{
323 final String encryptedDeviceName
;
324 if (deviceName
== null) {
325 encryptedDeviceName
= account
.getEncryptedDeviceName();
327 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
328 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
329 account
.setEncryptedDeviceName(encryptedDeviceName
);
331 dependencies
.getAccountManager()
332 .setAccountAttributes(encryptedDeviceName
,
334 account
.getLocalRegistrationId(),
337 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
338 account
.getSelfUnidentifiedAccessKey(),
339 account
.isUnrestrictedUnidentifiedAccess(),
341 account
.isDiscoverableByPhoneNumber());
345 public Configuration
getConfiguration() {
346 final var configurationStore
= account
.getConfigurationStore();
347 return new Configuration(java
.util
.Optional
.ofNullable(configurationStore
.getReadReceipts()),
348 java
.util
.Optional
.ofNullable(configurationStore
.getUnidentifiedDeliveryIndicators()),
349 java
.util
.Optional
.ofNullable(configurationStore
.getTypingIndicators()),
350 java
.util
.Optional
.ofNullable(configurationStore
.getLinkPreviews()));
354 public void updateConfiguration(
355 Configuration configuration
356 ) throws IOException
, NotMasterDeviceException
{
357 if (!account
.isMasterDevice()) {
358 throw new NotMasterDeviceException();
361 final var configurationStore
= account
.getConfigurationStore();
362 if (configuration
.readReceipts().isPresent()) {
363 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
365 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
366 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
368 if (configuration
.typingIndicators().isPresent()) {
369 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
371 if (configuration
.linkPreviews().isPresent()) {
372 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
374 syncHelper
.sendConfigurationMessage();
378 * @param givenName if null, the previous givenName will be kept
379 * @param familyName if null, the previous familyName will be kept
380 * @param about if null, the previous about text will be kept
381 * @param aboutEmoji if null, the previous about emoji will be kept
382 * @param avatar if avatar is null the image from the local avatar store is used (if present),
385 public void setProfile(
386 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
387 ) throws IOException
{
388 profileHelper
.setProfile(givenName
,
392 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
393 syncHelper
.sendSyncFetchProfileMessage();
397 public void unregister() throws IOException
{
398 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
399 // If this is the master device, other users can't send messages to this number anymore.
400 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
401 dependencies
.getAccountManager().setGcmId(Optional
.absent());
403 account
.setRegistered(false);
408 public void deleteAccount() throws IOException
{
410 pinHelper
.removeRegistrationLockPin();
411 } catch (IOException e
) {
412 logger
.warn("Failed to remove registration lock pin");
414 account
.setRegistrationLockPin(null, null);
416 dependencies
.getAccountManager().deleteAccount();
418 account
.setRegistered(false);
423 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
424 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
426 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
430 public List
<Device
> getLinkedDevices() throws IOException
{
431 var devices
= dependencies
.getAccountManager().getDevices();
432 account
.setMultiDevice(devices
.size() > 1);
433 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
434 return devices
.stream().map(d
-> {
435 String deviceName
= d
.getName();
436 if (deviceName
!= null) {
438 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
439 } catch (IOException e
) {
440 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
443 return new Device(d
.getId(),
447 d
.getId() == account
.getDeviceId());
448 }).collect(Collectors
.toList());
452 public void removeLinkedDevices(long deviceId
) throws IOException
{
453 dependencies
.getAccountManager().removeDevice(deviceId
);
454 var devices
= dependencies
.getAccountManager().getDevices();
455 account
.setMultiDevice(devices
.size() > 1);
459 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
460 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
462 addDevice(info
.deviceIdentifier(), info
.deviceKey());
465 private void addDevice(
466 String deviceIdentifier
, ECPublicKey deviceKey
467 ) throws IOException
, InvalidDeviceLinkException
{
468 var identityKeyPair
= account
.getIdentityKeyPair();
469 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
472 dependencies
.getAccountManager()
473 .addDevice(deviceIdentifier
,
476 Optional
.of(account
.getProfileKey().serialize()),
478 } catch (InvalidKeyException e
) {
479 throw new InvalidDeviceLinkException("Invalid device link", e
);
481 account
.setMultiDevice(true);
485 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
{
486 if (!account
.isMasterDevice()) {
487 throw new RuntimeException("Only master device can set a PIN");
489 if (pin
.isPresent()) {
490 final var masterKey
= account
.getPinMasterKey() != null
491 ? account
.getPinMasterKey()
492 : KeyUtils
.createMasterKey();
494 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
496 account
.setRegistrationLockPin(pin
.get(), masterKey
);
499 pinHelper
.removeRegistrationLockPin();
501 account
.setRegistrationLockPin(null, null);
505 void refreshPreKeys() throws IOException
{
506 preKeyHelper
.refreshPreKeys();
510 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
{
511 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
514 private Profile
getRecipientProfile(RecipientId recipientId
) {
515 return profileHelper
.getRecipientProfile(recipientId
);
519 public List
<Group
> getGroups() {
520 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
523 private Group
toGroup(final GroupInfo groupInfo
) {
524 if (groupInfo
== null) {
528 return new Group(groupInfo
.getGroupId(),
529 groupInfo
.getTitle(),
530 groupInfo
.getDescription(),
531 groupInfo
.getGroupInviteLink(),
532 groupInfo
.getMembers()
534 .map(account
.getRecipientStore()::resolveRecipientAddress
)
535 .collect(Collectors
.toSet()),
536 groupInfo
.getPendingMembers()
538 .map(account
.getRecipientStore()::resolveRecipientAddress
)
539 .collect(Collectors
.toSet()),
540 groupInfo
.getRequestingMembers()
542 .map(account
.getRecipientStore()::resolveRecipientAddress
)
543 .collect(Collectors
.toSet()),
544 groupInfo
.getAdminMembers()
546 .map(account
.getRecipientStore()::resolveRecipientAddress
)
547 .collect(Collectors
.toSet()),
548 groupInfo
.isBlocked(),
549 groupInfo
.getMessageExpirationTimer(),
550 groupInfo
.getPermissionAddMember(),
551 groupInfo
.getPermissionEditDetails(),
552 groupInfo
.getPermissionSendMessage(),
553 groupInfo
.isMember(account
.getSelfRecipientId()),
554 groupInfo
.isAdmin(account
.getSelfRecipientId()));
558 public SendGroupMessageResults
quitGroup(
559 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
560 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
561 final var newAdmins
= resolveRecipients(groupAdmins
);
562 return groupHelper
.quitGroup(groupId
, newAdmins
);
566 public void deleteGroup(GroupId groupId
) throws IOException
{
567 groupHelper
.deleteGroup(groupId
);
571 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
572 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
573 ) throws IOException
, AttachmentInvalidException
{
574 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
578 public SendGroupMessageResults
updateGroup(
579 final GroupId groupId
, final UpdateGroup updateGroup
580 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
581 return groupHelper
.updateGroup(groupId
,
582 updateGroup
.getName(),
583 updateGroup
.getDescription(),
584 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
585 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
586 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
587 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
588 updateGroup
.isResetGroupLink(),
589 updateGroup
.getGroupLinkState(),
590 updateGroup
.getAddMemberPermission(),
591 updateGroup
.getEditDetailsPermission(),
592 updateGroup
.getAvatarFile(),
593 updateGroup
.getExpirationTimer(),
594 updateGroup
.getIsAnnouncementGroup());
598 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
599 GroupInviteLinkUrl inviteLinkUrl
600 ) throws IOException
, InactiveGroupLinkException
{
601 return groupHelper
.joinGroup(inviteLinkUrl
);
604 private SendMessageResults
sendMessage(
605 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
606 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
607 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
608 long timestamp
= System
.currentTimeMillis();
609 messageBuilder
.withTimestamp(timestamp
);
610 for (final var recipient
: recipients
) {
611 if (recipient
instanceof RecipientIdentifier
.Single single
) {
612 final var recipientId
= resolveRecipient(single
);
613 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
614 results
.put(recipient
,
615 List
.of(SendMessageResult
.from(result
,
616 account
.getRecipientStore(),
617 account
.getRecipientStore()::resolveRecipientAddress
)));
618 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
619 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
620 results
.put(recipient
,
621 List
.of(SendMessageResult
.from(result
,
622 account
.getRecipientStore(),
623 account
.getRecipientStore()::resolveRecipientAddress
)));
624 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
625 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, group
.groupId());
626 results
.put(recipient
,
628 .map(sendMessageResult
-> SendMessageResult
.from(sendMessageResult
,
629 account
.getRecipientStore(),
630 account
.getRecipientStore()::resolveRecipientAddress
))
631 .collect(Collectors
.toList()));
634 return new SendMessageResults(timestamp
, results
);
637 private SendMessageResults
sendTypingMessage(
638 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
639 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
640 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
641 final var timestamp
= System
.currentTimeMillis();
642 for (var recipient
: recipients
) {
643 if (recipient
instanceof RecipientIdentifier
.Single
) {
644 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
645 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
646 final var result
= sendHelper
.sendTypingMessage(message
, recipientId
);
647 results
.put(recipient
,
648 List
.of(SendMessageResult
.from(result
,
649 account
.getRecipientStore(),
650 account
.getRecipientStore()::resolveRecipientAddress
)));
651 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
652 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
653 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
654 final var result
= sendHelper
.sendGroupTypingMessage(message
, groupId
);
655 results
.put(recipient
,
657 .map(r
-> SendMessageResult
.from(r
,
658 account
.getRecipientStore(),
659 account
.getRecipientStore()::resolveRecipientAddress
))
660 .collect(Collectors
.toList()));
663 return new SendMessageResults(timestamp
, results
);
667 public SendMessageResults
sendTypingMessage(
668 TypingAction action
, Set
<RecipientIdentifier
> recipients
669 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
670 return sendTypingMessage(action
.toSignalService(), recipients
);
674 public SendMessageResults
sendReadReceipt(
675 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
676 ) throws IOException
{
677 final var timestamp
= System
.currentTimeMillis();
678 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
682 final var result
= sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
683 return new SendMessageResults(timestamp
,
685 List
.of(SendMessageResult
.from(result
,
686 account
.getRecipientStore(),
687 account
.getRecipientStore()::resolveRecipientAddress
))));
691 public SendMessageResults
sendViewedReceipt(
692 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
693 ) throws IOException
{
694 final var timestamp
= System
.currentTimeMillis();
695 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
699 final var result
= sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
700 return new SendMessageResults(timestamp
,
702 List
.of(SendMessageResult
.from(result
,
703 account
.getRecipientStore(),
704 account
.getRecipientStore()::resolveRecipientAddress
))));
708 public SendMessageResults
sendMessage(
709 Message message
, Set
<RecipientIdentifier
> recipients
710 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
711 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
712 applyMessage(messageBuilder
, message
);
713 return sendMessage(messageBuilder
, recipients
);
716 private void applyMessage(
717 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
718 ) throws AttachmentInvalidException
, IOException
{
719 messageBuilder
.withBody(message
.messageText());
720 final var attachments
= message
.attachments();
721 if (attachments
!= null) {
722 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
724 if (message
.mentions().size() > 0) {
725 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
727 if (message
.quote().isPresent()) {
728 final var quote
= message
.quote().get();
729 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
730 resolveSignalServiceAddress(resolveRecipient(quote
.author())),
733 resolveMentions(quote
.mentions())));
737 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
{
738 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
739 for (final var m
: mentionList
) {
740 final var recipientId
= resolveRecipient(m
.recipient());
741 mentions
.add(new SignalServiceDataMessage
.Mention(resolveSignalServiceAddress(recipientId
).getAci(),
749 public SendMessageResults
sendRemoteDeleteMessage(
750 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
751 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
752 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
753 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
754 return sendMessage(messageBuilder
, recipients
);
758 public SendMessageResults
sendMessageReaction(
761 RecipientIdentifier
.Single targetAuthor
,
762 long targetSentTimestamp
,
763 Set
<RecipientIdentifier
> recipients
764 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
765 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
766 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
768 resolveSignalServiceAddress(targetAuthorRecipientId
),
769 targetSentTimestamp
);
770 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
771 return sendMessage(messageBuilder
, recipients
);
775 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
776 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
779 return sendMessage(messageBuilder
,
780 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
781 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
782 throw new AssertionError(e
);
784 for (var recipient
: recipients
) {
785 final var recipientId
= resolveRecipient(recipient
);
786 account
.getSessionStore().deleteAllSessions(recipientId
);
792 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
793 account
.removeRecipient(resolveRecipient(recipient
));
797 public void deleteContact(final RecipientIdentifier
.Single recipient
) throws IOException
{
798 account
.getContactStore().deleteContact(resolveRecipient(recipient
));
802 public void setContactName(
803 RecipientIdentifier
.Single recipient
, String name
804 ) throws NotMasterDeviceException
, IOException
{
805 if (!account
.isMasterDevice()) {
806 throw new NotMasterDeviceException();
808 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
812 public void setContactBlocked(
813 RecipientIdentifier
.Single recipient
, boolean blocked
814 ) throws NotMasterDeviceException
, IOException
{
815 if (!account
.isMasterDevice()) {
816 throw new NotMasterDeviceException();
818 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
819 // TODO cycle our profile key
820 syncHelper
.sendBlockedList();
824 public void setGroupBlocked(
825 final GroupId groupId
, final boolean blocked
826 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
827 if (!account
.isMasterDevice()) {
828 throw new NotMasterDeviceException();
830 groupHelper
.setGroupBlocked(groupId
, blocked
);
831 // TODO cycle our profile key
832 syncHelper
.sendBlockedList();
836 * Change the expiration timer for a contact
839 public void setExpirationTimer(
840 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
841 ) throws IOException
{
842 var recipientId
= resolveRecipient(recipient
);
843 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
844 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
846 sendMessage(messageBuilder
, Set
.of(recipient
));
847 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
848 throw new AssertionError(e
);
853 * Upload the sticker pack from path.
855 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
856 * @return if successful, returns the URL to install the sticker pack in the signal app
859 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
860 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
862 var messageSender
= dependencies
.getMessageSender();
864 var packKey
= KeyUtils
.createStickerUploadKey();
865 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
866 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
868 var sticker
= new Sticker(packId
, packKey
);
869 account
.getStickerStore().updateSticker(sticker
);
872 return new URI("https",
876 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
878 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
879 } catch (URISyntaxException e
) {
880 throw new AssertionError(e
);
885 public void requestAllSyncData() throws IOException
{
886 syncHelper
.requestAllSyncData();
887 retrieveRemoteStorage();
890 void retrieveRemoteStorage() throws IOException
{
891 if (account
.getStorageKey() != null) {
892 storageHelper
.readDataFromStorage();
896 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
897 final var address
= resolveSignalServiceAddress(recipientId
);
898 if (!address
.getNumber().isPresent()) {
901 final var number
= address
.getNumber().get();
902 final var uuid
= getRegisteredUser(number
);
903 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
906 private ACI
getRegisteredUser(final String number
) throws IOException
{
907 final Map
<String
, ACI
> aciMap
;
909 aciMap
= getRegisteredUsers(Set
.of(number
));
910 } catch (NumberFormatException e
) {
911 throw new IOException(number
, e
);
913 final var uuid
= aciMap
.get(number
);
915 throw new IOException(number
, null);
920 private Map
<String
, ACI
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
921 final Map
<String
, ACI
> registeredUsers
;
923 registeredUsers
= dependencies
.getAccountManager()
924 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
926 serviceEnvironmentConfig
.getCdsMrenclave());
927 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
928 throw new IOException(e
);
931 // Store numbers as recipients, so we have the number/uuid association
932 registeredUsers
.forEach((number
, aci
) -> resolveRecipientTrusted(new SignalServiceAddress(aci
, number
)));
934 return registeredUsers
;
937 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
938 Set
<HandleAction
> queuedActions
= new HashSet
<>();
939 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
940 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
941 if (actions
!= null) {
942 queuedActions
.addAll(actions
);
945 handleQueuedActions(queuedActions
);
948 private List
<HandleAction
> retryFailedReceivedMessage(
949 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
951 var envelope
= cachedMessage
.loadEnvelope();
952 if (envelope
== null) {
953 cachedMessage
.delete();
957 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
958 final var actions
= result
.first();
959 final var exception
= result
.second();
961 if (exception
instanceof UntrustedIdentityException
) {
962 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
963 // Envelope is more than a month old, cleaning up.
964 cachedMessage
.delete();
967 if (!envelope
.hasSourceUuid()) {
968 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
969 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
971 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
972 } catch (IOException ioException
) {
973 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
979 // If successful and for all other errors that are not recoverable, delete the cached message
980 cachedMessage
.delete();
985 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
986 if (isReceivingSynchronous
) {
987 throw new IllegalStateException("Already receiving message synchronously.");
989 synchronized (messageHandlers
) {
990 if (isWeakListener
) {
991 weakHandlers
.add(handler
);
993 messageHandlers
.add(handler
);
994 startReceiveThreadIfRequired();
999 private void startReceiveThreadIfRequired() {
1000 if (receiveThread
!= null) {
1003 receiveThread
= new Thread(() -> {
1004 logger
.debug("Starting receiving messages");
1005 while (!Thread
.interrupted()) {
1007 receiveMessagesInternal(1L, TimeUnit
.HOURS
, false, (envelope
, e
) -> {
1008 synchronized (messageHandlers
) {
1009 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
1011 h
.handleMessage(envelope
, e
);
1012 } catch (Exception ex
) {
1013 logger
.warn("Message handler failed, ignoring", ex
);
1019 } catch (IOException e
) {
1020 logger
.warn("Receiving messages failed, retrying", e
);
1023 logger
.debug("Finished receiving messages");
1024 hasCaughtUpWithOldMessages
= false;
1025 synchronized (messageHandlers
) {
1026 receiveThread
= null;
1028 // Check if in the meantime another handler has been registered
1029 if (!messageHandlers
.isEmpty()) {
1030 logger
.debug("Another handler has been registered, starting receive thread again");
1031 startReceiveThreadIfRequired();
1036 receiveThread
.start();
1040 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
1041 final Thread thread
;
1042 synchronized (messageHandlers
) {
1043 weakHandlers
.remove(handler
);
1044 messageHandlers
.remove(handler
);
1045 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
1048 thread
= receiveThread
;
1049 receiveThread
= null;
1052 stopReceiveThread(thread
);
1055 private void stopReceiveThread(final Thread thread
) {
1059 } catch (InterruptedException ignored
) {
1064 public boolean isReceiving() {
1065 if (isReceivingSynchronous
) {
1068 synchronized (messageHandlers
) {
1069 return messageHandlers
.size() > 0;
1074 public void receiveMessages(long timeout
, TimeUnit unit
, ReceiveMessageHandler handler
) throws IOException
{
1075 receiveMessages(timeout
, unit
, true, handler
);
1079 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
1080 receiveMessages(1L, TimeUnit
.HOURS
, false, handler
);
1083 private void receiveMessages(
1084 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1085 ) throws IOException
{
1086 if (isReceiving()) {
1087 throw new IllegalStateException("Already receiving message.");
1089 isReceivingSynchronous
= true;
1090 receiveThread
= Thread
.currentThread();
1092 receiveMessagesInternal(timeout
, unit
, returnOnTimeout
, handler
);
1094 receiveThread
= null;
1095 hasCaughtUpWithOldMessages
= false;
1096 isReceivingSynchronous
= false;
1100 private void receiveMessagesInternal(
1101 long timeout
, TimeUnit unit
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1102 ) throws IOException
{
1103 retryFailedReceivedMessages(handler
);
1105 // Use a Map here because java Set doesn't have a get method ...
1106 Map
<HandleAction
, HandleAction
> queuedActions
= new HashMap
<>();
1108 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1109 final var webSocketStateDisposable
= Observable
.merge(signalWebSocket
.getUnidentifiedWebSocketState(),
1110 signalWebSocket
.getWebSocketState())
1111 .subscribeOn(Schedulers
.computation())
1112 .observeOn(Schedulers
.computation())
1113 .distinctUntilChanged()
1114 .subscribe(this::onWebSocketStateChange
);
1115 signalWebSocket
.connect();
1117 hasCaughtUpWithOldMessages
= false;
1118 var backOffCounter
= 0;
1119 final var MAX_BACKOFF_COUNTER
= 9;
1121 while (!Thread
.interrupted()) {
1122 SignalServiceEnvelope envelope
;
1123 final CachedMessage
[] cachedMessage
= {null};
1124 final var nowMillis
= System
.currentTimeMillis();
1125 if (nowMillis
- account
.getLastReceiveTimestamp() > 60000) {
1126 account
.setLastReceiveTimestamp(nowMillis
);
1128 logger
.debug("Checking for new message from server");
1130 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1131 final var recipientId
= envelope1
.hasSourceUuid()
1132 ?
resolveRecipient(envelope1
.getSourceAddress())
1134 // store message on disk, before acknowledging receipt to the server
1135 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1139 if (result
.isPresent()) {
1140 envelope
= result
.get();
1141 logger
.debug("New message received from server");
1143 logger
.debug("Received indicator that server queue is empty");
1144 handleQueuedActions(queuedActions
.keySet());
1145 queuedActions
.clear();
1147 hasCaughtUpWithOldMessages
= true;
1148 synchronized (this) {
1152 // Continue to wait another timeout for new messages
1155 } catch (AssertionError e
) {
1156 if (e
.getCause() instanceof InterruptedException
) {
1157 Thread
.currentThread().interrupt();
1162 } catch (IOException e
) {
1163 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1164 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1165 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1166 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1167 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1169 Thread
.sleep(sleepMilliseconds
);
1170 } catch (InterruptedException interruptedException
) {
1173 hasCaughtUpWithOldMessages
= false;
1174 signalWebSocket
.connect();
1178 } catch (TimeoutException e
) {
1180 if (returnOnTimeout
) return;
1184 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
1185 for (final var h
: result
.first()) {
1186 final var existingAction
= queuedActions
.get(h
);
1187 if (existingAction
== null) {
1188 queuedActions
.put(h
, h
);
1190 existingAction
.mergeOther(h
);
1193 final var exception
= result
.second();
1195 if (hasCaughtUpWithOldMessages
) {
1196 handleQueuedActions(queuedActions
.keySet());
1197 queuedActions
.clear();
1199 if (cachedMessage
[0] != null) {
1200 if (exception
instanceof UntrustedIdentityException
) {
1201 logger
.debug("Keeping message with untrusted identity in message cache");
1202 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1203 final var recipientId
= resolveRecipient(address
);
1204 if (!envelope
.hasSourceUuid()) {
1206 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1207 } catch (IOException ioException
) {
1208 logger
.warn("Failed to move cached message to recipient folder: {}",
1209 ioException
.getMessage());
1213 cachedMessage
[0].delete();
1217 handleQueuedActions(queuedActions
.keySet());
1218 queuedActions
.clear();
1219 dependencies
.getSignalWebSocket().disconnect();
1220 webSocketStateDisposable
.dispose();
1223 private void onWebSocketStateChange(final WebSocketConnectionState s
) {
1224 if (s
.equals(WebSocketConnectionState
.AUTHENTICATION_FAILED
)) {
1225 account
.setRegistered(false);
1228 } catch (IOException e
) {
1229 e
.printStackTrace();
1235 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1236 this.ignoreAttachments
= ignoreAttachments
;
1240 public boolean hasCaughtUpWithOldMessages() {
1241 return hasCaughtUpWithOldMessages
;
1244 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1245 logger
.debug("Handling message actions");
1246 var interrupted
= false;
1247 for (var action
: queuedActions
) {
1249 action
.execute(context
);
1250 } catch (Throwable e
) {
1251 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1252 && e
.getCause() instanceof InterruptedException
) {
1256 logger
.warn("Message action failed.", e
);
1260 Thread
.currentThread().interrupt();
1265 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1266 final RecipientId recipientId
;
1268 recipientId
= resolveRecipient(recipient
);
1269 } catch (IOException e
) {
1272 return contactHelper
.isContactBlocked(recipientId
);
1276 public void sendContacts() throws IOException
{
1277 syncHelper
.sendContacts();
1281 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1282 return account
.getContactStore()
1285 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1286 .collect(Collectors
.toList());
1290 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1291 final RecipientId recipientId
;
1293 recipientId
= resolveRecipient(recipient
);
1294 } catch (IOException e
) {
1298 final var contact
= account
.getContactStore().getContact(recipientId
);
1299 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1300 return contact
.getName();
1303 final var profile
= getRecipientProfile(recipientId
);
1304 if (profile
!= null) {
1305 return profile
.getDisplayName();
1312 public Group
getGroup(GroupId groupId
) {
1313 return toGroup(groupHelper
.getGroup(groupId
));
1316 private GroupInfo
getGroupInfo(GroupId groupId
) {
1317 return groupHelper
.getGroup(groupId
);
1321 public List
<Identity
> getIdentities() {
1322 return account
.getIdentityKeyStore()
1325 .map(this::toIdentity
)
1326 .collect(Collectors
.toList());
1329 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1330 if (identityInfo
== null) {
1334 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1335 final var scannableFingerprint
= identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1336 identityInfo
.getIdentityKey());
1337 return new Identity(address
,
1338 identityInfo
.getIdentityKey(),
1339 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1340 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1341 identityInfo
.getTrustLevel(),
1342 identityInfo
.getDateAdded());
1346 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1347 IdentityInfo identity
;
1349 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1350 } catch (IOException e
) {
1353 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1357 * Trust this the identity with this fingerprint
1359 * @param recipient account of the identity
1360 * @param fingerprint Fingerprint
1363 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1364 RecipientId recipientId
;
1366 recipientId
= resolveRecipient(recipient
);
1367 } catch (IOException e
) {
1370 return identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1374 * Trust this the identity with this safety number
1376 * @param recipient account of the identity
1377 * @param safetyNumber Safety number
1380 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1381 RecipientId recipientId
;
1383 recipientId
= resolveRecipient(recipient
);
1384 } catch (IOException e
) {
1387 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1391 * Trust this the identity with this scannable safety number
1393 * @param recipient account of the identity
1394 * @param safetyNumber Scannable safety number
1397 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1398 RecipientId recipientId
;
1400 recipientId
= resolveRecipient(recipient
);
1401 } catch (IOException e
) {
1404 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1408 * Trust all keys of this identity without verification
1410 * @param recipient account of the identity
1413 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1414 RecipientId recipientId
;
1416 recipientId
= resolveRecipient(recipient
);
1417 } catch (IOException e
) {
1420 return identityHelper
.trustIdentityAllKeys(recipientId
);
1424 public void addClosedListener(final Runnable listener
) {
1425 synchronized (closedListeners
) {
1426 closedListeners
.add(listener
);
1430 private void handleIdentityFailure(
1431 final RecipientId recipientId
,
1432 final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
.IdentityFailure identityFailure
1434 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1437 private SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1438 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1439 if (address
.uuid().isPresent()) {
1440 return address
.toSignalServiceAddress();
1443 // Address in recipient store doesn't have a uuid, this shouldn't happen
1444 // Try to retrieve the uuid from the server
1445 final var number
= address
.number().get();
1448 aci
= getRegisteredUser(number
);
1449 } catch (IOException e
) {
1450 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1451 // Return SignalServiceAddress with unknown UUID
1452 return address
.toSignalServiceAddress();
1454 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(aci
));
1457 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
1458 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1459 for (var number
: recipients
) {
1460 final var recipientId
= resolveRecipient(number
);
1461 recipientIds
.add(recipientId
);
1463 return recipientIds
;
1466 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
1467 if (recipient
instanceof RecipientIdentifier
.Uuid uuidRecipient
) {
1468 return account
.getRecipientStore().resolveRecipient(ACI
.from(uuidRecipient
.uuid()));
1470 final var number
= ((RecipientIdentifier
.Number
) recipient
).number();
1471 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1473 return getRegisteredUser(number
);
1474 } catch (IOException e
) {
1481 private RecipientId
resolveRecipient(RecipientAddress address
) {
1482 return account
.getRecipientStore().resolveRecipient(address
);
1485 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1486 return account
.getRecipientStore().resolveRecipient(address
);
1489 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1490 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1494 public void close() throws IOException
{
1496 synchronized (messageHandlers
) {
1497 weakHandlers
.clear();
1498 messageHandlers
.clear();
1499 thread
= receiveThread
;
1500 receiveThread
= null;
1502 if (thread
!= null) {
1503 stopReceiveThread(thread
);
1505 executor
.shutdown();
1507 dependencies
.getSignalWebSocket().disconnect();
1509 synchronized (closedListeners
) {
1510 closedListeners
.forEach(Runnable
::run
);
1511 closedListeners
.clear();
1514 if (account
!= null) {