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
.api
.UpdateProfile
;
42 import org
.asamk
.signal
.manager
.api
.UserStatus
;
43 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
44 import org
.asamk
.signal
.manager
.groups
.GroupId
;
45 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
46 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
47 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
48 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
49 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
50 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
51 import org
.asamk
.signal
.manager
.helper
.Context
;
52 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
53 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
54 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.Recipient
;
57 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
58 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
59 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
60 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
61 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
62 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
63 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
64 import org
.slf4j
.Logger
;
65 import org
.slf4j
.LoggerFactory
;
66 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
70 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
71 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
72 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
73 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
74 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
75 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
78 import java
.io
.IOException
;
80 import java
.time
.Duration
;
81 import java
.util
.ArrayList
;
82 import java
.util
.Collection
;
83 import java
.util
.HashMap
;
84 import java
.util
.HashSet
;
85 import java
.util
.List
;
87 import java
.util
.Objects
;
88 import java
.util
.Optional
;
90 import java
.util
.concurrent
.ExecutorService
;
91 import java
.util
.concurrent
.Executors
;
92 import java
.util
.concurrent
.atomic
.AtomicInteger
;
93 import java
.util
.concurrent
.locks
.ReentrantLock
;
94 import java
.util
.function
.Function
;
95 import java
.util
.stream
.Collectors
;
96 import java
.util
.stream
.Stream
;
98 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
100 class ManagerImpl
implements Manager
{
102 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
104 private SignalAccount account
;
105 private final SignalDependencies dependencies
;
106 private final Context context
;
108 private final ExecutorService executor
= Executors
.newCachedThreadPool();
110 private Thread receiveThread
;
111 private boolean isReceivingSynchronous
;
112 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
113 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
114 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
115 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
116 private final CompositeDisposable disposable
= new CompositeDisposable();
119 SignalAccount account
,
120 PathConfig pathConfig
,
121 AccountFileUpdater accountFileUpdater
,
122 ServiceEnvironmentConfig serviceEnvironmentConfig
,
125 this.account
= account
;
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
.getProfileStore().getProfile(recipientId
);
172 if (profile
!= null) {
173 account
.getProfileStore()
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
, UserStatus
> getUserStatus(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 final var profile
= aci
== null
218 : context
.getProfileHelper()
219 .getRecipientProfile(account
.getRecipientResolver().resolveRecipient(aci
));
220 return new UserStatus(number
.isEmpty() ?
null : number
,
221 aci
== null ?
null : aci
.uuid(),
223 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
228 public void updateAccountAttributes(String deviceName
) throws IOException
{
229 if (deviceName
!= null) {
230 context
.getAccountHelper().setDeviceName(deviceName
);
232 context
.getAccountHelper().updateAccountAttributes();
236 public Configuration
getConfiguration() {
237 final var configurationStore
= account
.getConfigurationStore();
238 return Configuration
.from(configurationStore
);
242 public void updateConfiguration(
243 Configuration configuration
244 ) throws NotMasterDeviceException
{
245 if (!account
.isMasterDevice()) {
246 throw new NotMasterDeviceException();
249 final var configurationStore
= account
.getConfigurationStore();
250 if (configuration
.readReceipts().isPresent()) {
251 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
253 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
254 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
256 if (configuration
.typingIndicators().isPresent()) {
257 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
259 if (configuration
.linkPreviews().isPresent()) {
260 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
262 context
.getSyncHelper().sendConfigurationMessage();
266 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
267 context
.getProfileHelper()
268 .setProfile(updateProfile
.getGivenName(),
269 updateProfile
.getFamilyName(),
270 updateProfile
.getAbout(),
271 updateProfile
.getAboutEmoji(),
272 updateProfile
.isDeleteAvatar()
274 : updateProfile
.getAvatar() == null ?
null : Optional
.of(updateProfile
.getAvatar()),
275 updateProfile
.getMobileCoinAddress());
276 context
.getSyncHelper().sendSyncFetchProfileMessage();
280 public void unregister() throws IOException
{
281 context
.getAccountHelper().unregister();
285 public void deleteAccount() throws IOException
{
286 context
.getAccountHelper().deleteAccount();
290 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
291 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
293 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
297 public List
<Device
> getLinkedDevices() throws IOException
{
298 var devices
= dependencies
.getAccountManager().getDevices();
299 account
.setMultiDevice(devices
.size() > 1);
300 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
301 return devices
.stream().map(d
-> {
302 String deviceName
= d
.getName();
303 if (deviceName
!= null) {
305 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
306 } catch (IOException e
) {
307 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
310 return new Device(d
.getId(),
314 d
.getId() == account
.getDeviceId());
319 public void removeLinkedDevices(int deviceId
) throws IOException
{
320 context
.getAccountHelper().removeLinkedDevices(deviceId
);
324 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
325 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
326 context
.getAccountHelper().addDevice(deviceLinkInfo
);
330 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
331 if (!account
.isMasterDevice()) {
332 throw new NotMasterDeviceException();
334 if (pin
.isPresent()) {
335 context
.getAccountHelper().setRegistrationPin(pin
.get());
337 context
.getAccountHelper().removeRegistrationPin();
341 void refreshPreKeys() throws IOException
{
342 context
.getPreKeyHelper().refreshPreKeys();
346 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
347 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
351 public List
<Group
> getGroups() {
352 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
355 private Group
toGroup(final GroupInfo groupInfo
) {
356 if (groupInfo
== null) {
360 return Group
.from(groupInfo
, account
.getRecipientAddressResolver(), account
.getSelfRecipientId());
364 public SendGroupMessageResults
quitGroup(
365 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
366 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
367 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
368 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
372 public void deleteGroup(GroupId groupId
) throws IOException
{
373 final var group
= context
.getGroupHelper().getGroup(groupId
);
374 if (group
.isMember(account
.getSelfRecipientId())) {
375 throw new IOException(
376 "The local group information cannot be removed, as the user is still a member of the group");
378 context
.getGroupHelper().deleteGroup(groupId
);
382 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
383 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
384 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
385 return context
.getGroupHelper()
387 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
392 public SendGroupMessageResults
updateGroup(
393 final GroupId groupId
, final UpdateGroup updateGroup
394 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
395 return context
.getGroupHelper()
396 .updateGroup(groupId
,
397 updateGroup
.getName(),
398 updateGroup
.getDescription(),
399 updateGroup
.getMembers() == null
401 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
402 updateGroup
.getRemoveMembers() == null
404 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
405 updateGroup
.getAdmins() == null
407 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
408 updateGroup
.getRemoveAdmins() == null
410 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
411 updateGroup
.getBanMembers() == null
413 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
414 updateGroup
.getUnbanMembers() == null
416 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
417 updateGroup
.isResetGroupLink(),
418 updateGroup
.getGroupLinkState(),
419 updateGroup
.getAddMemberPermission(),
420 updateGroup
.getEditDetailsPermission(),
421 updateGroup
.getAvatarFile(),
422 updateGroup
.getExpirationTimer(),
423 updateGroup
.getIsAnnouncementGroup());
427 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
428 GroupInviteLinkUrl inviteLinkUrl
429 ) throws IOException
, InactiveGroupLinkException
{
430 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
433 private SendMessageResults
sendMessage(
434 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
435 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
436 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
437 long timestamp
= System
.currentTimeMillis();
438 messageBuilder
.withTimestamp(timestamp
);
439 for (final var recipient
: recipients
) {
440 if (recipient
instanceof RecipientIdentifier
.Single single
) {
442 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
443 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, 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
.NoteToSelf
) {
450 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
451 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
452 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
453 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
454 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
457 return new SendMessageResults(timestamp
, results
);
460 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
461 return SendMessageResult
.from(result
, account
.getRecipientResolver(), account
.getRecipientAddressResolver());
464 private SendMessageResults
sendTypingMessage(
465 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
466 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
467 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
468 final var timestamp
= System
.currentTimeMillis();
469 for (var recipient
: recipients
) {
470 if (recipient
instanceof RecipientIdentifier
.Single single
) {
471 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
473 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
474 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
475 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
476 } catch (UnregisteredRecipientException e
) {
477 results
.put(recipient
,
478 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
480 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
481 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
482 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
483 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
484 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
487 return new SendMessageResults(timestamp
, results
);
491 public SendMessageResults
sendTypingMessage(
492 TypingAction action
, Set
<RecipientIdentifier
> recipients
493 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
494 return sendTypingMessage(action
.toSignalService(), recipients
);
498 public SendMessageResults
sendReadReceipt(
499 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
501 final var timestamp
= System
.currentTimeMillis();
502 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
506 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
510 public SendMessageResults
sendViewedReceipt(
511 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
513 final var timestamp
= System
.currentTimeMillis();
514 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
518 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
521 private SendMessageResults
sendReceiptMessage(
522 final RecipientIdentifier
.Single sender
,
523 final long timestamp
,
524 final SignalServiceReceiptMessage receiptMessage
527 final var result
= context
.getSendHelper()
528 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
529 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
530 } catch (UnregisteredRecipientException e
) {
531 return new SendMessageResults(timestamp
,
532 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
537 public SendMessageResults
sendMessage(
538 Message message
, Set
<RecipientIdentifier
> recipients
539 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
540 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
541 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
543 "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.");
545 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
546 applyMessage(messageBuilder
, message
);
547 return sendMessage(messageBuilder
, recipients
);
550 private void applyMessage(
551 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
552 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
553 messageBuilder
.withBody(message
.messageText());
554 final var attachments
= message
.attachments();
555 if (attachments
!= null) {
556 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
558 if (message
.mentions().size() > 0) {
559 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
561 if (message
.quote().isPresent()) {
562 final var quote
= message
.quote().get();
563 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
564 context
.getRecipientHelper()
565 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
568 resolveMentions(quote
.mentions()),
569 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
571 if (message
.sticker().isPresent()) {
572 final var sticker
= message
.sticker().get();
573 final var packId
= StickerPackId
.deserialize(sticker
.packId());
574 final var stickerId
= sticker
.stickerId();
576 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
577 if (stickerPack
== null) {
578 throw new InvalidStickerException("Sticker pack not found");
580 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
581 if (manifest
.stickers().size() <= stickerId
) {
582 throw new InvalidStickerException("Sticker id not part of this pack");
584 final var manifestSticker
= manifest
.stickers().get(stickerId
);
585 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
586 if (streamDetails
== null) {
587 throw new InvalidStickerException("Missing local sticker file");
589 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
590 stickerPack
.getPackKey(),
592 manifestSticker
.emoji(),
593 AttachmentUtils
.createAttachment(streamDetails
, Optional
.empty())));
597 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
598 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
599 for (final var m
: mentionList
) {
600 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
601 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
602 .resolveSignalServiceAddress(recipientId
)
603 .getServiceId(), m
.start(), m
.length()));
609 public SendMessageResults
sendRemoteDeleteMessage(
610 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
611 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
612 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
613 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
614 for (final var recipient
: recipients
) {
615 if (recipient
instanceof RecipientIdentifier
.Single r
) {
617 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
618 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
619 } catch (UnregisteredRecipientException ignored
) {
621 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
622 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
625 return sendMessage(messageBuilder
, recipients
);
629 public SendMessageResults
sendMessageReaction(
632 RecipientIdentifier
.Single targetAuthor
,
633 long targetSentTimestamp
,
634 Set
<RecipientIdentifier
> recipients
635 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
636 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
637 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
639 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
640 targetSentTimestamp
);
641 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
642 return sendMessage(messageBuilder
, recipients
);
646 public SendMessageResults
sendPaymentNotificationMessage(
647 byte[] receipt
, String note
, RecipientIdentifier
.Single recipient
648 ) throws IOException
{
649 final var paymentNotification
= new SignalServiceDataMessage
.PaymentNotification(receipt
, note
);
650 final var payment
= new SignalServiceDataMessage
.Payment(paymentNotification
);
651 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withPayment(payment
);
653 return sendMessage(messageBuilder
, Set
.of(recipient
));
654 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
655 throw new AssertionError(e
);
660 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
661 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
664 return sendMessage(messageBuilder
,
665 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
666 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
667 throw new AssertionError(e
);
669 for (var recipient
: recipients
) {
670 final RecipientId recipientId
;
672 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
673 } catch (UnregisteredRecipientException e
) {
676 account
.getSessionStore().deleteAllSessions(recipientId
);
682 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
683 account
.removeRecipient(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
687 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
688 account
.getContactStore()
689 .deleteContact(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
693 public void setContactName(
694 RecipientIdentifier
.Single recipient
, String name
695 ) throws NotMasterDeviceException
, UnregisteredRecipientException
{
696 if (!account
.isMasterDevice()) {
697 throw new NotMasterDeviceException();
699 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
703 public void setContactsBlocked(
704 Collection
<RecipientIdentifier
.Single
> recipients
, boolean blocked
705 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
706 if (!account
.isMasterDevice()) {
707 throw new NotMasterDeviceException();
709 if (recipients
.size() == 0) {
712 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
713 final var selfRecipientId
= account
.getSelfRecipientId();
714 boolean shouldRotateProfileKey
= false;
715 for (final var recipientId
: recipientIds
) {
716 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
719 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
720 // if we don't have a common group with the blocked contact we need to rotate the profile key
721 shouldRotateProfileKey
= blocked
&& (
722 shouldRotateProfileKey
|| account
.getGroupStore()
725 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
728 if (shouldRotateProfileKey
) {
729 context
.getProfileHelper().rotateProfileKey();
731 context
.getSyncHelper().sendBlockedList();
735 public void setGroupsBlocked(
736 final Collection
<GroupId
> groupIds
, final boolean blocked
737 ) throws GroupNotFoundException
, NotMasterDeviceException
, IOException
{
738 if (!account
.isMasterDevice()) {
739 throw new NotMasterDeviceException();
741 if (groupIds
.size() == 0) {
744 boolean shouldRotateProfileKey
= false;
745 for (final var groupId
: groupIds
) {
746 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
749 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
750 shouldRotateProfileKey
= blocked
;
752 if (shouldRotateProfileKey
) {
753 context
.getProfileHelper().rotateProfileKey();
755 context
.getSyncHelper().sendBlockedList();
759 public void setExpirationTimer(
760 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
761 ) throws IOException
, UnregisteredRecipientException
{
762 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
763 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
764 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
766 sendMessage(messageBuilder
, Set
.of(recipient
));
767 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
768 throw new AssertionError(e
);
773 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
774 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
776 var messageSender
= dependencies
.getMessageSender();
778 var packKey
= KeyUtils
.createStickerUploadKey();
779 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
780 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
782 var sticker
= new Sticker(packId
, packKey
);
783 account
.getStickerStore().updateSticker(sticker
);
785 return new StickerPackUrl(packId
, packKey
);
789 public List
<StickerPack
> getStickerPacks() {
790 final var stickerPackStore
= context
.getStickerPackStore();
791 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
792 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
794 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
795 return new StickerPack(pack
.getPackId(),
796 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
800 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
801 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
802 } catch (Exception e
) {
803 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
807 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
812 public void requestAllSyncData() throws IOException
{
813 context
.getSyncHelper().requestAllSyncData();
814 retrieveRemoteStorage();
817 void retrieveRemoteStorage() throws IOException
{
818 if (account
.getStorageKey() != null) {
819 context
.getStorageHelper().readDataFromStorage();
824 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
825 if (isReceivingSynchronous
) {
826 throw new IllegalStateException("Already receiving message synchronously.");
828 synchronized (messageHandlers
) {
829 if (isWeakListener
) {
830 weakHandlers
.add(handler
);
832 messageHandlers
.add(handler
);
833 startReceiveThreadIfRequired();
838 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
840 private void startReceiveThreadIfRequired() {
841 if (receiveThread
!= null) {
844 receiveThread
= new Thread(() -> {
845 logger
.debug("Starting receiving messages");
846 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
847 synchronized (messageHandlers
) {
848 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
850 h
.handleMessage(envelope
, e
);
851 } catch (Throwable ex
) {
852 logger
.warn("Message handler failed, ignoring", ex
);
857 logger
.debug("Finished receiving messages");
858 synchronized (messageHandlers
) {
859 receiveThread
= null;
861 // Check if in the meantime another handler has been registered
862 if (!messageHandlers
.isEmpty()) {
863 logger
.debug("Another handler has been registered, starting receive thread again");
864 startReceiveThreadIfRequired();
868 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
870 receiveThread
.start();
874 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
876 synchronized (messageHandlers
) {
877 weakHandlers
.remove(handler
);
878 messageHandlers
.remove(handler
);
879 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
882 thread
= receiveThread
;
883 receiveThread
= null;
886 stopReceiveThread(thread
);
889 private void stopReceiveThread(final Thread thread
) {
890 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
891 logger
.debug("Receive stop requested, interrupting read from server.");
896 } catch (InterruptedException ignored
) {
901 public boolean isReceiving() {
902 if (isReceivingSynchronous
) {
905 synchronized (messageHandlers
) {
906 return messageHandlers
.size() > 0;
911 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
912 receiveMessages(timeout
, true, handler
);
916 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
917 receiveMessages(Duration
.ofMinutes(1), false, handler
);
920 private void receiveMessages(
921 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
922 ) throws IOException
{
924 throw new IllegalStateException("Already receiving message.");
926 isReceivingSynchronous
= true;
927 receiveThread
= Thread
.currentThread();
929 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
931 receiveThread
= null;
932 isReceivingSynchronous
= false;
937 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
938 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
942 public boolean hasCaughtUpWithOldMessages() {
943 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
947 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
948 final RecipientId recipientId
;
950 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
951 } catch (UnregisteredRecipientException e
) {
954 return context
.getContactHelper().isContactBlocked(recipientId
);
958 public void sendContacts() throws IOException
{
959 context
.getSyncHelper().sendContacts();
963 public List
<Recipient
> getRecipients(
964 boolean onlyContacts
,
965 Optional
<Boolean
> blocked
,
966 Collection
<RecipientIdentifier
.Single
> recipients
,
967 Optional
<String
> name
969 final var recipientIds
= recipients
.stream().map(a
-> {
971 return context
.getRecipientHelper().resolveRecipient(a
);
972 } catch (UnregisteredRecipientException e
) {
975 }).filter(Objects
::nonNull
).collect(Collectors
.toSet());
976 // refresh profiles of explicitly given recipients
977 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
978 return account
.getRecipientStore().getRecipients(onlyContacts
, blocked
, recipientIds
, name
);
982 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
983 final RecipientId recipientId
;
985 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
986 } catch (UnregisteredRecipientException e
) {
990 final var contact
= account
.getContactStore().getContact(recipientId
);
991 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
992 return contact
.getName();
995 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
996 if (profile
!= null) {
997 return profile
.getDisplayName();
1004 public Group
getGroup(GroupId groupId
) {
1005 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1009 public List
<Identity
> getIdentities() {
1010 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1013 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1014 if (identityInfo
== null) {
1018 final var address
= account
.getRecipientAddressResolver()
1019 .resolveRecipientAddress(identityInfo
.getRecipientId());
1020 final var scannableFingerprint
= context
.getIdentityHelper()
1021 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
1022 return new Identity(address
,
1023 identityInfo
.getIdentityKey(),
1024 context
.getIdentityHelper()
1025 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1026 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1027 identityInfo
.getTrustLevel(),
1028 identityInfo
.getDateAdded());
1032 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1033 IdentityInfo identity
;
1035 identity
= account
.getIdentityKeyStore()
1036 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
1037 } catch (UnregisteredRecipientException e
) {
1040 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1044 public boolean trustIdentityVerified(
1045 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1046 ) throws UnregisteredRecipientException
{
1047 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
1051 public boolean trustIdentityVerifiedSafetyNumber(
1052 RecipientIdentifier
.Single recipient
, String safetyNumber
1053 ) throws UnregisteredRecipientException
{
1054 return trustIdentity(recipient
,
1055 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1059 public boolean trustIdentityVerifiedSafetyNumber(
1060 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1061 ) throws UnregisteredRecipientException
{
1062 return trustIdentity(recipient
,
1063 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1067 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1068 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1071 private boolean trustIdentity(
1072 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1073 ) throws UnregisteredRecipientException
{
1074 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1075 final var updated
= trustMethod
.apply(recipientId
);
1076 if (updated
&& this.isReceiving()) {
1077 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1083 public void addAddressChangedListener(final Runnable listener
) {
1084 synchronized (addressChangedListeners
) {
1085 addressChangedListeners
.add(listener
);
1090 public void addClosedListener(final Runnable listener
) {
1091 synchronized (closedListeners
) {
1092 closedListeners
.add(listener
);
1097 public void close() {
1099 synchronized (messageHandlers
) {
1100 weakHandlers
.clear();
1101 messageHandlers
.clear();
1102 thread
= receiveThread
;
1103 receiveThread
= null;
1105 if (thread
!= null) {
1106 stopReceiveThread(thread
);
1108 executor
.shutdown();
1110 dependencies
.getSignalWebSocket().disconnect();
1111 disposable
.dispose();
1113 if (account
!= null) {
1117 synchronized (closedListeners
) {
1118 closedListeners
.forEach(Runnable
::run
);
1119 closedListeners
.clear();