2 Copyright (C) 2015-2022 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
.api
.AttachmentInvalidException
;
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
.InvalidStickerException
;
27 import org
.asamk
.signal
.manager
.api
.Message
;
28 import org
.asamk
.signal
.manager
.api
.NotMasterDeviceException
;
29 import org
.asamk
.signal
.manager
.api
.Pair
;
30 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
31 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
32 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
33 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
34 import org
.asamk
.signal
.manager
.api
.StickerPack
;
35 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
36 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
37 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
38 import org
.asamk
.signal
.manager
.api
.TypingAction
;
39 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
40 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
41 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
42 import org
.asamk
.signal
.manager
.groups
.GroupId
;
43 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
44 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
45 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
46 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
47 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
48 import org
.asamk
.signal
.manager
.helper
.Context
;
49 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
50 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
51 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
52 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
53 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
56 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
57 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
58 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
59 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
60 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
61 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
62 import org
.slf4j
.Logger
;
63 import org
.slf4j
.LoggerFactory
;
64 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
65 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
66 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
69 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
70 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
71 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
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
.time
.Duration
;
80 import java
.util
.ArrayList
;
81 import java
.util
.HashMap
;
82 import java
.util
.HashSet
;
83 import java
.util
.List
;
86 import java
.util
.UUID
;
87 import java
.util
.concurrent
.ExecutorService
;
88 import java
.util
.concurrent
.Executors
;
89 import java
.util
.concurrent
.atomic
.AtomicInteger
;
90 import java
.util
.concurrent
.locks
.ReentrantLock
;
91 import java
.util
.function
.Function
;
92 import java
.util
.stream
.Collectors
;
93 import java
.util
.stream
.Stream
;
95 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
97 class ManagerImpl
implements Manager
{
99 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
101 private SignalAccount account
;
102 private final SignalDependencies dependencies
;
103 private final Context context
;
105 private final ExecutorService executor
= Executors
.newCachedThreadPool();
107 private Thread receiveThread
;
108 private boolean isReceivingSynchronous
;
109 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
110 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
111 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
112 private final CompositeDisposable disposable
= new CompositeDisposable();
115 SignalAccount account
,
116 PathConfig pathConfig
,
117 ServiceEnvironmentConfig serviceEnvironmentConfig
,
120 this.account
= account
;
122 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
123 account
.getAccount(),
124 account
.getPassword(),
125 account
.getDeviceId());
126 final var sessionLock
= new SignalSessionLock() {
127 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
130 public Lock
acquire() {
132 return LEGACY_LOCK
::unlock
;
135 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
138 account
.getSignalProtocolStore(),
141 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
142 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
143 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
145 this.context
= new Context(account
, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
146 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
147 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
148 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
149 synchronized (this) {
153 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
154 logger
.trace("Archiving old sessions for {}", recipientId
);
155 account
.getSessionStore().archiveSessions(recipientId
);
156 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
157 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
158 if (profile
!= null) {
159 account
.getRecipientStore()
160 .storeProfile(recipientId
,
161 Profile
.newBuilder(profile
)
162 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
163 .withLastUpdateTimestamp(0)
170 public String
getSelfNumber() {
171 return account
.getAccount();
174 void checkAccountState() throws IOException
{
175 context
.getAccountHelper().checkAccountState();
179 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
180 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
182 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getAccount());
183 if (!canonicalizedNumber
.equals(n
)) {
184 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
186 return canonicalizedNumber
;
187 } catch (InvalidNumberException e
) {
192 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
193 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
195 .filter(s
-> !s
.isEmpty())
196 .collect(Collectors
.toSet());
197 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
199 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
200 final var number
= canonicalizedNumbers
.get(n
);
201 final var aci
= registeredUsers
.get(number
);
202 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
207 public void updateAccountAttributes(String deviceName
) throws IOException
{
208 if (deviceName
!= null) {
209 context
.getAccountHelper().setDeviceName(deviceName
);
211 context
.getAccountHelper().updateAccountAttributes();
215 public Configuration
getConfiguration() {
216 final var configurationStore
= account
.getConfigurationStore();
217 return Configuration
.from(configurationStore
);
221 public void updateConfiguration(
222 Configuration configuration
223 ) throws NotMasterDeviceException
{
224 if (!account
.isMasterDevice()) {
225 throw new NotMasterDeviceException();
228 final var configurationStore
= account
.getConfigurationStore();
229 if (configuration
.readReceipts().isPresent()) {
230 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
232 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
233 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
235 if (configuration
.typingIndicators().isPresent()) {
236 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
238 if (configuration
.linkPreviews().isPresent()) {
239 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
241 context
.getSyncHelper().sendConfigurationMessage();
245 public void setProfile(
246 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
247 ) throws IOException
{
248 context
.getProfileHelper()
249 .setProfile(givenName
,
253 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
254 context
.getSyncHelper().sendSyncFetchProfileMessage();
258 public void unregister() throws IOException
{
259 context
.getAccountHelper().unregister();
263 public void deleteAccount() throws IOException
{
264 context
.getAccountHelper().deleteAccount();
268 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
269 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
271 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
275 public List
<Device
> getLinkedDevices() throws IOException
{
276 var devices
= dependencies
.getAccountManager().getDevices();
277 account
.setMultiDevice(devices
.size() > 1);
278 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
279 return devices
.stream().map(d
-> {
280 String deviceName
= d
.getName();
281 if (deviceName
!= null) {
283 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
284 } catch (IOException e
) {
285 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
288 return new Device(d
.getId(),
292 d
.getId() == account
.getDeviceId());
297 public void removeLinkedDevices(int deviceId
) throws IOException
{
298 context
.getAccountHelper().removeLinkedDevices(deviceId
);
302 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
303 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
304 context
.getAccountHelper().addDevice(deviceLinkInfo
);
308 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
309 if (!account
.isMasterDevice()) {
310 throw new NotMasterDeviceException();
312 if (pin
.isPresent()) {
313 context
.getAccountHelper().setRegistrationPin(pin
.get());
315 context
.getAccountHelper().removeRegistrationPin();
319 void refreshPreKeys() throws IOException
{
320 context
.getPreKeyHelper().refreshPreKeys();
324 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
325 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
329 public List
<Group
> getGroups() {
330 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
333 private Group
toGroup(final GroupInfo groupInfo
) {
334 if (groupInfo
== null) {
338 return Group
.from(groupInfo
,
339 account
.getRecipientStore()::resolveRecipientAddress
,
340 account
.getSelfRecipientId());
344 public SendGroupMessageResults
quitGroup(
345 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
346 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
347 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
348 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
352 public void deleteGroup(GroupId groupId
) throws IOException
{
353 context
.getGroupHelper().deleteGroup(groupId
);
357 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
358 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
359 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
360 return context
.getGroupHelper()
362 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
367 public SendGroupMessageResults
updateGroup(
368 final GroupId groupId
, final UpdateGroup updateGroup
369 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
370 return context
.getGroupHelper()
371 .updateGroup(groupId
,
372 updateGroup
.getName(),
373 updateGroup
.getDescription(),
374 updateGroup
.getMembers() == null
376 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
377 updateGroup
.getRemoveMembers() == null
379 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
380 updateGroup
.getAdmins() == null
382 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
383 updateGroup
.getRemoveAdmins() == null
385 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
386 updateGroup
.isResetGroupLink(),
387 updateGroup
.getGroupLinkState(),
388 updateGroup
.getAddMemberPermission(),
389 updateGroup
.getEditDetailsPermission(),
390 updateGroup
.getAvatarFile(),
391 updateGroup
.getExpirationTimer(),
392 updateGroup
.getIsAnnouncementGroup());
396 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
397 GroupInviteLinkUrl inviteLinkUrl
398 ) throws IOException
, InactiveGroupLinkException
{
399 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
402 private SendMessageResults
sendMessage(
403 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
404 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
405 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
406 long timestamp
= System
.currentTimeMillis();
407 messageBuilder
.withTimestamp(timestamp
);
408 for (final var recipient
: recipients
) {
409 if (recipient
instanceof RecipientIdentifier
.Single single
) {
411 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
412 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
413 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
414 } catch (UnregisteredRecipientException e
) {
415 results
.put(recipient
,
416 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
418 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
419 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
420 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
421 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
422 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
423 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
426 return new SendMessageResults(timestamp
, results
);
429 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
430 return SendMessageResult
.from(result
,
431 account
.getRecipientStore(),
432 account
.getRecipientStore()::resolveRecipientAddress
);
435 private SendMessageResults
sendTypingMessage(
436 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
437 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
438 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
439 final var timestamp
= System
.currentTimeMillis();
440 for (var recipient
: recipients
) {
441 if (recipient
instanceof RecipientIdentifier
.Single single
) {
442 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
444 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
445 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
446 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
447 } catch (UnregisteredRecipientException e
) {
448 results
.put(recipient
,
449 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
451 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
452 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
453 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
454 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
455 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
458 return new SendMessageResults(timestamp
, results
);
462 public SendMessageResults
sendTypingMessage(
463 TypingAction action
, Set
<RecipientIdentifier
> recipients
464 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
465 return sendTypingMessage(action
.toSignalService(), recipients
);
469 public SendMessageResults
sendReadReceipt(
470 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
471 ) throws IOException
{
472 final var timestamp
= System
.currentTimeMillis();
473 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
477 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
481 public SendMessageResults
sendViewedReceipt(
482 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
483 ) throws IOException
{
484 final var timestamp
= System
.currentTimeMillis();
485 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
489 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
492 private SendMessageResults
sendReceiptMessage(
493 final RecipientIdentifier
.Single sender
,
494 final long timestamp
,
495 final SignalServiceReceiptMessage receiptMessage
496 ) throws IOException
{
498 final var result
= context
.getSendHelper()
499 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
500 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
501 } catch (UnregisteredRecipientException e
) {
502 return new SendMessageResults(timestamp
,
503 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
508 public SendMessageResults
sendMessage(
509 Message message
, Set
<RecipientIdentifier
> recipients
510 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
511 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
512 applyMessage(messageBuilder
, message
);
513 return sendMessage(messageBuilder
, recipients
);
516 private void applyMessage(
517 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
518 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
519 messageBuilder
.withBody(message
.messageText());
520 final var attachments
= message
.attachments();
521 if (attachments
!= null) {
522 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
524 if (message
.mentions().size() > 0) {
525 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
527 if (message
.quote().isPresent()) {
528 final var quote
= message
.quote().get();
529 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
530 context
.getRecipientHelper()
531 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
534 resolveMentions(quote
.mentions())));
536 if (message
.sticker().isPresent()) {
537 final var sticker
= message
.sticker().get();
538 final var packId
= StickerPackId
.deserialize(sticker
.packId());
539 final var stickerId
= sticker
.stickerId();
541 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
542 if (stickerPack
== null) {
543 throw new InvalidStickerException("Sticker pack not found");
545 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
546 if (manifest
.stickers().size() <= stickerId
) {
547 throw new InvalidStickerException("Sticker id not part of this pack");
549 final var manifestSticker
= manifest
.stickers().get(stickerId
);
550 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
551 if (streamDetails
== null) {
552 throw new InvalidStickerException("Missing local sticker file");
554 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
555 stickerPack
.getPackKey(),
557 manifestSticker
.emoji(),
558 AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent())));
562 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
563 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
564 for (final var m
: mentionList
) {
565 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
566 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
567 .resolveSignalServiceAddress(recipientId
)
568 .getAci(), m
.start(), m
.length()));
574 public SendMessageResults
sendRemoteDeleteMessage(
575 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
576 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
577 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
578 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
579 for (final var recipient
: recipients
) {
580 if (recipient
instanceof RecipientIdentifier
.Single r
) {
582 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
583 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
584 } catch (UnregisteredRecipientException ignored
) {
586 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
587 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
590 return sendMessage(messageBuilder
, recipients
);
594 public SendMessageResults
sendMessageReaction(
597 RecipientIdentifier
.Single targetAuthor
,
598 long targetSentTimestamp
,
599 Set
<RecipientIdentifier
> recipients
600 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
601 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
602 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
604 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
605 targetSentTimestamp
);
606 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
607 return sendMessage(messageBuilder
, recipients
);
611 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
612 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
615 return sendMessage(messageBuilder
,
616 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
617 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
618 throw new AssertionError(e
);
620 for (var recipient
: recipients
) {
621 final RecipientId recipientId
;
623 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
624 } catch (UnregisteredRecipientException e
) {
627 account
.getSessionStore().deleteAllSessions(recipientId
);
633 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
634 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
638 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
639 account
.getContactStore()
640 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
644 public void setContactName(
645 RecipientIdentifier
.Single recipient
, String name
646 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
647 if (!account
.isMasterDevice()) {
648 throw new NotMasterDeviceException();
650 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
654 public void setContactBlocked(
655 RecipientIdentifier
.Single recipient
, boolean blocked
656 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
657 if (!account
.isMasterDevice()) {
658 throw new NotMasterDeviceException();
660 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
661 // TODO cycle our profile key, if we're not together in a group with recipient
662 context
.getSyncHelper().sendBlockedList();
666 public void setGroupBlocked(
667 final GroupId groupId
, final boolean blocked
668 ) throws GroupNotFoundException
, NotMasterDeviceException
{
669 if (!account
.isMasterDevice()) {
670 throw new NotMasterDeviceException();
672 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
673 // TODO cycle our profile key
674 context
.getSyncHelper().sendBlockedList();
678 public void setExpirationTimer(
679 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
680 ) throws IOException
, UnregisteredRecipientException
{
681 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
682 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
683 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
685 sendMessage(messageBuilder
, Set
.of(recipient
));
686 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
687 throw new AssertionError(e
);
692 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
693 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
695 var messageSender
= dependencies
.getMessageSender();
697 var packKey
= KeyUtils
.createStickerUploadKey();
698 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
699 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
701 var sticker
= new Sticker(packId
, packKey
);
702 account
.getStickerStore().updateSticker(sticker
);
704 return new StickerPackUrl(packId
, packKey
);
708 public List
<StickerPack
> getStickerPacks() {
709 final var stickerPackStore
= context
.getStickerPackStore();
710 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
711 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
713 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
714 return new StickerPack(pack
.getPackId(),
715 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
719 java
.util
.Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
720 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
721 } catch (Exception e
) {
722 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
726 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
731 public void requestAllSyncData() throws IOException
{
732 context
.getSyncHelper().requestAllSyncData();
733 retrieveRemoteStorage();
736 void retrieveRemoteStorage() throws IOException
{
737 if (account
.getStorageKey() != null) {
738 context
.getStorageHelper().readDataFromStorage();
743 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
744 if (isReceivingSynchronous
) {
745 throw new IllegalStateException("Already receiving message synchronously.");
747 synchronized (messageHandlers
) {
748 if (isWeakListener
) {
749 weakHandlers
.add(handler
);
751 messageHandlers
.add(handler
);
752 startReceiveThreadIfRequired();
757 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
759 private void startReceiveThreadIfRequired() {
760 if (receiveThread
!= null) {
763 receiveThread
= new Thread(() -> {
764 logger
.debug("Starting receiving messages");
765 while (!Thread
.interrupted()) {
767 context
.getReceiveHelper().receiveMessages(Duration
.ofMinutes(1), false, (envelope
, e
) -> {
768 synchronized (messageHandlers
) {
769 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
771 h
.handleMessage(envelope
, e
);
772 } catch (Exception ex
) {
773 logger
.warn("Message handler failed, ignoring", ex
);
779 } catch (IOException e
) {
780 logger
.warn("Receiving messages failed, retrying", e
);
783 logger
.debug("Finished receiving messages");
784 synchronized (messageHandlers
) {
785 receiveThread
= null;
787 // Check if in the meantime another handler has been registered
788 if (!messageHandlers
.isEmpty()) {
789 logger
.debug("Another handler has been registered, starting receive thread again");
790 startReceiveThreadIfRequired();
794 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
796 receiveThread
.start();
800 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
802 synchronized (messageHandlers
) {
803 weakHandlers
.remove(handler
);
804 messageHandlers
.remove(handler
);
805 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
808 thread
= receiveThread
;
809 receiveThread
= null;
812 stopReceiveThread(thread
);
815 private void stopReceiveThread(final Thread thread
) {
819 } catch (InterruptedException ignored
) {
824 public boolean isReceiving() {
825 if (isReceivingSynchronous
) {
828 synchronized (messageHandlers
) {
829 return messageHandlers
.size() > 0;
834 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
835 receiveMessages(timeout
, true, handler
);
839 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
840 receiveMessages(Duration
.ofMinutes(1), false, handler
);
843 private void receiveMessages(
844 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
845 ) throws IOException
{
847 throw new IllegalStateException("Already receiving message.");
849 isReceivingSynchronous
= true;
850 receiveThread
= Thread
.currentThread();
852 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
854 receiveThread
= null;
855 isReceivingSynchronous
= false;
860 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
861 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
865 public boolean hasCaughtUpWithOldMessages() {
866 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
870 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
871 final RecipientId recipientId
;
873 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
874 } catch (IOException
| UnregisteredRecipientException e
) {
877 return context
.getContactHelper().isContactBlocked(recipientId
);
881 public void sendContacts() throws IOException
{
882 context
.getSyncHelper().sendContacts();
886 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
887 return account
.getContactStore()
890 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
895 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
896 final RecipientId recipientId
;
898 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
899 } catch (IOException
| UnregisteredRecipientException e
) {
903 final var contact
= account
.getContactStore().getContact(recipientId
);
904 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
905 return contact
.getName();
908 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
909 if (profile
!= null) {
910 return profile
.getDisplayName();
917 public Group
getGroup(GroupId groupId
) {
918 return toGroup(context
.getGroupHelper().getGroup(groupId
));
922 public List
<Identity
> getIdentities() {
923 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
926 private Identity
toIdentity(final IdentityInfo identityInfo
) {
927 if (identityInfo
== null) {
931 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
932 final var scannableFingerprint
= context
.getIdentityHelper()
933 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
934 return new Identity(address
,
935 identityInfo
.getIdentityKey(),
936 context
.getIdentityHelper()
937 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
938 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
939 identityInfo
.getTrustLevel(),
940 identityInfo
.getDateAdded());
944 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
945 IdentityInfo identity
;
947 identity
= account
.getIdentityKeyStore()
948 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
949 } catch (IOException
| UnregisteredRecipientException e
) {
952 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
956 public boolean trustIdentityVerified(
957 RecipientIdentifier
.Single recipient
, byte[] fingerprint
958 ) throws UnregisteredRecipientException
{
959 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
963 public boolean trustIdentityVerifiedSafetyNumber(
964 RecipientIdentifier
.Single recipient
, String safetyNumber
965 ) throws UnregisteredRecipientException
{
966 return trustIdentity(recipient
,
967 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
971 public boolean trustIdentityVerifiedSafetyNumber(
972 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
973 ) throws UnregisteredRecipientException
{
974 return trustIdentity(recipient
,
975 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
979 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
980 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
983 private boolean trustIdentity(
984 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
985 ) throws UnregisteredRecipientException
{
986 RecipientId recipientId
;
988 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
989 } catch (IOException e
) {
992 final var updated
= trustMethod
.apply(recipientId
);
993 if (updated
&& this.isReceiving()) {
994 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1000 public void addClosedListener(final Runnable listener
) {
1001 synchronized (closedListeners
) {
1002 closedListeners
.add(listener
);
1007 public void close() {
1009 synchronized (messageHandlers
) {
1010 weakHandlers
.clear();
1011 messageHandlers
.clear();
1012 thread
= receiveThread
;
1013 receiveThread
= null;
1015 if (thread
!= null) {
1016 stopReceiveThread(thread
);
1018 executor
.shutdown();
1020 dependencies
.getSignalWebSocket().disconnect();
1021 disposable
.dispose();
1023 synchronized (closedListeners
) {
1024 closedListeners
.forEach(Runnable
::run
);
1025 closedListeners
.clear();
1028 if (account
!= null) {