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
.UnregisteredRecipientException
;
34 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
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
.Context
;
43 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
44 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
45 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
46 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
47 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
48 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
49 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
50 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
51 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
52 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
53 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
54 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
55 import org
.slf4j
.Logger
;
56 import org
.slf4j
.LoggerFactory
;
57 import org
.whispersystems
.libsignal
.InvalidKeyException
;
58 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
59 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
60 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
61 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
62 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
63 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
64 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
65 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
66 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
67 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
68 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
69 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
70 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketConnectionState
;
71 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
72 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
73 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
74 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
77 import java
.io
.IOException
;
79 import java
.net
.URISyntaxException
;
80 import java
.net
.URLEncoder
;
81 import java
.nio
.charset
.StandardCharsets
;
82 import java
.time
.Duration
;
83 import java
.util
.ArrayList
;
84 import java
.util
.Collection
;
85 import java
.util
.HashMap
;
86 import java
.util
.HashSet
;
87 import java
.util
.List
;
90 import java
.util
.UUID
;
91 import java
.util
.concurrent
.ExecutorService
;
92 import java
.util
.concurrent
.Executors
;
93 import java
.util
.concurrent
.TimeUnit
;
94 import java
.util
.concurrent
.TimeoutException
;
95 import java
.util
.concurrent
.locks
.ReentrantLock
;
96 import java
.util
.stream
.Collectors
;
97 import java
.util
.stream
.Stream
;
99 import io
.reactivex
.rxjava3
.core
.Observable
;
100 import io
.reactivex
.rxjava3
.schedulers
.Schedulers
;
102 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
104 public class ManagerImpl
implements Manager
{
106 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
108 private final SignalDependencies dependencies
;
110 private SignalAccount account
;
112 private final ExecutorService executor
= Executors
.newCachedThreadPool();
114 private final Context context
;
116 private boolean hasCaughtUpWithOldMessages
= false;
117 private boolean ignoreAttachments
= false;
119 private Thread receiveThread
;
120 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
121 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
122 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
123 private boolean isReceivingSynchronous
;
124 private boolean needsToRetryFailedMessages
= false;
127 SignalAccount account
,
128 PathConfig pathConfig
,
129 ServiceEnvironmentConfig serviceEnvironmentConfig
,
132 this.account
= account
;
134 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
135 account
.getAccount(),
136 account
.getPassword(),
137 account
.getDeviceId());
138 final var sessionLock
= new SignalSessionLock() {
139 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
142 public Lock
acquire() {
144 return LEGACY_LOCK
::unlock
;
147 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
150 account
.getSignalProtocolStore(),
153 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
154 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
155 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
157 this.context
= new Context(account
, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
161 public String
getSelfNumber() {
162 return account
.getAccount();
166 public void checkAccountState() throws IOException
{
167 if (account
.getLastReceiveTimestamp() == 0) {
168 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
170 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
171 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
174 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
179 context
.getPreKeyHelper().refreshPreKeysIfNecessary();
180 if (account
.getAci() == null) {
181 account
.setAci(ACI
.parseOrNull(dependencies
.getAccountManager().getWhoAmI().getAci()));
183 updateAccountAttributes(null);
184 } catch (AuthorizationFailedException e
) {
185 account
.setRegistered(false);
191 * This is used for checking a set of phone numbers for registration on Signal
193 * @param numbers The set of phone number in question
194 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
195 * @throws IOException if it's unable to get the contacts to check if they're registered
198 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
199 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
201 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getAccount());
202 if (!canonicalizedNumber
.equals(n
)) {
203 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
205 return canonicalizedNumber
;
206 } catch (InvalidNumberException e
) {
211 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
212 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
214 .filter(s
-> !s
.isEmpty())
215 .collect(Collectors
.toSet());
216 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
218 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
219 final var number
= canonicalizedNumbers
.get(n
);
220 final var aci
= registeredUsers
.get(number
);
221 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
226 public void updateAccountAttributes(String deviceName
) throws IOException
{
227 final String encryptedDeviceName
;
228 if (deviceName
== null) {
229 encryptedDeviceName
= account
.getEncryptedDeviceName();
231 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
232 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
233 account
.setEncryptedDeviceName(encryptedDeviceName
);
235 dependencies
.getAccountManager()
236 .setAccountAttributes(encryptedDeviceName
,
238 account
.getLocalRegistrationId(),
241 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
242 account
.getSelfUnidentifiedAccessKey(),
243 account
.isUnrestrictedUnidentifiedAccess(),
245 account
.isDiscoverableByPhoneNumber());
249 public Configuration
getConfiguration() {
250 final var configurationStore
= account
.getConfigurationStore();
251 return new Configuration(java
.util
.Optional
.ofNullable(configurationStore
.getReadReceipts()),
252 java
.util
.Optional
.ofNullable(configurationStore
.getUnidentifiedDeliveryIndicators()),
253 java
.util
.Optional
.ofNullable(configurationStore
.getTypingIndicators()),
254 java
.util
.Optional
.ofNullable(configurationStore
.getLinkPreviews()));
258 public void updateConfiguration(
259 Configuration configuration
260 ) throws IOException
, NotMasterDeviceException
{
261 if (!account
.isMasterDevice()) {
262 throw new NotMasterDeviceException();
265 final var configurationStore
= account
.getConfigurationStore();
266 if (configuration
.readReceipts().isPresent()) {
267 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
269 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
270 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
272 if (configuration
.typingIndicators().isPresent()) {
273 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
275 if (configuration
.linkPreviews().isPresent()) {
276 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
278 context
.getSyncHelper().sendConfigurationMessage();
282 * @param givenName if null, the previous givenName will be kept
283 * @param familyName if null, the previous familyName will be kept
284 * @param about if null, the previous about text will be kept
285 * @param aboutEmoji if null, the previous about emoji will be kept
286 * @param avatar if avatar is null the image from the local avatar store is used (if present),
289 public void setProfile(
290 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
291 ) throws IOException
{
292 context
.getProfileHelper()
293 .setProfile(givenName
,
297 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
298 context
.getSyncHelper().sendSyncFetchProfileMessage();
302 public void unregister() throws IOException
{
303 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
304 // If this is the master device, other users can't send messages to this number anymore.
305 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
306 dependencies
.getAccountManager().setGcmId(Optional
.absent());
308 account
.setRegistered(false);
313 public void deleteAccount() throws IOException
{
315 context
.getPinHelper().removeRegistrationLockPin();
316 } catch (IOException e
) {
317 logger
.warn("Failed to remove registration lock pin");
319 account
.setRegistrationLockPin(null, null);
321 dependencies
.getAccountManager().deleteAccount();
323 account
.setRegistered(false);
328 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
329 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
331 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
335 public List
<Device
> getLinkedDevices() throws IOException
{
336 var devices
= dependencies
.getAccountManager().getDevices();
337 account
.setMultiDevice(devices
.size() > 1);
338 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
339 return devices
.stream().map(d
-> {
340 String deviceName
= d
.getName();
341 if (deviceName
!= null) {
343 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
344 } catch (IOException e
) {
345 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
348 return new Device(d
.getId(),
352 d
.getId() == account
.getDeviceId());
357 public void removeLinkedDevices(long deviceId
) throws IOException
{
358 dependencies
.getAccountManager().removeDevice(deviceId
);
359 var devices
= dependencies
.getAccountManager().getDevices();
360 account
.setMultiDevice(devices
.size() > 1);
364 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
365 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
367 addDevice(info
.deviceIdentifier(), info
.deviceKey());
370 private void addDevice(
371 String deviceIdentifier
, ECPublicKey deviceKey
372 ) throws IOException
, InvalidDeviceLinkException
{
373 var identityKeyPair
= account
.getIdentityKeyPair();
374 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
377 dependencies
.getAccountManager()
378 .addDevice(deviceIdentifier
,
381 Optional
.of(account
.getProfileKey().serialize()),
383 } catch (InvalidKeyException e
) {
384 throw new InvalidDeviceLinkException("Invalid device link", e
);
386 account
.setMultiDevice(true);
390 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
{
391 if (!account
.isMasterDevice()) {
392 throw new RuntimeException("Only master device can set a PIN");
394 if (pin
.isPresent()) {
395 final var masterKey
= account
.getPinMasterKey() != null
396 ? account
.getPinMasterKey()
397 : KeyUtils
.createMasterKey();
399 context
.getPinHelper().setRegistrationLockPin(pin
.get(), masterKey
);
401 account
.setRegistrationLockPin(pin
.get(), masterKey
);
404 context
.getPinHelper().removeRegistrationLockPin();
406 account
.setRegistrationLockPin(null, null);
410 void refreshPreKeys() throws IOException
{
411 context
.getPreKeyHelper().refreshPreKeys();
415 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
416 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
420 public List
<Group
> getGroups() {
421 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
424 private Group
toGroup(final GroupInfo groupInfo
) {
425 if (groupInfo
== null) {
429 return new Group(groupInfo
.getGroupId(),
430 groupInfo
.getTitle(),
431 groupInfo
.getDescription(),
432 groupInfo
.getGroupInviteLink(),
433 groupInfo
.getMembers()
435 .map(account
.getRecipientStore()::resolveRecipientAddress
)
436 .collect(Collectors
.toSet()),
437 groupInfo
.getPendingMembers()
439 .map(account
.getRecipientStore()::resolveRecipientAddress
)
440 .collect(Collectors
.toSet()),
441 groupInfo
.getRequestingMembers()
443 .map(account
.getRecipientStore()::resolveRecipientAddress
)
444 .collect(Collectors
.toSet()),
445 groupInfo
.getAdminMembers()
447 .map(account
.getRecipientStore()::resolveRecipientAddress
)
448 .collect(Collectors
.toSet()),
449 groupInfo
.isBlocked(),
450 groupInfo
.getMessageExpirationTimer(),
451 groupInfo
.getPermissionAddMember(),
452 groupInfo
.getPermissionEditDetails(),
453 groupInfo
.getPermissionSendMessage(),
454 groupInfo
.isMember(account
.getSelfRecipientId()),
455 groupInfo
.isAdmin(account
.getSelfRecipientId()));
459 public SendGroupMessageResults
quitGroup(
460 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
461 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
462 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
463 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
467 public void deleteGroup(GroupId groupId
) throws IOException
{
468 context
.getGroupHelper().deleteGroup(groupId
);
472 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
473 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
474 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
475 return context
.getGroupHelper()
477 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
482 public SendGroupMessageResults
updateGroup(
483 final GroupId groupId
, final UpdateGroup updateGroup
484 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
485 return context
.getGroupHelper()
486 .updateGroup(groupId
,
487 updateGroup
.getName(),
488 updateGroup
.getDescription(),
489 updateGroup
.getMembers() == null
491 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
492 updateGroup
.getRemoveMembers() == null
494 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
495 updateGroup
.getAdmins() == null
497 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
498 updateGroup
.getRemoveAdmins() == null
500 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
501 updateGroup
.isResetGroupLink(),
502 updateGroup
.getGroupLinkState(),
503 updateGroup
.getAddMemberPermission(),
504 updateGroup
.getEditDetailsPermission(),
505 updateGroup
.getAvatarFile(),
506 updateGroup
.getExpirationTimer(),
507 updateGroup
.getIsAnnouncementGroup());
511 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
512 GroupInviteLinkUrl inviteLinkUrl
513 ) throws IOException
, InactiveGroupLinkException
{
514 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
517 private SendMessageResults
sendMessage(
518 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
519 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
520 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
521 long timestamp
= System
.currentTimeMillis();
522 messageBuilder
.withTimestamp(timestamp
);
523 for (final var recipient
: recipients
) {
524 if (recipient
instanceof RecipientIdentifier
.Single single
) {
526 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
527 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
528 results
.put(recipient
,
529 List
.of(SendMessageResult
.from(result
,
530 account
.getRecipientStore(),
531 account
.getRecipientStore()::resolveRecipientAddress
)));
532 } catch (UnregisteredRecipientException e
) {
533 results
.put(recipient
,
534 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
536 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
537 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
538 results
.put(recipient
,
539 List
.of(SendMessageResult
.from(result
,
540 account
.getRecipientStore(),
541 account
.getRecipientStore()::resolveRecipientAddress
)));
542 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
543 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
544 results
.put(recipient
,
546 .map(sendMessageResult
-> SendMessageResult
.from(sendMessageResult
,
547 account
.getRecipientStore(),
548 account
.getRecipientStore()::resolveRecipientAddress
))
552 return new SendMessageResults(timestamp
, results
);
555 private SendMessageResults
sendTypingMessage(
556 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
557 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
558 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
559 final var timestamp
= System
.currentTimeMillis();
560 for (var recipient
: recipients
) {
561 if (recipient
instanceof RecipientIdentifier
.Single single
) {
562 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
564 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
565 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
566 results
.put(recipient
,
567 List
.of(SendMessageResult
.from(result
,
568 account
.getRecipientStore(),
569 account
.getRecipientStore()::resolveRecipientAddress
)));
570 } catch (UnregisteredRecipientException e
) {
571 results
.put(recipient
,
572 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
574 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
575 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
576 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
577 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
578 results
.put(recipient
,
580 .map(r
-> SendMessageResult
.from(r
,
581 account
.getRecipientStore(),
582 account
.getRecipientStore()::resolveRecipientAddress
))
586 return new SendMessageResults(timestamp
, results
);
590 public SendMessageResults
sendTypingMessage(
591 TypingAction action
, Set
<RecipientIdentifier
> recipients
592 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
593 return sendTypingMessage(action
.toSignalService(), recipients
);
597 public SendMessageResults
sendReadReceipt(
598 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
599 ) throws IOException
{
600 final var timestamp
= System
.currentTimeMillis();
601 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
605 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
609 public SendMessageResults
sendViewedReceipt(
610 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
611 ) throws IOException
{
612 final var timestamp
= System
.currentTimeMillis();
613 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
617 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
620 private SendMessageResults
sendReceiptMessage(
621 final RecipientIdentifier
.Single sender
,
622 final long timestamp
,
623 final SignalServiceReceiptMessage receiptMessage
624 ) throws IOException
{
626 final var result
= context
.getSendHelper()
627 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
628 return new SendMessageResults(timestamp
,
630 List
.of(SendMessageResult
.from(result
,
631 account
.getRecipientStore(),
632 account
.getRecipientStore()::resolveRecipientAddress
))));
633 } catch (UnregisteredRecipientException e
) {
634 return new SendMessageResults(timestamp
,
635 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
640 public SendMessageResults
sendMessage(
641 Message message
, Set
<RecipientIdentifier
> recipients
642 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
643 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
644 applyMessage(messageBuilder
, message
);
645 return sendMessage(messageBuilder
, recipients
);
648 private void applyMessage(
649 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
650 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
{
651 messageBuilder
.withBody(message
.messageText());
652 final var attachments
= message
.attachments();
653 if (attachments
!= null) {
654 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
656 if (message
.mentions().size() > 0) {
657 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
659 if (message
.quote().isPresent()) {
660 final var quote
= message
.quote().get();
661 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
662 context
.getRecipientHelper()
663 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
666 resolveMentions(quote
.mentions())));
670 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
671 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
672 for (final var m
: mentionList
) {
673 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
674 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
675 .resolveSignalServiceAddress(recipientId
)
676 .getAci(), m
.start(), m
.length()));
682 public SendMessageResults
sendRemoteDeleteMessage(
683 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
684 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
685 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
686 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
687 return sendMessage(messageBuilder
, recipients
);
691 public SendMessageResults
sendMessageReaction(
694 RecipientIdentifier
.Single targetAuthor
,
695 long targetSentTimestamp
,
696 Set
<RecipientIdentifier
> recipients
697 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
698 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
699 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
701 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
702 targetSentTimestamp
);
703 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
704 return sendMessage(messageBuilder
, recipients
);
708 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
709 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
712 return sendMessage(messageBuilder
,
713 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
714 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
715 throw new AssertionError(e
);
717 for (var recipient
: recipients
) {
718 final RecipientId recipientId
;
720 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
721 } catch (UnregisteredRecipientException e
) {
724 account
.getSessionStore().deleteAllSessions(recipientId
);
730 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
731 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
735 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
736 account
.getContactStore()
737 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
741 public void setContactName(
742 RecipientIdentifier
.Single recipient
, String name
743 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
744 if (!account
.isMasterDevice()) {
745 throw new NotMasterDeviceException();
747 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
751 public void setContactBlocked(
752 RecipientIdentifier
.Single recipient
, boolean blocked
753 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
754 if (!account
.isMasterDevice()) {
755 throw new NotMasterDeviceException();
757 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
758 // TODO cycle our profile key, if we're not together in a group with recipient
759 context
.getSyncHelper().sendBlockedList();
763 public void setGroupBlocked(
764 final GroupId groupId
, final boolean blocked
765 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
766 if (!account
.isMasterDevice()) {
767 throw new NotMasterDeviceException();
769 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
770 // TODO cycle our profile key
771 context
.getSyncHelper().sendBlockedList();
775 * Change the expiration timer for a contact
778 public void setExpirationTimer(
779 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
780 ) throws IOException
, UnregisteredRecipientException
{
781 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
782 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
783 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
785 sendMessage(messageBuilder
, Set
.of(recipient
));
786 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
787 throw new AssertionError(e
);
792 * Upload the sticker pack from path.
794 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
795 * @return if successful, returns the URL to install the sticker pack in the signal app
798 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
799 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
801 var messageSender
= dependencies
.getMessageSender();
803 var packKey
= KeyUtils
.createStickerUploadKey();
804 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
805 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
807 var sticker
= new Sticker(packId
, packKey
);
808 account
.getStickerStore().updateSticker(sticker
);
811 return new URI("https",
815 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
817 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
818 } catch (URISyntaxException e
) {
819 throw new AssertionError(e
);
824 public void requestAllSyncData() throws IOException
{
825 context
.getSyncHelper().requestAllSyncData();
826 retrieveRemoteStorage();
829 void retrieveRemoteStorage() throws IOException
{
830 if (account
.getStorageKey() != null) {
831 context
.getStorageHelper().readDataFromStorage();
835 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
836 Set
<HandleAction
> queuedActions
= new HashSet
<>();
837 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
838 var actions
= retryFailedReceivedMessage(handler
, cachedMessage
);
839 if (actions
!= null) {
840 queuedActions
.addAll(actions
);
843 handleQueuedActions(queuedActions
);
846 private List
<HandleAction
> retryFailedReceivedMessage(
847 final ReceiveMessageHandler handler
, final CachedMessage cachedMessage
849 var envelope
= cachedMessage
.loadEnvelope();
850 if (envelope
== null) {
851 cachedMessage
.delete();
855 final var result
= context
.getIncomingMessageHandler()
856 .handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
857 final var actions
= result
.first();
858 final var exception
= result
.second();
860 if (exception
instanceof UntrustedIdentityException
) {
861 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
862 // Envelope is more than a month old, cleaning up.
863 cachedMessage
.delete();
866 if (!envelope
.hasSourceUuid()) {
867 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
868 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
870 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
871 } catch (IOException ioException
) {
872 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
878 // If successful and for all other errors that are not recoverable, delete the cached message
879 cachedMessage
.delete();
884 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
885 if (isReceivingSynchronous
) {
886 throw new IllegalStateException("Already receiving message synchronously.");
888 synchronized (messageHandlers
) {
889 if (isWeakListener
) {
890 weakHandlers
.add(handler
);
892 messageHandlers
.add(handler
);
893 startReceiveThreadIfRequired();
898 private void startReceiveThreadIfRequired() {
899 if (receiveThread
!= null) {
902 receiveThread
= new Thread(() -> {
903 logger
.debug("Starting receiving messages");
904 while (!Thread
.interrupted()) {
906 receiveMessagesInternal(Duration
.ofMinutes(1), false, (envelope
, e
) -> {
907 synchronized (messageHandlers
) {
908 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
910 h
.handleMessage(envelope
, e
);
911 } catch (Exception ex
) {
912 logger
.warn("Message handler failed, ignoring", ex
);
918 } catch (IOException e
) {
919 logger
.warn("Receiving messages failed, retrying", e
);
922 logger
.debug("Finished receiving messages");
923 hasCaughtUpWithOldMessages
= false;
924 synchronized (messageHandlers
) {
925 receiveThread
= null;
927 // Check if in the meantime another handler has been registered
928 if (!messageHandlers
.isEmpty()) {
929 logger
.debug("Another handler has been registered, starting receive thread again");
930 startReceiveThreadIfRequired();
935 receiveThread
.start();
939 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
941 synchronized (messageHandlers
) {
942 weakHandlers
.remove(handler
);
943 messageHandlers
.remove(handler
);
944 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
947 thread
= receiveThread
;
948 receiveThread
= null;
951 stopReceiveThread(thread
);
954 private void stopReceiveThread(final Thread thread
) {
958 } catch (InterruptedException ignored
) {
963 public boolean isReceiving() {
964 if (isReceivingSynchronous
) {
967 synchronized (messageHandlers
) {
968 return messageHandlers
.size() > 0;
973 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
974 receiveMessages(timeout
, true, handler
);
978 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
979 receiveMessages(Duration
.ofMinutes(1), false, handler
);
982 private void receiveMessages(
983 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
984 ) throws IOException
{
986 throw new IllegalStateException("Already receiving message.");
988 isReceivingSynchronous
= true;
989 receiveThread
= Thread
.currentThread();
991 receiveMessagesInternal(timeout
, returnOnTimeout
, handler
);
993 receiveThread
= null;
994 hasCaughtUpWithOldMessages
= false;
995 isReceivingSynchronous
= false;
999 private void receiveMessagesInternal(
1000 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
1001 ) throws IOException
{
1002 needsToRetryFailedMessages
= true;
1004 // Use a Map here because java Set doesn't have a get method ...
1005 Map
<HandleAction
, HandleAction
> queuedActions
= new HashMap
<>();
1007 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1008 final var webSocketStateDisposable
= Observable
.merge(signalWebSocket
.getUnidentifiedWebSocketState(),
1009 signalWebSocket
.getWebSocketState())
1010 .subscribeOn(Schedulers
.computation())
1011 .observeOn(Schedulers
.computation())
1012 .distinctUntilChanged()
1013 .subscribe(this::onWebSocketStateChange
);
1014 signalWebSocket
.connect();
1016 hasCaughtUpWithOldMessages
= false;
1017 var backOffCounter
= 0;
1018 final var MAX_BACKOFF_COUNTER
= 9;
1020 while (!Thread
.interrupted()) {
1021 if (needsToRetryFailedMessages
) {
1022 retryFailedReceivedMessages(handler
);
1023 needsToRetryFailedMessages
= false;
1025 SignalServiceEnvelope envelope
;
1026 final CachedMessage
[] cachedMessage
= {null};
1027 final var nowMillis
= System
.currentTimeMillis();
1028 if (nowMillis
- account
.getLastReceiveTimestamp() > 60000) {
1029 account
.setLastReceiveTimestamp(nowMillis
);
1031 logger
.debug("Checking for new message from server");
1033 var result
= signalWebSocket
.readOrEmpty(timeout
.toMillis(), envelope1
-> {
1034 final var recipientId
= envelope1
.hasSourceUuid() ? account
.getRecipientStore()
1035 .resolveRecipient(envelope1
.getSourceAddress()) : null;
1036 // store message on disk, before acknowledging receipt to the server
1037 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1041 if (result
.isPresent()) {
1042 envelope
= result
.get();
1043 logger
.debug("New message received from server");
1045 logger
.debug("Received indicator that server queue is empty");
1046 handleQueuedActions(queuedActions
.keySet());
1047 queuedActions
.clear();
1049 hasCaughtUpWithOldMessages
= true;
1050 synchronized (this) {
1054 // Continue to wait another timeout for new messages
1057 } catch (AssertionError e
) {
1058 if (e
.getCause() instanceof InterruptedException
) {
1059 Thread
.currentThread().interrupt();
1064 } catch (IOException e
) {
1065 logger
.debug("Pipe unexpectedly unavailable: {}", e
.getMessage());
1066 if (e
instanceof WebSocketUnavailableException
|| "Connection closed!".equals(e
.getMessage())) {
1067 final var sleepMilliseconds
= 100 * (long) Math
.pow(2, backOffCounter
);
1068 backOffCounter
= Math
.min(backOffCounter
+ 1, MAX_BACKOFF_COUNTER
);
1069 logger
.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds
);
1071 Thread
.sleep(sleepMilliseconds
);
1072 } catch (InterruptedException interruptedException
) {
1075 hasCaughtUpWithOldMessages
= false;
1076 signalWebSocket
.connect();
1080 } catch (TimeoutException e
) {
1082 if (returnOnTimeout
) return;
1086 final var result
= context
.getIncomingMessageHandler().handleEnvelope(envelope
, ignoreAttachments
, handler
);
1087 for (final var h
: result
.first()) {
1088 final var existingAction
= queuedActions
.get(h
);
1089 if (existingAction
== null) {
1090 queuedActions
.put(h
, h
);
1092 existingAction
.mergeOther(h
);
1095 final var exception
= result
.second();
1097 if (hasCaughtUpWithOldMessages
) {
1098 handleQueuedActions(queuedActions
.keySet());
1099 queuedActions
.clear();
1101 if (cachedMessage
[0] != null) {
1102 if (exception
instanceof UntrustedIdentityException
) {
1103 logger
.debug("Keeping message with untrusted identity in message cache");
1104 final var address
= ((UntrustedIdentityException
) exception
).getSender();
1105 final var recipientId
= account
.getRecipientStore().resolveRecipient(address
);
1106 if (!envelope
.hasSourceUuid()) {
1108 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1109 } catch (IOException ioException
) {
1110 logger
.warn("Failed to move cached message to recipient folder: {}",
1111 ioException
.getMessage());
1115 cachedMessage
[0].delete();
1119 handleQueuedActions(queuedActions
.keySet());
1120 queuedActions
.clear();
1121 dependencies
.getSignalWebSocket().disconnect();
1122 webSocketStateDisposable
.dispose();
1125 private void onWebSocketStateChange(final WebSocketConnectionState s
) {
1126 if (s
.equals(WebSocketConnectionState
.AUTHENTICATION_FAILED
)) {
1127 account
.setRegistered(false);
1130 } catch (IOException e
) {
1131 e
.printStackTrace();
1137 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
1138 this.ignoreAttachments
= ignoreAttachments
;
1142 public boolean hasCaughtUpWithOldMessages() {
1143 return hasCaughtUpWithOldMessages
;
1146 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
1147 logger
.debug("Handling message actions");
1148 var interrupted
= false;
1149 for (var action
: queuedActions
) {
1150 logger
.debug("Executing action {}", action
.getClass().getSimpleName());
1152 action
.execute(context
);
1153 } catch (Throwable e
) {
1154 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
1155 && e
.getCause() instanceof InterruptedException
) {
1159 logger
.warn("Message action failed.", e
);
1163 Thread
.currentThread().interrupt();
1168 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1169 final RecipientId recipientId
;
1171 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1172 } catch (IOException
| UnregisteredRecipientException e
) {
1175 return context
.getContactHelper().isContactBlocked(recipientId
);
1179 public void sendContacts() throws IOException
{
1180 context
.getSyncHelper().sendContacts();
1184 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1185 return account
.getContactStore()
1188 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1193 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1194 final RecipientId recipientId
;
1196 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1197 } catch (IOException
| UnregisteredRecipientException e
) {
1201 final var contact
= account
.getContactStore().getContact(recipientId
);
1202 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1203 return contact
.getName();
1206 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
1207 if (profile
!= null) {
1208 return profile
.getDisplayName();
1215 public Group
getGroup(GroupId groupId
) {
1216 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1220 public List
<Identity
> getIdentities() {
1221 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1224 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1225 if (identityInfo
== null) {
1229 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1230 final var scannableFingerprint
= context
.getIdentityHelper()
1231 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
1232 return new Identity(address
,
1233 identityInfo
.getIdentityKey(),
1234 context
.getIdentityHelper()
1235 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1236 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1237 identityInfo
.getTrustLevel(),
1238 identityInfo
.getDateAdded());
1242 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1243 IdentityInfo identity
;
1245 identity
= account
.getIdentityKeyStore()
1246 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
1247 } catch (IOException
| UnregisteredRecipientException e
) {
1250 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1254 * Trust this the identity with this fingerprint
1256 * @param recipient account of the identity
1257 * @param fingerprint Fingerprint
1260 public boolean trustIdentityVerified(
1261 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1262 ) throws UnregisteredRecipientException
{
1263 RecipientId recipientId
;
1265 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1266 } catch (IOException e
) {
1269 final var updated
= context
.getIdentityHelper().trustIdentityVerified(recipientId
, fingerprint
);
1270 if (updated
&& this.isReceiving()) {
1271 needsToRetryFailedMessages
= true;
1277 * Trust this the identity with this safety number
1279 * @param recipient account of the identity
1280 * @param safetyNumber Safety number
1283 public boolean trustIdentityVerifiedSafetyNumber(
1284 RecipientIdentifier
.Single recipient
, String safetyNumber
1285 ) throws UnregisteredRecipientException
{
1286 RecipientId recipientId
;
1288 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1289 } catch (IOException e
) {
1292 final var updated
= context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1293 if (updated
&& this.isReceiving()) {
1294 needsToRetryFailedMessages
= true;
1300 * Trust this the identity with this scannable safety number
1302 * @param recipient account of the identity
1303 * @param safetyNumber Scannable safety number
1306 public boolean trustIdentityVerifiedSafetyNumber(
1307 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1308 ) throws UnregisteredRecipientException
{
1309 RecipientId recipientId
;
1311 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1312 } catch (IOException e
) {
1315 final var updated
= context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1316 if (updated
&& this.isReceiving()) {
1317 needsToRetryFailedMessages
= true;
1323 * Trust all keys of this identity without verification
1325 * @param recipient account of the identity
1328 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1329 RecipientId recipientId
;
1331 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1332 } catch (IOException e
) {
1335 final var updated
= context
.getIdentityHelper().trustIdentityAllKeys(recipientId
);
1336 if (updated
&& this.isReceiving()) {
1337 needsToRetryFailedMessages
= true;
1343 public void addClosedListener(final Runnable listener
) {
1344 synchronized (closedListeners
) {
1345 closedListeners
.add(listener
);
1350 public void close() throws IOException
{
1352 synchronized (messageHandlers
) {
1353 weakHandlers
.clear();
1354 messageHandlers
.clear();
1355 thread
= receiveThread
;
1356 receiveThread
= null;
1358 if (thread
!= null) {
1359 stopReceiveThread(thread
);
1361 executor
.shutdown();
1363 dependencies
.getSignalWebSocket().disconnect();
1365 synchronized (closedListeners
) {
1366 closedListeners
.forEach(Runnable
::run
);
1367 closedListeners
.clear();
1370 if (account
!= null) {