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
.ServiceEnvironmentConfig
;
35 import org
.asamk
.signal
.manager
.groups
.GroupId
;
36 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
37 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
38 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
39 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
40 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
41 import org
.asamk
.signal
.manager
.helper
.AttachmentHelper
;
42 import org
.asamk
.signal
.manager
.helper
.ContactHelper
;
43 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
44 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
45 import org
.asamk
.signal
.manager
.helper
.IdentityHelper
;
46 import org
.asamk
.signal
.manager
.helper
.IncomingMessageHandler
;
47 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
48 import org
.asamk
.signal
.manager
.helper
.PreKeyHelper
;
49 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
50 import org
.asamk
.signal
.manager
.helper
.RecipientHelper
;
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
.util
.DynamicCredentialsProvider
;
87 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
88 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
91 import java
.io
.IOException
;
93 import java
.net
.URISyntaxException
;
94 import java
.net
.URLEncoder
;
95 import java
.nio
.charset
.StandardCharsets
;
96 import java
.time
.Duration
;
97 import java
.util
.ArrayList
;
98 import java
.util
.Collection
;
99 import java
.util
.HashMap
;
100 import java
.util
.HashSet
;
101 import java
.util
.List
;
102 import java
.util
.Map
;
103 import java
.util
.Set
;
104 import java
.util
.UUID
;
105 import java
.util
.concurrent
.ExecutorService
;
106 import java
.util
.concurrent
.Executors
;
107 import java
.util
.concurrent
.TimeUnit
;
108 import java
.util
.concurrent
.TimeoutException
;
109 import java
.util
.concurrent
.locks
.ReentrantLock
;
110 import java
.util
.stream
.Collectors
;
111 import java
.util
.stream
.Stream
;
113 import io
.reactivex
.rxjava3
.core
.Observable
;
114 import io
.reactivex
.rxjava3
.schedulers
.Schedulers
;
116 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
118 public class ManagerImpl
implements Manager
{
120 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
122 private final SignalDependencies dependencies
;
124 private SignalAccount account
;
126 private final ExecutorService executor
= Executors
.newCachedThreadPool();
128 private final ProfileHelper profileHelper
;
129 private final PinHelper pinHelper
;
130 private final StorageHelper storageHelper
;
131 private final SendHelper sendHelper
;
132 private final SyncHelper syncHelper
;
133 private final AttachmentHelper attachmentHelper
;
134 private final GroupHelper groupHelper
;
135 private final ContactHelper contactHelper
;
136 private final IncomingMessageHandler incomingMessageHandler
;
137 private final PreKeyHelper preKeyHelper
;
138 private final IdentityHelper identityHelper
;
139 private final RecipientHelper recipientHelper
;
141 private final Context context
;
142 private boolean hasCaughtUpWithOldMessages
= false;
143 private boolean ignoreAttachments
= false;
145 private Thread receiveThread
;
146 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
147 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
148 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
149 private boolean isReceivingSynchronous
;
150 private boolean needsToRetryFailedMessages
= false;
153 SignalAccount account
,
154 PathConfig pathConfig
,
155 ServiceEnvironmentConfig serviceEnvironmentConfig
,
158 this.account
= account
;
160 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
161 account
.getAccount(),
162 account
.getPassword(),
163 account
.getDeviceId());
164 final var sessionLock
= new SignalSessionLock() {
165 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
168 public Lock
acquire() {
170 return LEGACY_LOCK
::unlock
;
173 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
176 account
.getSignalProtocolStore(),
179 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
180 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
181 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
183 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
184 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
185 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
,
187 account
::getProfileKey
,
188 this::getRecipientProfile
);
189 this.recipientHelper
= new RecipientHelper(account
, dependencies
, serviceEnvironmentConfig
);
190 this.profileHelper
= new ProfileHelper(account
,
193 unidentifiedAccessHelper
::getAccessFor
,
194 recipientHelper
::resolveSignalServiceAddress
);
195 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
,
196 account
::getSelfRecipientId
,
197 dependencies
.getGroupsV2Operations(),
198 dependencies
.getGroupsV2Api(),
199 recipientHelper
::resolveSignalServiceAddress
);
200 this.sendHelper
= new SendHelper(account
,
202 unidentifiedAccessHelper
,
203 recipientHelper
::resolveSignalServiceAddress
,
204 account
.getRecipientStore(),
205 this::handleIdentityFailure
,
208 recipientHelper
::refreshRegisteredUser
);
209 this.groupHelper
= new GroupHelper(account
,
215 recipientHelper
::resolveSignalServiceAddress
,
216 account
.getRecipientStore());
217 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
218 this.contactHelper
= new ContactHelper(account
);
219 this.syncHelper
= new SyncHelper(account
,
224 recipientHelper
::resolveSignalServiceAddress
);
225 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
227 this.context
= new Context(account
,
236 var jobExecutor
= new JobExecutor(context
);
238 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
240 account
.getRecipientStore(),
241 recipientHelper
::resolveSignalServiceAddress
,
246 profileHelper
::getRecipientProfile
,
248 this.identityHelper
= new IdentityHelper(account
,
250 recipientHelper
::resolveSignalServiceAddress
,
256 public String
getSelfNumber() {
257 return account
.getAccount();
261 public void checkAccountState() throws IOException
{
262 if (account
.getLastReceiveTimestamp() == 0) {
263 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
265 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
266 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
269 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
274 preKeyHelper
.refreshPreKeysIfNecessary();
275 if (account
.getAci() == null) {
276 account
.setAci(ACI
.parseOrNull(dependencies
.getAccountManager().getWhoAmI().getAci()));
278 updateAccountAttributes(null);
279 } catch (AuthorizationFailedException e
) {
280 account
.setRegistered(false);
286 * This is used for checking a set of phone numbers for registration on Signal
288 * @param numbers The set of phone number in question
289 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
290 * @throws IOException if it's unable to get the contacts to check if they're registered
293 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
294 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
296 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getAccount());
297 if (!canonicalizedNumber
.equals(n
)) {
298 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
300 return canonicalizedNumber
;
301 } catch (InvalidNumberException e
) {
306 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
307 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
309 .filter(s
-> !s
.isEmpty())
310 .collect(Collectors
.toSet());
311 final var registeredUsers
= recipientHelper
.getRegisteredUsers(canonicalizedNumbersSet
);
313 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
314 final var number
= canonicalizedNumbers
.get(n
);
315 final var aci
= registeredUsers
.get(number
);
316 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
321 public void updateAccountAttributes(String deviceName
) throws IOException
{
322 final String encryptedDeviceName
;
323 if (deviceName
== null) {
324 encryptedDeviceName
= account
.getEncryptedDeviceName();
326 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
327 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
328 account
.setEncryptedDeviceName(encryptedDeviceName
);
330 dependencies
.getAccountManager()
331 .setAccountAttributes(encryptedDeviceName
,
333 account
.getLocalRegistrationId(),
336 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
337 account
.getSelfUnidentifiedAccessKey(),
338 account
.isUnrestrictedUnidentifiedAccess(),
340 account
.isDiscoverableByPhoneNumber());
344 public Configuration
getConfiguration() {
345 final var configurationStore
= account
.getConfigurationStore();
346 return new Configuration(java
.util
.Optional
.ofNullable(configurationStore
.getReadReceipts()),
347 java
.util
.Optional
.ofNullable(configurationStore
.getUnidentifiedDeliveryIndicators()),
348 java
.util
.Optional
.ofNullable(configurationStore
.getTypingIndicators()),
349 java
.util
.Optional
.ofNullable(configurationStore
.getLinkPreviews()));
353 public void updateConfiguration(
354 Configuration configuration
355 ) throws IOException
, NotMasterDeviceException
{
356 if (!account
.isMasterDevice()) {
357 throw new NotMasterDeviceException();
360 final var configurationStore
= account
.getConfigurationStore();
361 if (configuration
.readReceipts().isPresent()) {
362 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
364 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
365 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
367 if (configuration
.typingIndicators().isPresent()) {
368 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
370 if (configuration
.linkPreviews().isPresent()) {
371 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
373 syncHelper
.sendConfigurationMessage();
377 * @param givenName if null, the previous givenName will be kept
378 * @param familyName if null, the previous familyName will be kept
379 * @param about if null, the previous about text will be kept
380 * @param aboutEmoji if null, the previous about emoji will be kept
381 * @param avatar if avatar is null the image from the local avatar store is used (if present),
384 public void setProfile(
385 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
386 ) throws IOException
{
387 profileHelper
.setProfile(givenName
,
391 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
392 syncHelper
.sendSyncFetchProfileMessage();
396 public void unregister() throws IOException
{
397 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
398 // If this is the master device, other users can't send messages to this number anymore.
399 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
400 dependencies
.getAccountManager().setGcmId(Optional
.absent());
402 account
.setRegistered(false);
407 public void deleteAccount() throws IOException
{
409 pinHelper
.removeRegistrationLockPin();
410 } catch (IOException e
) {
411 logger
.warn("Failed to remove registration lock pin");
413 account
.setRegistrationLockPin(null, null);
415 dependencies
.getAccountManager().deleteAccount();
417 account
.setRegistered(false);
422 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
423 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
425 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
429 public List
<Device
> getLinkedDevices() throws IOException
{
430 var devices
= dependencies
.getAccountManager().getDevices();
431 account
.setMultiDevice(devices
.size() > 1);
432 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
433 return devices
.stream().map(d
-> {
434 String deviceName
= d
.getName();
435 if (deviceName
!= null) {
437 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
438 } catch (IOException e
) {
439 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
442 return new Device(d
.getId(),
446 d
.getId() == account
.getDeviceId());
451 public void removeLinkedDevices(long deviceId
) throws IOException
{
452 dependencies
.getAccountManager().removeDevice(deviceId
);
453 var devices
= dependencies
.getAccountManager().getDevices();
454 account
.setMultiDevice(devices
.size() > 1);
458 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
459 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
461 addDevice(info
.deviceIdentifier(), info
.deviceKey());
464 private void addDevice(
465 String deviceIdentifier
, ECPublicKey deviceKey
466 ) throws IOException
, InvalidDeviceLinkException
{
467 var identityKeyPair
= account
.getIdentityKeyPair();
468 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
471 dependencies
.getAccountManager()
472 .addDevice(deviceIdentifier
,
475 Optional
.of(account
.getProfileKey().serialize()),
477 } catch (InvalidKeyException e
) {
478 throw new InvalidDeviceLinkException("Invalid device link", e
);
480 account
.setMultiDevice(true);
484 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
{
485 if (!account
.isMasterDevice()) {
486 throw new RuntimeException("Only master device can set a PIN");
488 if (pin
.isPresent()) {
489 final var masterKey
= account
.getPinMasterKey() != null
490 ? account
.getPinMasterKey()
491 : KeyUtils
.createMasterKey();
493 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
495 account
.setRegistrationLockPin(pin
.get(), masterKey
);
498 pinHelper
.removeRegistrationLockPin();
500 account
.setRegistrationLockPin(null, null);
504 void refreshPreKeys() throws IOException
{
505 preKeyHelper
.refreshPreKeys();
509 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
{
510 return profileHelper
.getRecipientProfile(recipientHelper
.resolveRecipient(recipient
));
513 private Profile
getRecipientProfile(RecipientId recipientId
) {
514 return profileHelper
.getRecipientProfile(recipientId
);
518 public List
<Group
> getGroups() {
519 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
522 private Group
toGroup(final GroupInfo groupInfo
) {
523 if (groupInfo
== null) {
527 return new Group(groupInfo
.getGroupId(),
528 groupInfo
.getTitle(),
529 groupInfo
.getDescription(),
530 groupInfo
.getGroupInviteLink(),
531 groupInfo
.getMembers()
533 .map(account
.getRecipientStore()::resolveRecipientAddress
)
534 .collect(Collectors
.toSet()),
535 groupInfo
.getPendingMembers()
537 .map(account
.getRecipientStore()::resolveRecipientAddress
)
538 .collect(Collectors
.toSet()),
539 groupInfo
.getRequestingMembers()
541 .map(account
.getRecipientStore()::resolveRecipientAddress
)
542 .collect(Collectors
.toSet()),
543 groupInfo
.getAdminMembers()
545 .map(account
.getRecipientStore()::resolveRecipientAddress
)
546 .collect(Collectors
.toSet()),
547 groupInfo
.isBlocked(),
548 groupInfo
.getMessageExpirationTimer(),
549 groupInfo
.getPermissionAddMember(),
550 groupInfo
.getPermissionEditDetails(),
551 groupInfo
.getPermissionSendMessage(),
552 groupInfo
.isMember(account
.getSelfRecipientId()),
553 groupInfo
.isAdmin(account
.getSelfRecipientId()));
557 public SendGroupMessageResults
quitGroup(
558 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
559 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
560 final var newAdmins
= recipientHelper
.resolveRecipients(groupAdmins
);
561 return groupHelper
.quitGroup(groupId
, newAdmins
);
565 public void deleteGroup(GroupId groupId
) throws IOException
{
566 groupHelper
.deleteGroup(groupId
);
570 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
571 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
572 ) throws IOException
, AttachmentInvalidException
{
573 return groupHelper
.createGroup(name
,
574 members
== null ?
null : recipientHelper
.resolveRecipients(members
),
579 public SendGroupMessageResults
updateGroup(
580 final GroupId groupId
, final UpdateGroup updateGroup
581 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
582 return groupHelper
.updateGroup(groupId
,
583 updateGroup
.getName(),
584 updateGroup
.getDescription(),
585 updateGroup
.getMembers() == null ?
null : recipientHelper
.resolveRecipients(updateGroup
.getMembers()),
586 updateGroup
.getRemoveMembers() == null
588 : recipientHelper
.resolveRecipients(updateGroup
.getRemoveMembers()),
589 updateGroup
.getAdmins() == null ?
null : recipientHelper
.resolveRecipients(updateGroup
.getAdmins()),
590 updateGroup
.getRemoveAdmins() == null
592 : recipientHelper
.resolveRecipients(updateGroup
.getRemoveAdmins()),
593 updateGroup
.isResetGroupLink(),
594 updateGroup
.getGroupLinkState(),
595 updateGroup
.getAddMemberPermission(),
596 updateGroup
.getEditDetailsPermission(),
597 updateGroup
.getAvatarFile(),
598 updateGroup
.getExpirationTimer(),
599 updateGroup
.getIsAnnouncementGroup());
603 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
604 GroupInviteLinkUrl inviteLinkUrl
605 ) throws IOException
, InactiveGroupLinkException
{
606 return groupHelper
.joinGroup(inviteLinkUrl
);
609 private SendMessageResults
sendMessage(
610 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
611 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
612 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
613 long timestamp
= System
.currentTimeMillis();
614 messageBuilder
.withTimestamp(timestamp
);
615 for (final var recipient
: recipients
) {
616 if (recipient
instanceof RecipientIdentifier
.Single single
) {
617 final var recipientId
= recipientHelper
.resolveRecipient(single
);
618 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
619 results
.put(recipient
,
620 List
.of(SendMessageResult
.from(result
,
621 account
.getRecipientStore(),
622 account
.getRecipientStore()::resolveRecipientAddress
)));
623 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
624 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
625 results
.put(recipient
,
626 List
.of(SendMessageResult
.from(result
,
627 account
.getRecipientStore(),
628 account
.getRecipientStore()::resolveRecipientAddress
)));
629 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
630 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, group
.groupId());
631 results
.put(recipient
,
633 .map(sendMessageResult
-> SendMessageResult
.from(sendMessageResult
,
634 account
.getRecipientStore(),
635 account
.getRecipientStore()::resolveRecipientAddress
))
639 return new SendMessageResults(timestamp
, results
);
642 private SendMessageResults
sendTypingMessage(
643 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
644 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
645 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
646 final var timestamp
= System
.currentTimeMillis();
647 for (var recipient
: recipients
) {
648 if (recipient
instanceof RecipientIdentifier
.Single
) {
649 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
650 final var recipientId
= recipientHelper
.resolveRecipient((RecipientIdentifier
.Single
) recipient
);
651 final var result
= sendHelper
.sendTypingMessage(message
, recipientId
);
652 results
.put(recipient
,
653 List
.of(SendMessageResult
.from(result
,
654 account
.getRecipientStore(),
655 account
.getRecipientStore()::resolveRecipientAddress
)));
656 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
657 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
658 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
659 final var result
= sendHelper
.sendGroupTypingMessage(message
, groupId
);
660 results
.put(recipient
,
662 .map(r
-> SendMessageResult
.from(r
,
663 account
.getRecipientStore(),
664 account
.getRecipientStore()::resolveRecipientAddress
))
668 return new SendMessageResults(timestamp
, results
);
672 public SendMessageResults
sendTypingMessage(
673 TypingAction action
, Set
<RecipientIdentifier
> recipients
674 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
675 return sendTypingMessage(action
.toSignalService(), recipients
);
679 public SendMessageResults
sendReadReceipt(
680 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
681 ) throws IOException
{
682 final var timestamp
= System
.currentTimeMillis();
683 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
687 final var result
= sendHelper
.sendReceiptMessage(receiptMessage
, recipientHelper
.resolveRecipient(sender
));
688 return new SendMessageResults(timestamp
,
690 List
.of(SendMessageResult
.from(result
,
691 account
.getRecipientStore(),
692 account
.getRecipientStore()::resolveRecipientAddress
))));
696 public SendMessageResults
sendViewedReceipt(
697 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
698 ) throws IOException
{
699 final var timestamp
= System
.currentTimeMillis();
700 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
704 final var result
= sendHelper
.sendReceiptMessage(receiptMessage
, recipientHelper
.resolveRecipient(sender
));
705 return new SendMessageResults(timestamp
,
707 List
.of(SendMessageResult
.from(result
,
708 account
.getRecipientStore(),
709 account
.getRecipientStore()::resolveRecipientAddress
))));
713 public SendMessageResults
sendMessage(
714 Message message
, Set
<RecipientIdentifier
> recipients
715 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
716 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
717 applyMessage(messageBuilder
, message
);
718 return sendMessage(messageBuilder
, recipients
);
721 private void applyMessage(
722 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
723 ) throws AttachmentInvalidException
, IOException
{
724 messageBuilder
.withBody(message
.messageText());
725 final var attachments
= message
.attachments();
726 if (attachments
!= null) {
727 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
729 if (message
.mentions().size() > 0) {
730 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
732 if (message
.quote().isPresent()) {
733 final var quote
= message
.quote().get();
734 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
735 recipientHelper
.resolveSignalServiceAddress(recipientHelper
.resolveRecipient(quote
.author())),
738 resolveMentions(quote
.mentions())));
742 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
{
743 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
744 for (final var m
: mentionList
) {
745 final var recipientId
= recipientHelper
.resolveRecipient(m
.recipient());
746 mentions
.add(new SignalServiceDataMessage
.Mention(recipientHelper
.resolveSignalServiceAddress(recipientId
)
747 .getAci(), m
.start(), m
.length()));
753 public SendMessageResults
sendRemoteDeleteMessage(
754 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
755 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
756 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
757 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
758 return sendMessage(messageBuilder
, recipients
);
762 public SendMessageResults
sendMessageReaction(
765 RecipientIdentifier
.Single targetAuthor
,
766 long targetSentTimestamp
,
767 Set
<RecipientIdentifier
> recipients
768 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
769 var targetAuthorRecipientId
= recipientHelper
.resolveRecipient(targetAuthor
);
770 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
772 recipientHelper
.resolveSignalServiceAddress(targetAuthorRecipientId
),
773 targetSentTimestamp
);
774 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
775 return sendMessage(messageBuilder
, recipients
);
779 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
780 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
783 return sendMessage(messageBuilder
,
784 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
785 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
786 throw new AssertionError(e
);
788 for (var recipient
: recipients
) {
789 final var recipientId
= recipientHelper
.resolveRecipient(recipient
);
790 account
.getSessionStore().deleteAllSessions(recipientId
);
796 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
797 account
.removeRecipient(recipientHelper
.resolveRecipient(recipient
));
801 public void deleteContact(final RecipientIdentifier
.Single recipient
) throws IOException
{
802 account
.getContactStore().deleteContact(recipientHelper
.resolveRecipient(recipient
));
806 public void setContactName(
807 RecipientIdentifier
.Single recipient
, String name
808 ) throws NotMasterDeviceException
, IOException
{
809 if (!account
.isMasterDevice()) {
810 throw new NotMasterDeviceException();
812 contactHelper
.setContactName(recipientHelper
.resolveRecipient(recipient
), name
);
816 public void setContactBlocked(
817 RecipientIdentifier
.Single recipient
, boolean blocked
818 ) throws NotMasterDeviceException
, IOException
{
819 if (!account
.isMasterDevice()) {
820 throw new NotMasterDeviceException();
822 contactHelper
.setContactBlocked(recipientHelper
.resolveRecipient(recipient
), blocked
);
823 // TODO cycle our profile key
824 syncHelper
.sendBlockedList();
828 public void setGroupBlocked(
829 final GroupId groupId
, final boolean blocked
830 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
831 if (!account
.isMasterDevice()) {
832 throw new NotMasterDeviceException();
834 groupHelper
.setGroupBlocked(groupId
, blocked
);
835 // TODO cycle our profile key
836 syncHelper
.sendBlockedList();
840 * Change the expiration timer for a contact
843 public void setExpirationTimer(
844 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
845 ) throws IOException
{
846 var recipientId
= recipientHelper
.resolveRecipient(recipient
);
847 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
848 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
850 sendMessage(messageBuilder
, Set
.of(recipient
));
851 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
852 throw new AssertionError(e
);
857 * Upload the sticker pack from path.
859 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
860 * @return if successful, returns the URL to install the sticker pack in the signal app
863 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
864 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
866 var messageSender
= dependencies
.getMessageSender();
868 var packKey
= KeyUtils
.createStickerUploadKey();
869 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
870 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
872 var sticker
= new Sticker(packId
, packKey
);
873 account
.getStickerStore().updateSticker(sticker
);
876 return new URI("https",
880 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
882 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
883 } catch (URISyntaxException e
) {
884 throw new AssertionError(e
);
889 public void requestAllSyncData() throws IOException
{
890 syncHelper
.requestAllSyncData();
891 retrieveRemoteStorage();
894 void retrieveRemoteStorage() throws IOException
{
895 if (account
.getStorageKey() != null) {
896 storageHelper
.readDataFromStorage();
900 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
901 Set
<HandleAction
> queuedActions
= new HashSet
<>();
902 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
903 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
904 if (actions
!= null) {
905 queuedActions
.addAll(actions
);
908 handleQueuedActions(queuedActions
);
911 private List
<HandleAction
> retryFailedReceivedMessage(
912 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
914 var envelope
= cachedMessage
.loadEnvelope();
915 if (envelope
== null) {
916 cachedMessage
.delete();
920 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
921 final var actions
= result
.first();
922 final var exception
= result
.second();
924 if (exception
instanceof UntrustedIdentityException
) {
925 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
926 // Envelope is more than a month old, cleaning up.
927 cachedMessage
.delete();
930 if (!envelope
.hasSourceUuid()) {
931 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
932 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
934 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
935 } catch (IOException ioException
) {
936 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
942 // If successful and for all other errors that are not recoverable, delete the cached message
943 cachedMessage
.delete();
948 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
949 if (isReceivingSynchronous
) {
950 throw new IllegalStateException("Already receiving message synchronously.");
952 synchronized (messageHandlers
) {
953 if (isWeakListener
) {
954 weakHandlers
.add(handler
);
956 messageHandlers
.add(handler
);
957 startReceiveThreadIfRequired();
962 private void startReceiveThreadIfRequired() {
963 if (receiveThread
!= null) {
966 receiveThread
= new Thread(() -> {
967 logger
.debug("Starting receiving messages");
968 while (!Thread
.interrupted()) {
970 receiveMessagesInternal(Duration
.ofMinutes(1), false, (envelope
, e
) -> {
971 synchronized (messageHandlers
) {
972 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
974 h
.handleMessage(envelope
, e
);
975 } catch (Exception ex
) {
976 logger
.warn("Message handler failed, ignoring", ex
);
982 } catch (IOException e
) {
983 logger
.warn("Receiving messages failed, retrying", e
);
986 logger
.debug("Finished receiving messages");
987 hasCaughtUpWithOldMessages
= false;
988 synchronized (messageHandlers
) {
989 receiveThread
= null;
991 // Check if in the meantime another handler has been registered
992 if (!messageHandlers
.isEmpty()) {
993 logger
.debug("Another handler has been registered, starting receive thread again");
994 startReceiveThreadIfRequired();
999 receiveThread
.start();
1003 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
1004 final Thread thread
;
1005 synchronized (messageHandlers
) {
1006 weakHandlers
.remove(handler
);
1007 messageHandlers
.remove(handler
);
1008 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
1011 thread
= receiveThread
;
1012 receiveThread
= null;
1015 stopReceiveThread(thread
);
1018 private void stopReceiveThread(final Thread thread
) {
1022 } catch (InterruptedException ignored
) {
1027 public boolean isReceiving() {
1028 if (isReceivingSynchronous
) {
1031 synchronized (messageHandlers
) {
1032 return messageHandlers
.size() > 0;
1037 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
1038 receiveMessages(timeout
, true, handler
);
1042 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
1043 receiveMessages(Duration
.ofMinutes(1), false, handler
);
1046 private void receiveMessages(
1047 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1048 ) throws IOException
{
1049 if (isReceiving()) {
1050 throw new IllegalStateException("Already receiving message.");
1052 isReceivingSynchronous
= true;
1053 receiveThread
= Thread
.currentThread();
1055 receiveMessagesInternal(timeout
, returnOnTimeout
, handler
);
1057 receiveThread
= null;
1058 hasCaughtUpWithOldMessages
= false;
1059 isReceivingSynchronous
= false;
1063 private void receiveMessagesInternal(
1064 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1065 ) throws IOException
{
1066 needsToRetryFailedMessages
= true;
1068 // Use a Map here because java Set doesn't have a get method ...
1069 Map
<HandleAction
, HandleAction
> queuedActions
= new HashMap
<>();
1071 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1072 final var webSocketStateDisposable
= Observable
.merge(signalWebSocket
.getUnidentifiedWebSocketState(),
1073 signalWebSocket
.getWebSocketState())
1074 .subscribeOn(Schedulers
.computation())
1075 .observeOn(Schedulers
.computation())
1076 .distinctUntilChanged()
1077 .subscribe(this::onWebSocketStateChange
);
1078 signalWebSocket
.connect();
1080 hasCaughtUpWithOldMessages
= false;
1081 var backOffCounter
= 0;
1082 final var MAX_BACKOFF_COUNTER
= 9;
1084 while (!Thread
.interrupted()) {
1085 if (needsToRetryFailedMessages
) {
1086 retryFailedReceivedMessages(handler
);
1087 needsToRetryFailedMessages
= false;
1089 SignalServiceEnvelope envelope
;
1090 final CachedMessage
[] cachedMessage
= {null};
1091 final var nowMillis
= System
.currentTimeMillis();
1092 if (nowMillis
- account
.getLastReceiveTimestamp() > 60000) {
1093 account
.setLastReceiveTimestamp(nowMillis
);
1095 logger
.debug("Checking for new message from server");
1097 var result
= signalWebSocket
.readOrEmpty(timeout
.toMillis(), envelope1
-> {
1098 final var recipientId
= envelope1
.hasSourceUuid()
1099 ?
resolveRecipient(envelope1
.getSourceAddress())
1101 // store message on disk, before acknowledging receipt to the server
1102 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1106 if (result
.isPresent()) {
1107 envelope
= result
.get();
1108 logger
.debug("New message received from server");
1110 logger
.debug("Received indicator that server queue is empty");
1111 handleQueuedActions(queuedActions
.keySet());
1112 queuedActions
.clear();
1114 hasCaughtUpWithOldMessages
= true;
1115 synchronized (this) {
1119 // Continue to wait another timeout for new messages
1122 } catch (AssertionError e
) {
1123 if (e
.getCause() instanceof InterruptedException
) {
1124 Thread
.currentThread().interrupt();
1129 } catch (IOException e
) {
1130 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1131 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1132 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1133 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1134 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1136 Thread
.sleep(sleepMilliseconds
);
1137 } catch (InterruptedException interruptedException
) {
1140 hasCaughtUpWithOldMessages
= false;
1141 signalWebSocket
.connect();
1145 } catch (TimeoutException e
) {
1147 if (returnOnTimeout
) return;
1151 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
1152 for (final var h
: result
.first()) {
1153 final var existingAction
= queuedActions
.get(h
);
1154 if (existingAction
== null) {
1155 queuedActions
.put(h
, h
);
1157 existingAction
.mergeOther(h
);
1160 final var exception
= result
.second();
1162 if (hasCaughtUpWithOldMessages
) {
1163 handleQueuedActions(queuedActions
.keySet());
1164 queuedActions
.clear();
1166 if (cachedMessage
[0] != null) {
1167 if (exception
instanceof UntrustedIdentityException
) {
1168 logger
.debug("Keeping message with untrusted identity in message cache");
1169 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1170 final var recipientId
= account
.getRecipientStore().resolveRecipient(address
);
1171 if (!envelope
.hasSourceUuid()) {
1173 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1174 } catch (IOException ioException
) {
1175 logger
.warn("Failed to move cached message to recipient folder: {}",
1176 ioException
.getMessage());
1180 cachedMessage
[0].delete();
1184 handleQueuedActions(queuedActions
.keySet());
1185 queuedActions
.clear();
1186 dependencies
.getSignalWebSocket().disconnect();
1187 webSocketStateDisposable
.dispose();
1190 private void onWebSocketStateChange(final WebSocketConnectionState s
) {
1191 if (s
.equals(WebSocketConnectionState
.AUTHENTICATION_FAILED
)) {
1192 account
.setRegistered(false);
1195 } catch (IOException e
) {
1196 e
.printStackTrace();
1202 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1203 this.ignoreAttachments
= ignoreAttachments
;
1207 public boolean hasCaughtUpWithOldMessages() {
1208 return hasCaughtUpWithOldMessages
;
1211 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1212 logger
.debug("Handling message actions");
1213 var interrupted
= false;
1214 for (var action
: queuedActions
) {
1215 logger
.debug("Executing action {}", action
.getClass().getSimpleName());
1217 action
.execute(context
);
1218 } catch (Throwable e
) {
1219 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1220 && e
.getCause() instanceof InterruptedException
) {
1224 logger
.warn("Message action failed.", e
);
1228 Thread
.currentThread().interrupt();
1233 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1234 final RecipientId recipientId
;
1236 recipientId
= recipientHelper
.resolveRecipient(recipient
);
1237 } catch (IOException e
) {
1240 return contactHelper
.isContactBlocked(recipientId
);
1244 public void sendContacts() throws IOException
{
1245 syncHelper
.sendContacts();
1249 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1250 return account
.getContactStore()
1253 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1258 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1259 final RecipientId recipientId
;
1261 recipientId
= recipientHelper
.resolveRecipient(recipient
);
1262 } catch (IOException e
) {
1266 final var contact
= account
.getContactStore().getContact(recipientId
);
1267 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1268 return contact
.getName();
1271 final var profile
= getRecipientProfile(recipientId
);
1272 if (profile
!= null) {
1273 return profile
.getDisplayName();
1280 public Group
getGroup(GroupId groupId
) {
1281 return toGroup(groupHelper
.getGroup(groupId
));
1284 private GroupInfo
getGroupInfo(GroupId groupId
) {
1285 return groupHelper
.getGroup(groupId
);
1289 public List
<Identity
> getIdentities() {
1290 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1293 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1294 if (identityInfo
== null) {
1298 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1299 final var scannableFingerprint
= identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1300 identityInfo
.getIdentityKey());
1301 return new Identity(address
,
1302 identityInfo
.getIdentityKey(),
1303 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1304 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1305 identityInfo
.getTrustLevel(),
1306 identityInfo
.getDateAdded());
1310 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1311 IdentityInfo identity
;
1313 identity
= account
.getIdentityKeyStore().getIdentity(recipientHelper
.resolveRecipient(recipient
));
1314 } catch (IOException e
) {
1317 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1321 * Trust this the identity with this fingerprint
1323 * @param recipient account of the identity
1324 * @param fingerprint Fingerprint
1327 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1328 RecipientId recipientId
;
1330 recipientId
= recipientHelper
.resolveRecipient(recipient
);
1331 } catch (IOException e
) {
1334 final var updated
= identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1335 if (updated
&& this.isReceiving()) {
1336 needsToRetryFailedMessages
= true;
1342 * Trust this the identity with this safety number
1344 * @param recipient account of the identity
1345 * @param safetyNumber Safety number
1348 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1349 RecipientId recipientId
;
1351 recipientId
= recipientHelper
.resolveRecipient(recipient
);
1352 } catch (IOException e
) {
1355 final var updated
= identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1356 if (updated
&& this.isReceiving()) {
1357 needsToRetryFailedMessages
= true;
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
= recipientHelper
.resolveRecipient(recipient
);
1373 } catch (IOException e
) {
1376 final var updated
= identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1377 if (updated
&& this.isReceiving()) {
1378 needsToRetryFailedMessages
= true;
1384 * Trust all keys of this identity without verification
1386 * @param recipient account of the identity
1389 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1390 RecipientId recipientId
;
1392 recipientId
= recipientHelper
.resolveRecipient(recipient
);
1393 } catch (IOException e
) {
1396 final var updated
= identityHelper
.trustIdentityAllKeys(recipientId
);
1397 if (updated
&& this.isReceiving()) {
1398 needsToRetryFailedMessages
= true;
1404 public void addClosedListener(final Runnable listener
) {
1405 synchronized (closedListeners
) {
1406 closedListeners
.add(listener
);
1410 private void handleIdentityFailure(
1411 final RecipientId recipientId
,
1412 final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
.IdentityFailure identityFailure
1414 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1417 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1418 return account
.getRecipientStore().resolveRecipient(address
);
1422 public void close() throws IOException
{
1424 synchronized (messageHandlers
) {
1425 weakHandlers
.clear();
1426 messageHandlers
.clear();
1427 thread
= receiveThread
;
1428 receiveThread
= null;
1430 if (thread
!= null) {
1431 stopReceiveThread(thread
);
1433 executor
.shutdown();
1435 dependencies
.getSignalWebSocket().disconnect();
1437 synchronized (closedListeners
) {
1438 closedListeners
.forEach(Runnable
::run
);
1439 closedListeners
.clear();
1442 if (account
!= null) {