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
.push
.ACI
;
70 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
71 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
72 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
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
;
85 import java
.util
.Optional
;
87 import java
.util
.UUID
;
88 import java
.util
.concurrent
.ExecutorService
;
89 import java
.util
.concurrent
.Executors
;
90 import java
.util
.concurrent
.atomic
.AtomicInteger
;
91 import java
.util
.concurrent
.locks
.ReentrantLock
;
92 import java
.util
.function
.Function
;
93 import java
.util
.stream
.Collectors
;
94 import java
.util
.stream
.Stream
;
96 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
98 class ManagerImpl
implements Manager
{
100 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
102 private SignalAccount account
;
103 private AccountFileUpdater accountFileUpdater
;
104 private final SignalDependencies dependencies
;
105 private final Context context
;
107 private final ExecutorService executor
= Executors
.newCachedThreadPool();
109 private Thread receiveThread
;
110 private boolean isReceivingSynchronous
;
111 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
112 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
113 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
114 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
115 private final CompositeDisposable disposable
= new CompositeDisposable();
118 SignalAccount account
,
119 PathConfig pathConfig
,
120 AccountFileUpdater accountFileUpdater
,
121 ServiceEnvironmentConfig serviceEnvironmentConfig
,
124 this.account
= account
;
125 this.accountFileUpdater
= accountFileUpdater
;
127 final var sessionLock
= new SignalSessionLock() {
128 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
131 public Lock
acquire() {
133 return LEGACY_LOCK
::unlock
;
136 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
138 account
.getCredentialsProvider(),
139 account
.getSignalServiceDataStore(),
142 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
143 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
144 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
146 this.context
= new Context(account
, new AccountFileUpdater() {
148 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
149 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
150 synchronized (addressChangedListeners
) {
151 addressChangedListeners
.forEach(Runnable
::run
);
156 public void removeAccount() {
157 accountFileUpdater
.removeAccount();
159 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
160 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
161 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
162 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
163 synchronized (this) {
167 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
168 logger
.trace("Archiving old sessions for {}", recipientId
);
169 account
.getSessionStore().archiveSessions(recipientId
);
170 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
171 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
172 if (profile
!= null) {
173 account
.getRecipientStore()
174 .storeProfile(recipientId
,
175 Profile
.newBuilder(profile
)
176 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
177 .withLastUpdateTimestamp(0)
184 public String
getSelfNumber() {
185 return account
.getNumber();
188 void checkAccountState() throws IOException
{
189 context
.getAccountHelper().checkAccountState();
193 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
194 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
196 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
197 if (!canonicalizedNumber
.equals(n
)) {
198 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
200 return canonicalizedNumber
;
201 } catch (InvalidNumberException e
) {
206 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
207 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
209 .filter(s
-> !s
.isEmpty())
210 .collect(Collectors
.toSet());
211 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
213 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
214 final var number
= canonicalizedNumbers
.get(n
);
215 final var aci
= registeredUsers
.get(number
);
216 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
221 public void updateAccountAttributes(String deviceName
) throws IOException
{
222 if (deviceName
!= null) {
223 context
.getAccountHelper().setDeviceName(deviceName
);
225 context
.getAccountHelper().updateAccountAttributes();
229 public Configuration
getConfiguration() {
230 final var configurationStore
= account
.getConfigurationStore();
231 return Configuration
.from(configurationStore
);
235 public void updateConfiguration(
236 Configuration configuration
237 ) throws NotMasterDeviceException
{
238 if (!account
.isMasterDevice()) {
239 throw new NotMasterDeviceException();
242 final var configurationStore
= account
.getConfigurationStore();
243 if (configuration
.readReceipts().isPresent()) {
244 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
246 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
247 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
249 if (configuration
.typingIndicators().isPresent()) {
250 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
252 if (configuration
.linkPreviews().isPresent()) {
253 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
255 context
.getSyncHelper().sendConfigurationMessage();
259 public void setProfile(
260 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
261 ) throws IOException
{
262 context
.getProfileHelper().setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
263 context
.getSyncHelper().sendSyncFetchProfileMessage();
267 public void unregister() throws IOException
{
268 context
.getAccountHelper().unregister();
272 public void deleteAccount() throws IOException
{
273 context
.getAccountHelper().deleteAccount();
277 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
278 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
280 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
284 public List
<Device
> getLinkedDevices() throws IOException
{
285 var devices
= dependencies
.getAccountManager().getDevices();
286 account
.setMultiDevice(devices
.size() > 1);
287 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
288 return devices
.stream().map(d
-> {
289 String deviceName
= d
.getName();
290 if (deviceName
!= null) {
292 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
293 } catch (IOException e
) {
294 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
297 return new Device(d
.getId(),
301 d
.getId() == account
.getDeviceId());
306 public void removeLinkedDevices(int deviceId
) throws IOException
{
307 context
.getAccountHelper().removeLinkedDevices(deviceId
);
311 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
312 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
313 context
.getAccountHelper().addDevice(deviceLinkInfo
);
317 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
318 if (!account
.isMasterDevice()) {
319 throw new NotMasterDeviceException();
321 if (pin
.isPresent()) {
322 context
.getAccountHelper().setRegistrationPin(pin
.get());
324 context
.getAccountHelper().removeRegistrationPin();
328 void refreshPreKeys() throws IOException
{
329 context
.getPreKeyHelper().refreshPreKeys();
333 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
334 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
338 public List
<Group
> getGroups() {
339 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
342 private Group
toGroup(final GroupInfo groupInfo
) {
343 if (groupInfo
== null) {
347 return Group
.from(groupInfo
,
348 account
.getRecipientStore()::resolveRecipientAddress
,
349 account
.getSelfRecipientId());
353 public SendGroupMessageResults
quitGroup(
354 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
355 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
356 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
357 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
361 public void deleteGroup(GroupId groupId
) throws IOException
{
362 final var group
= context
.getGroupHelper().getGroup(groupId
);
363 if (group
.isMember(account
.getSelfRecipientId())) {
364 throw new IOException(
365 "The local group information cannot be removed, as the user is still a member of the group");
367 context
.getGroupHelper().deleteGroup(groupId
);
371 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
372 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
373 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
374 return context
.getGroupHelper()
376 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
381 public SendGroupMessageResults
updateGroup(
382 final GroupId groupId
, final UpdateGroup updateGroup
383 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
384 return context
.getGroupHelper()
385 .updateGroup(groupId
,
386 updateGroup
.getName(),
387 updateGroup
.getDescription(),
388 updateGroup
.getMembers() == null
390 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
391 updateGroup
.getRemoveMembers() == null
393 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
394 updateGroup
.getAdmins() == null
396 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
397 updateGroup
.getRemoveAdmins() == null
399 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
400 updateGroup
.getBanMembers() == null
402 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
403 updateGroup
.getUnbanMembers() == null
405 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
406 updateGroup
.isResetGroupLink(),
407 updateGroup
.getGroupLinkState(),
408 updateGroup
.getAddMemberPermission(),
409 updateGroup
.getEditDetailsPermission(),
410 updateGroup
.getAvatarFile(),
411 updateGroup
.getExpirationTimer(),
412 updateGroup
.getIsAnnouncementGroup());
416 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
417 GroupInviteLinkUrl inviteLinkUrl
418 ) throws IOException
, InactiveGroupLinkException
{
419 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
422 private SendMessageResults
sendMessage(
423 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
424 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
425 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
426 long timestamp
= System
.currentTimeMillis();
427 messageBuilder
.withTimestamp(timestamp
);
428 for (final var recipient
: recipients
) {
429 if (recipient
instanceof RecipientIdentifier
.Single single
) {
431 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
432 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
433 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
434 } catch (UnregisteredRecipientException e
) {
435 results
.put(recipient
,
436 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
438 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
439 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
440 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
441 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
442 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
443 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
446 return new SendMessageResults(timestamp
, results
);
449 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
450 return SendMessageResult
.from(result
,
451 account
.getRecipientStore(),
452 account
.getRecipientStore()::resolveRecipientAddress
);
455 private SendMessageResults
sendTypingMessage(
456 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
457 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
458 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
459 final var timestamp
= System
.currentTimeMillis();
460 for (var recipient
: recipients
) {
461 if (recipient
instanceof RecipientIdentifier
.Single single
) {
462 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
464 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
465 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
466 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
467 } catch (UnregisteredRecipientException e
) {
468 results
.put(recipient
,
469 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
471 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
472 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
473 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
474 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
475 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
478 return new SendMessageResults(timestamp
, results
);
482 public SendMessageResults
sendTypingMessage(
483 TypingAction action
, Set
<RecipientIdentifier
> recipients
484 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
485 return sendTypingMessage(action
.toSignalService(), recipients
);
489 public SendMessageResults
sendReadReceipt(
490 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
491 ) throws IOException
{
492 final var timestamp
= System
.currentTimeMillis();
493 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
497 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
501 public SendMessageResults
sendViewedReceipt(
502 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
503 ) throws IOException
{
504 final var timestamp
= System
.currentTimeMillis();
505 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
509 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
512 private SendMessageResults
sendReceiptMessage(
513 final RecipientIdentifier
.Single sender
,
514 final long timestamp
,
515 final SignalServiceReceiptMessage receiptMessage
516 ) throws IOException
{
518 final var result
= context
.getSendHelper()
519 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
520 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
521 } catch (UnregisteredRecipientException e
) {
522 return new SendMessageResults(timestamp
,
523 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
528 public SendMessageResults
sendMessage(
529 Message message
, Set
<RecipientIdentifier
> recipients
530 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
531 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
532 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
534 "No profile name set. When sending a message it's recommended to set a profile name wit the updateProfile command. This may become mandatory in the future.");
536 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
537 applyMessage(messageBuilder
, message
);
538 return sendMessage(messageBuilder
, recipients
);
541 private void applyMessage(
542 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
543 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
544 messageBuilder
.withBody(message
.messageText());
545 final var attachments
= message
.attachments();
546 if (attachments
!= null) {
547 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
549 if (message
.mentions().size() > 0) {
550 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
552 if (message
.quote().isPresent()) {
553 final var quote
= message
.quote().get();
554 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
555 context
.getRecipientHelper()
556 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
559 resolveMentions(quote
.mentions()),
560 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
562 if (message
.sticker().isPresent()) {
563 final var sticker
= message
.sticker().get();
564 final var packId
= StickerPackId
.deserialize(sticker
.packId());
565 final var stickerId
= sticker
.stickerId();
567 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
568 if (stickerPack
== null) {
569 throw new InvalidStickerException("Sticker pack not found");
571 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
572 if (manifest
.stickers().size() <= stickerId
) {
573 throw new InvalidStickerException("Sticker id not part of this pack");
575 final var manifestSticker
= manifest
.stickers().get(stickerId
);
576 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
577 if (streamDetails
== null) {
578 throw new InvalidStickerException("Missing local sticker file");
580 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
581 stickerPack
.getPackKey(),
583 manifestSticker
.emoji(),
584 AttachmentUtils
.createAttachment(streamDetails
, Optional
.empty())));
588 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
589 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
590 for (final var m
: mentionList
) {
591 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
592 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
593 .resolveSignalServiceAddress(recipientId
)
594 .getServiceId(), m
.start(), m
.length()));
600 public SendMessageResults
sendRemoteDeleteMessage(
601 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
602 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
603 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
604 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
605 for (final var recipient
: recipients
) {
606 if (recipient
instanceof RecipientIdentifier
.Single r
) {
608 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
609 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
610 } catch (UnregisteredRecipientException ignored
) {
612 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
613 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
616 return sendMessage(messageBuilder
, recipients
);
620 public SendMessageResults
sendMessageReaction(
623 RecipientIdentifier
.Single targetAuthor
,
624 long targetSentTimestamp
,
625 Set
<RecipientIdentifier
> recipients
626 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
627 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
628 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
630 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
631 targetSentTimestamp
);
632 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
633 return sendMessage(messageBuilder
, recipients
);
637 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
638 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
641 return sendMessage(messageBuilder
,
642 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
643 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
644 throw new AssertionError(e
);
646 for (var recipient
: recipients
) {
647 final RecipientId recipientId
;
649 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
650 } catch (UnregisteredRecipientException e
) {
653 account
.getSessionStore().deleteAllSessions(recipientId
);
659 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
660 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
664 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
665 account
.getContactStore()
666 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
670 public void setContactName(
671 RecipientIdentifier
.Single recipient
, String name
672 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
673 if (!account
.isMasterDevice()) {
674 throw new NotMasterDeviceException();
676 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
680 public void setContactBlocked(
681 RecipientIdentifier
.Single recipient
, boolean blocked
682 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
683 if (!account
.isMasterDevice()) {
684 throw new NotMasterDeviceException();
686 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
687 // TODO cycle our profile key, if we're not together in a group with recipient
688 context
.getSyncHelper().sendBlockedList();
692 public void setGroupBlocked(
693 final GroupId groupId
, final boolean blocked
694 ) throws GroupNotFoundException
, NotMasterDeviceException
{
695 if (!account
.isMasterDevice()) {
696 throw new NotMasterDeviceException();
698 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
699 // TODO cycle our profile key
700 context
.getSyncHelper().sendBlockedList();
704 public void setExpirationTimer(
705 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
706 ) throws IOException
, UnregisteredRecipientException
{
707 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
708 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
709 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
711 sendMessage(messageBuilder
, Set
.of(recipient
));
712 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
713 throw new AssertionError(e
);
718 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
719 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
721 var messageSender
= dependencies
.getMessageSender();
723 var packKey
= KeyUtils
.createStickerUploadKey();
724 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
725 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
727 var sticker
= new Sticker(packId
, packKey
);
728 account
.getStickerStore().updateSticker(sticker
);
730 return new StickerPackUrl(packId
, packKey
);
734 public List
<StickerPack
> getStickerPacks() {
735 final var stickerPackStore
= context
.getStickerPackStore();
736 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
737 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
739 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
740 return new StickerPack(pack
.getPackId(),
741 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
745 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
746 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
747 } catch (Exception e
) {
748 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
752 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
757 public void requestAllSyncData() throws IOException
{
758 context
.getSyncHelper().requestAllSyncData();
759 retrieveRemoteStorage();
762 void retrieveRemoteStorage() throws IOException
{
763 if (account
.getStorageKey() != null) {
764 context
.getStorageHelper().readDataFromStorage();
769 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
770 if (isReceivingSynchronous
) {
771 throw new IllegalStateException("Already receiving message synchronously.");
773 synchronized (messageHandlers
) {
774 if (isWeakListener
) {
775 weakHandlers
.add(handler
);
777 messageHandlers
.add(handler
);
778 startReceiveThreadIfRequired();
783 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
785 private void startReceiveThreadIfRequired() {
786 if (receiveThread
!= null) {
789 receiveThread
= new Thread(() -> {
790 logger
.debug("Starting receiving messages");
791 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
792 synchronized (messageHandlers
) {
793 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
795 h
.handleMessage(envelope
, e
);
796 } catch (Throwable ex
) {
797 logger
.warn("Message handler failed, ignoring", ex
);
802 logger
.debug("Finished receiving messages");
803 synchronized (messageHandlers
) {
804 receiveThread
= null;
806 // Check if in the meantime another handler has been registered
807 if (!messageHandlers
.isEmpty()) {
808 logger
.debug("Another handler has been registered, starting receive thread again");
809 startReceiveThreadIfRequired();
813 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
815 receiveThread
.start();
819 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
821 synchronized (messageHandlers
) {
822 weakHandlers
.remove(handler
);
823 messageHandlers
.remove(handler
);
824 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
827 thread
= receiveThread
;
828 receiveThread
= null;
831 stopReceiveThread(thread
);
834 private void stopReceiveThread(final Thread thread
) {
835 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
836 logger
.debug("Receive stop requested, interrupting read from server.");
841 } catch (InterruptedException ignored
) {
846 public boolean isReceiving() {
847 if (isReceivingSynchronous
) {
850 synchronized (messageHandlers
) {
851 return messageHandlers
.size() > 0;
856 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
857 receiveMessages(timeout
, true, handler
);
861 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
862 receiveMessages(Duration
.ofMinutes(1), false, handler
);
865 private void receiveMessages(
866 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
867 ) throws IOException
{
869 throw new IllegalStateException("Already receiving message.");
871 isReceivingSynchronous
= true;
872 receiveThread
= Thread
.currentThread();
874 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
876 receiveThread
= null;
877 isReceivingSynchronous
= false;
882 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
883 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
887 public boolean hasCaughtUpWithOldMessages() {
888 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
892 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
893 final RecipientId recipientId
;
895 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
896 } catch (IOException
| UnregisteredRecipientException e
) {
899 return context
.getContactHelper().isContactBlocked(recipientId
);
903 public void sendContacts() throws IOException
{
904 context
.getSyncHelper().sendContacts();
908 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
909 return account
.getContactStore()
912 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
917 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
918 final RecipientId recipientId
;
920 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
921 } catch (IOException
| UnregisteredRecipientException e
) {
925 final var contact
= account
.getContactStore().getContact(recipientId
);
926 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
927 return contact
.getName();
930 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
931 if (profile
!= null) {
932 return profile
.getDisplayName();
939 public Group
getGroup(GroupId groupId
) {
940 return toGroup(context
.getGroupHelper().getGroup(groupId
));
944 public List
<Identity
> getIdentities() {
945 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
948 private Identity
toIdentity(final IdentityInfo identityInfo
) {
949 if (identityInfo
== null) {
953 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
954 final var scannableFingerprint
= context
.getIdentityHelper()
955 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
956 return new Identity(address
,
957 identityInfo
.getIdentityKey(),
958 context
.getIdentityHelper()
959 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
960 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
961 identityInfo
.getTrustLevel(),
962 identityInfo
.getDateAdded());
966 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
967 IdentityInfo identity
;
969 identity
= account
.getIdentityKeyStore()
970 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
971 } catch (IOException
| UnregisteredRecipientException e
) {
974 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
978 public boolean trustIdentityVerified(
979 RecipientIdentifier
.Single recipient
, byte[] fingerprint
980 ) throws UnregisteredRecipientException
{
981 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
985 public boolean trustIdentityVerifiedSafetyNumber(
986 RecipientIdentifier
.Single recipient
, String safetyNumber
987 ) throws UnregisteredRecipientException
{
988 return trustIdentity(recipient
,
989 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
993 public boolean trustIdentityVerifiedSafetyNumber(
994 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
995 ) throws UnregisteredRecipientException
{
996 return trustIdentity(recipient
,
997 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1001 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1002 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1005 private boolean trustIdentity(
1006 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1007 ) throws UnregisteredRecipientException
{
1008 RecipientId recipientId
;
1010 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1011 } catch (IOException e
) {
1014 final var updated
= trustMethod
.apply(recipientId
);
1015 if (updated
&& this.isReceiving()) {
1016 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1022 public void addAddressChangedListener(final Runnable listener
) {
1023 synchronized (addressChangedListeners
) {
1024 addressChangedListeners
.add(listener
);
1029 public void addClosedListener(final Runnable listener
) {
1030 synchronized (closedListeners
) {
1031 closedListeners
.add(listener
);
1036 public void close() {
1038 synchronized (messageHandlers
) {
1039 weakHandlers
.clear();
1040 messageHandlers
.clear();
1041 thread
= receiveThread
;
1042 receiveThread
= null;
1044 if (thread
!= null) {
1045 stopReceiveThread(thread
);
1047 executor
.shutdown();
1049 dependencies
.getSignalWebSocket().disconnect();
1050 disposable
.dispose();
1052 if (account
!= null) {
1056 synchronized (closedListeners
) {
1057 closedListeners
.forEach(Runnable
::run
);
1058 closedListeners
.clear();