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
.AccountFileUpdater
;
49 import org
.asamk
.signal
.manager
.helper
.Context
;
50 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
51 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
52 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
53 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
57 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
58 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
59 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
60 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
61 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
62 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
63 import org
.slf4j
.Logger
;
64 import org
.slf4j
.LoggerFactory
;
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
.Hex
;
73 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
76 import java
.io
.IOException
;
78 import java
.time
.Duration
;
79 import java
.util
.ArrayList
;
80 import java
.util
.HashMap
;
81 import java
.util
.HashSet
;
82 import java
.util
.List
;
84 import java
.util
.Optional
;
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 List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
113 private final CompositeDisposable disposable
= new CompositeDisposable();
116 SignalAccount account
,
117 PathConfig pathConfig
,
118 AccountFileUpdater accountFileUpdater
,
119 ServiceEnvironmentConfig serviceEnvironmentConfig
,
122 this.account
= account
;
124 final var sessionLock
= new SignalSessionLock() {
125 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
128 public Lock
acquire() {
130 return LEGACY_LOCK
::unlock
;
133 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
135 account
.getCredentialsProvider(),
136 account
.getSignalServiceDataStore(),
139 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
140 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
141 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
143 this.context
= new Context(account
, (number
, aci
) -> {
144 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
145 synchronized (addressChangedListeners
) {
146 addressChangedListeners
.forEach(Runnable
::run
);
148 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
149 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
150 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
151 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
152 synchronized (this) {
156 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
157 logger
.trace("Archiving old sessions for {}", recipientId
);
158 account
.getSessionStore().archiveSessions(recipientId
);
159 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
160 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
161 if (profile
!= null) {
162 account
.getRecipientStore()
163 .storeProfile(recipientId
,
164 Profile
.newBuilder(profile
)
165 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
166 .withLastUpdateTimestamp(0)
173 public String
getSelfNumber() {
174 return account
.getNumber();
177 void checkAccountState() throws IOException
{
178 context
.getAccountHelper().checkAccountState();
182 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
183 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
185 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
186 if (!canonicalizedNumber
.equals(n
)) {
187 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
189 return canonicalizedNumber
;
190 } catch (InvalidNumberException e
) {
195 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
196 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
198 .filter(s
-> !s
.isEmpty())
199 .collect(Collectors
.toSet());
200 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
202 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
203 final var number
= canonicalizedNumbers
.get(n
);
204 final var aci
= registeredUsers
.get(number
);
205 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
210 public void updateAccountAttributes(String deviceName
) throws IOException
{
211 if (deviceName
!= null) {
212 context
.getAccountHelper().setDeviceName(deviceName
);
214 context
.getAccountHelper().updateAccountAttributes();
218 public Configuration
getConfiguration() {
219 final var configurationStore
= account
.getConfigurationStore();
220 return Configuration
.from(configurationStore
);
224 public void updateConfiguration(
225 Configuration configuration
226 ) throws NotMasterDeviceException
{
227 if (!account
.isMasterDevice()) {
228 throw new NotMasterDeviceException();
231 final var configurationStore
= account
.getConfigurationStore();
232 if (configuration
.readReceipts().isPresent()) {
233 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
235 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
236 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
238 if (configuration
.typingIndicators().isPresent()) {
239 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
241 if (configuration
.linkPreviews().isPresent()) {
242 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
244 context
.getSyncHelper().sendConfigurationMessage();
248 public void setProfile(
249 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
250 ) throws IOException
{
251 context
.getProfileHelper().setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
252 context
.getSyncHelper().sendSyncFetchProfileMessage();
256 public void unregister() throws IOException
{
257 context
.getAccountHelper().unregister();
261 public void deleteAccount() throws IOException
{
262 context
.getAccountHelper().deleteAccount();
266 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
267 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
269 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
273 public List
<Device
> getLinkedDevices() throws IOException
{
274 var devices
= dependencies
.getAccountManager().getDevices();
275 account
.setMultiDevice(devices
.size() > 1);
276 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
277 return devices
.stream().map(d
-> {
278 String deviceName
= d
.getName();
279 if (deviceName
!= null) {
281 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
282 } catch (IOException e
) {
283 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
286 return new Device(d
.getId(),
290 d
.getId() == account
.getDeviceId());
295 public void removeLinkedDevices(int deviceId
) throws IOException
{
296 context
.getAccountHelper().removeLinkedDevices(deviceId
);
300 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
301 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
302 context
.getAccountHelper().addDevice(deviceLinkInfo
);
306 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
307 if (!account
.isMasterDevice()) {
308 throw new NotMasterDeviceException();
310 if (pin
.isPresent()) {
311 context
.getAccountHelper().setRegistrationPin(pin
.get());
313 context
.getAccountHelper().removeRegistrationPin();
317 void refreshPreKeys() throws IOException
{
318 context
.getPreKeyHelper().refreshPreKeys();
322 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
323 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
327 public List
<Group
> getGroups() {
328 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
331 private Group
toGroup(final GroupInfo groupInfo
) {
332 if (groupInfo
== null) {
336 return Group
.from(groupInfo
,
337 account
.getRecipientStore()::resolveRecipientAddress
,
338 account
.getSelfRecipientId());
342 public SendGroupMessageResults
quitGroup(
343 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
344 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
345 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
346 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
350 public void deleteGroup(GroupId groupId
) throws IOException
{
351 context
.getGroupHelper().deleteGroup(groupId
);
355 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
356 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
357 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
358 return context
.getGroupHelper()
360 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
365 public SendGroupMessageResults
updateGroup(
366 final GroupId groupId
, final UpdateGroup updateGroup
367 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
368 return context
.getGroupHelper()
369 .updateGroup(groupId
,
370 updateGroup
.getName(),
371 updateGroup
.getDescription(),
372 updateGroup
.getMembers() == null
374 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
375 updateGroup
.getRemoveMembers() == null
377 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
378 updateGroup
.getAdmins() == null
380 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
381 updateGroup
.getRemoveAdmins() == null
383 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
384 updateGroup
.isResetGroupLink(),
385 updateGroup
.getGroupLinkState(),
386 updateGroup
.getAddMemberPermission(),
387 updateGroup
.getEditDetailsPermission(),
388 updateGroup
.getAvatarFile(),
389 updateGroup
.getExpirationTimer(),
390 updateGroup
.getIsAnnouncementGroup());
394 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
395 GroupInviteLinkUrl inviteLinkUrl
396 ) throws IOException
, InactiveGroupLinkException
{
397 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
400 private SendMessageResults
sendMessage(
401 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
402 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
403 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
404 long timestamp
= System
.currentTimeMillis();
405 messageBuilder
.withTimestamp(timestamp
);
406 for (final var recipient
: recipients
) {
407 if (recipient
instanceof RecipientIdentifier
.Single single
) {
409 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
410 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
411 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
412 } catch (UnregisteredRecipientException e
) {
413 results
.put(recipient
,
414 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
416 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
417 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
418 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
419 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
420 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
421 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
424 return new SendMessageResults(timestamp
, results
);
427 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
428 return SendMessageResult
.from(result
,
429 account
.getRecipientStore(),
430 account
.getRecipientStore()::resolveRecipientAddress
);
433 private SendMessageResults
sendTypingMessage(
434 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
435 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
436 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
437 final var timestamp
= System
.currentTimeMillis();
438 for (var recipient
: recipients
) {
439 if (recipient
instanceof RecipientIdentifier
.Single single
) {
440 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
442 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
443 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
444 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
445 } catch (UnregisteredRecipientException e
) {
446 results
.put(recipient
,
447 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
449 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
450 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
451 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
452 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
453 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
456 return new SendMessageResults(timestamp
, results
);
460 public SendMessageResults
sendTypingMessage(
461 TypingAction action
, Set
<RecipientIdentifier
> recipients
462 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
463 return sendTypingMessage(action
.toSignalService(), recipients
);
467 public SendMessageResults
sendReadReceipt(
468 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
469 ) throws IOException
{
470 final var timestamp
= System
.currentTimeMillis();
471 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
475 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
479 public SendMessageResults
sendViewedReceipt(
480 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
481 ) throws IOException
{
482 final var timestamp
= System
.currentTimeMillis();
483 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
487 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
490 private SendMessageResults
sendReceiptMessage(
491 final RecipientIdentifier
.Single sender
,
492 final long timestamp
,
493 final SignalServiceReceiptMessage receiptMessage
494 ) throws IOException
{
496 final var result
= context
.getSendHelper()
497 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
498 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
499 } catch (UnregisteredRecipientException e
) {
500 return new SendMessageResults(timestamp
,
501 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
506 public SendMessageResults
sendMessage(
507 Message message
, Set
<RecipientIdentifier
> recipients
508 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
509 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
510 applyMessage(messageBuilder
, message
);
511 return sendMessage(messageBuilder
, recipients
);
514 private void applyMessage(
515 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
516 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
517 messageBuilder
.withBody(message
.messageText());
518 final var attachments
= message
.attachments();
519 if (attachments
!= null) {
520 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
522 if (message
.mentions().size() > 0) {
523 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
525 if (message
.quote().isPresent()) {
526 final var quote
= message
.quote().get();
527 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
528 context
.getRecipientHelper()
529 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
532 resolveMentions(quote
.mentions())));
534 if (message
.sticker().isPresent()) {
535 final var sticker
= message
.sticker().get();
536 final var packId
= StickerPackId
.deserialize(sticker
.packId());
537 final var stickerId
= sticker
.stickerId();
539 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
540 if (stickerPack
== null) {
541 throw new InvalidStickerException("Sticker pack not found");
543 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
544 if (manifest
.stickers().size() <= stickerId
) {
545 throw new InvalidStickerException("Sticker id not part of this pack");
547 final var manifestSticker
= manifest
.stickers().get(stickerId
);
548 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
549 if (streamDetails
== null) {
550 throw new InvalidStickerException("Missing local sticker file");
552 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
553 stickerPack
.getPackKey(),
555 manifestSticker
.emoji(),
556 AttachmentUtils
.createAttachment(streamDetails
, Optional
.empty())));
560 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
561 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
562 for (final var m
: mentionList
) {
563 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
564 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
565 .resolveSignalServiceAddress(recipientId
)
566 .getServiceId(), m
.start(), m
.length()));
572 public SendMessageResults
sendRemoteDeleteMessage(
573 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
574 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
575 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
576 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
577 for (final var recipient
: recipients
) {
578 if (recipient
instanceof RecipientIdentifier
.Single r
) {
580 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
581 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
582 } catch (UnregisteredRecipientException ignored
) {
584 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
585 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
588 return sendMessage(messageBuilder
, recipients
);
592 public SendMessageResults
sendMessageReaction(
595 RecipientIdentifier
.Single targetAuthor
,
596 long targetSentTimestamp
,
597 Set
<RecipientIdentifier
> recipients
598 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
599 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
600 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
602 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
603 targetSentTimestamp
);
604 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
605 return sendMessage(messageBuilder
, recipients
);
609 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
610 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
613 return sendMessage(messageBuilder
,
614 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
615 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
616 throw new AssertionError(e
);
618 for (var recipient
: recipients
) {
619 final RecipientId recipientId
;
621 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
622 } catch (UnregisteredRecipientException e
) {
625 account
.getSessionStore().deleteAllSessions(recipientId
);
631 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
632 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
636 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
637 account
.getContactStore()
638 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
642 public void setContactName(
643 RecipientIdentifier
.Single recipient
, String name
644 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
645 if (!account
.isMasterDevice()) {
646 throw new NotMasterDeviceException();
648 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
652 public void setContactBlocked(
653 RecipientIdentifier
.Single recipient
, boolean blocked
654 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
655 if (!account
.isMasterDevice()) {
656 throw new NotMasterDeviceException();
658 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
659 // TODO cycle our profile key, if we're not together in a group with recipient
660 context
.getSyncHelper().sendBlockedList();
664 public void setGroupBlocked(
665 final GroupId groupId
, final boolean blocked
666 ) throws GroupNotFoundException
, NotMasterDeviceException
{
667 if (!account
.isMasterDevice()) {
668 throw new NotMasterDeviceException();
670 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
671 // TODO cycle our profile key
672 context
.getSyncHelper().sendBlockedList();
676 public void setExpirationTimer(
677 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
678 ) throws IOException
, UnregisteredRecipientException
{
679 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
680 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
681 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
683 sendMessage(messageBuilder
, Set
.of(recipient
));
684 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
685 throw new AssertionError(e
);
690 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
691 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
693 var messageSender
= dependencies
.getMessageSender();
695 var packKey
= KeyUtils
.createStickerUploadKey();
696 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
697 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
699 var sticker
= new Sticker(packId
, packKey
);
700 account
.getStickerStore().updateSticker(sticker
);
702 return new StickerPackUrl(packId
, packKey
);
706 public List
<StickerPack
> getStickerPacks() {
707 final var stickerPackStore
= context
.getStickerPackStore();
708 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
709 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
711 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
712 return new StickerPack(pack
.getPackId(),
713 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
717 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
718 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
719 } catch (Exception e
) {
720 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
724 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
729 public void requestAllSyncData() throws IOException
{
730 context
.getSyncHelper().requestAllSyncData();
731 retrieveRemoteStorage();
734 void retrieveRemoteStorage() throws IOException
{
735 if (account
.getStorageKey() != null) {
736 context
.getStorageHelper().readDataFromStorage();
741 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
742 if (isReceivingSynchronous
) {
743 throw new IllegalStateException("Already receiving message synchronously.");
745 synchronized (messageHandlers
) {
746 if (isWeakListener
) {
747 weakHandlers
.add(handler
);
749 messageHandlers
.add(handler
);
750 startReceiveThreadIfRequired();
755 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
757 private void startReceiveThreadIfRequired() {
758 if (receiveThread
!= null) {
761 receiveThread
= new Thread(() -> {
762 logger
.debug("Starting receiving messages");
763 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
764 synchronized (messageHandlers
) {
765 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
767 h
.handleMessage(envelope
, e
);
768 } catch (Throwable ex
) {
769 logger
.warn("Message handler failed, ignoring", ex
);
774 logger
.debug("Finished receiving messages");
775 synchronized (messageHandlers
) {
776 receiveThread
= null;
778 // Check if in the meantime another handler has been registered
779 if (!messageHandlers
.isEmpty()) {
780 logger
.debug("Another handler has been registered, starting receive thread again");
781 startReceiveThreadIfRequired();
785 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
787 receiveThread
.start();
791 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
793 synchronized (messageHandlers
) {
794 weakHandlers
.remove(handler
);
795 messageHandlers
.remove(handler
);
796 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
799 thread
= receiveThread
;
800 receiveThread
= null;
803 stopReceiveThread(thread
);
806 private void stopReceiveThread(final Thread thread
) {
807 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
808 logger
.debug("Receive stop requested, interrupting read from server.");
813 } catch (InterruptedException ignored
) {
818 public boolean isReceiving() {
819 if (isReceivingSynchronous
) {
822 synchronized (messageHandlers
) {
823 return messageHandlers
.size() > 0;
828 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
829 receiveMessages(timeout
, true, handler
);
833 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
834 receiveMessages(Duration
.ofMinutes(1), false, handler
);
837 private void receiveMessages(
838 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
839 ) throws IOException
{
841 throw new IllegalStateException("Already receiving message.");
843 isReceivingSynchronous
= true;
844 receiveThread
= Thread
.currentThread();
846 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
848 receiveThread
= null;
849 isReceivingSynchronous
= false;
854 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
855 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
859 public boolean hasCaughtUpWithOldMessages() {
860 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
864 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
865 final RecipientId recipientId
;
867 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
868 } catch (IOException
| UnregisteredRecipientException e
) {
871 return context
.getContactHelper().isContactBlocked(recipientId
);
875 public void sendContacts() throws IOException
{
876 context
.getSyncHelper().sendContacts();
880 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
881 return account
.getContactStore()
884 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
889 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
890 final RecipientId recipientId
;
892 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
893 } catch (IOException
| UnregisteredRecipientException e
) {
897 final var contact
= account
.getContactStore().getContact(recipientId
);
898 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
899 return contact
.getName();
902 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
903 if (profile
!= null) {
904 return profile
.getDisplayName();
911 public Group
getGroup(GroupId groupId
) {
912 return toGroup(context
.getGroupHelper().getGroup(groupId
));
916 public List
<Identity
> getIdentities() {
917 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
920 private Identity
toIdentity(final IdentityInfo identityInfo
) {
921 if (identityInfo
== null) {
925 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
926 final var scannableFingerprint
= context
.getIdentityHelper()
927 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
928 return new Identity(address
,
929 identityInfo
.getIdentityKey(),
930 context
.getIdentityHelper()
931 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
932 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
933 identityInfo
.getTrustLevel(),
934 identityInfo
.getDateAdded());
938 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
939 IdentityInfo identity
;
941 identity
= account
.getIdentityKeyStore()
942 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
943 } catch (IOException
| UnregisteredRecipientException e
) {
946 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
950 public boolean trustIdentityVerified(
951 RecipientIdentifier
.Single recipient
, byte[] fingerprint
952 ) throws UnregisteredRecipientException
{
953 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
957 public boolean trustIdentityVerifiedSafetyNumber(
958 RecipientIdentifier
.Single recipient
, String safetyNumber
959 ) throws UnregisteredRecipientException
{
960 return trustIdentity(recipient
,
961 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
965 public boolean trustIdentityVerifiedSafetyNumber(
966 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
967 ) throws UnregisteredRecipientException
{
968 return trustIdentity(recipient
,
969 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
973 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
974 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
977 private boolean trustIdentity(
978 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
979 ) throws UnregisteredRecipientException
{
980 RecipientId recipientId
;
982 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
983 } catch (IOException e
) {
986 final var updated
= trustMethod
.apply(recipientId
);
987 if (updated
&& this.isReceiving()) {
988 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
994 public void addAddressChangedListener(final Runnable listener
) {
995 synchronized (addressChangedListeners
) {
996 addressChangedListeners
.add(listener
);
1001 public void addClosedListener(final Runnable listener
) {
1002 synchronized (closedListeners
) {
1003 closedListeners
.add(listener
);
1008 public void close() {
1010 synchronized (messageHandlers
) {
1011 weakHandlers
.clear();
1012 messageHandlers
.clear();
1013 thread
= receiveThread
;
1014 receiveThread
= null;
1016 if (thread
!= null) {
1017 stopReceiveThread(thread
);
1019 executor
.shutdown();
1021 dependencies
.getSignalWebSocket().disconnect();
1022 disposable
.dispose();
1024 if (account
!= null) {
1028 synchronized (closedListeners
) {
1029 closedListeners
.forEach(Runnable
::run
);
1030 closedListeners
.clear();