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
.NotPrimaryDeviceException
;
29 import org
.asamk
.signal
.manager
.api
.Pair
;
30 import org
.asamk
.signal
.manager
.api
.ReceiveConfig
;
31 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
32 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
33 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
34 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
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
.StickerPack
;
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
.SignalServicePreview
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
70 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
71 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
72 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
73 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
74 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
75 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
76 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
77 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
80 import java
.io
.IOException
;
82 import java
.time
.Duration
;
83 import java
.util
.ArrayList
;
84 import java
.util
.Collection
;
85 import java
.util
.HashMap
;
86 import java
.util
.HashSet
;
87 import java
.util
.List
;
89 import java
.util
.Objects
;
90 import java
.util
.Optional
;
92 import java
.util
.concurrent
.ExecutorService
;
93 import java
.util
.concurrent
.Executors
;
94 import java
.util
.concurrent
.atomic
.AtomicInteger
;
95 import java
.util
.concurrent
.locks
.ReentrantLock
;
96 import java
.util
.function
.Function
;
97 import java
.util
.stream
.Collectors
;
98 import java
.util
.stream
.Stream
;
100 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
102 class ManagerImpl
implements Manager
{
104 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
106 private SignalAccount account
;
107 private final SignalDependencies dependencies
;
108 private final Context context
;
110 private final ExecutorService executor
= Executors
.newCachedThreadPool();
112 private Thread receiveThread
;
113 private boolean isReceivingSynchronous
;
114 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
115 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
116 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
117 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
118 private final CompositeDisposable disposable
= new CompositeDisposable();
121 SignalAccount account
,
122 PathConfig pathConfig
,
123 AccountFileUpdater accountFileUpdater
,
124 ServiceEnvironmentConfig serviceEnvironmentConfig
,
127 this.account
= account
;
129 final var sessionLock
= new SignalSessionLock() {
130 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
133 public Lock
acquire() {
135 return LEGACY_LOCK
::unlock
;
138 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
140 account
.getCredentialsProvider(),
141 account
.getSignalServiceDataStore(),
144 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
145 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
146 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
148 this.context
= new Context(account
, new AccountFileUpdater() {
150 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
151 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
152 synchronized (addressChangedListeners
) {
153 addressChangedListeners
.forEach(Runnable
::run
);
158 public void removeAccount() {
159 accountFileUpdater
.removeAccount();
161 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
162 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
163 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
164 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
165 synchronized (this) {
169 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(serviceId
-> {
170 logger
.trace("Archiving old sessions for {}", serviceId
);
171 account
.getAciSessionStore().archiveSessions(serviceId
);
172 account
.getPniSessionStore().archiveSessions(serviceId
);
173 account
.getSenderKeyStore().deleteSharedWith(serviceId
);
174 final var recipientId
= account
.getRecipientResolver().resolveRecipient(serviceId
);
175 final var profile
= account
.getProfileStore().getProfile(recipientId
);
176 if (profile
!= null) {
177 account
.getProfileStore()
178 .storeProfile(recipientId
,
179 Profile
.newBuilder(profile
)
180 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
181 .withLastUpdateTimestamp(0)
188 public String
getSelfNumber() {
189 return account
.getNumber();
192 void checkAccountState() throws IOException
{
193 context
.getAccountHelper().checkAccountState();
197 public Map
<String
, UserStatus
> getUserStatus(Set
<String
> numbers
) throws IOException
{
198 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
200 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
201 if (!canonicalizedNumber
.equals(n
)) {
202 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
204 return canonicalizedNumber
;
205 } catch (InvalidNumberException e
) {
210 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
211 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
213 .filter(s
-> !s
.isEmpty())
214 .collect(Collectors
.toSet());
215 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
217 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
218 final var number
= canonicalizedNumbers
.get(n
);
219 final var aci
= registeredUsers
.get(number
);
220 final var profile
= aci
== null
222 : context
.getProfileHelper()
223 .getRecipientProfile(account
.getRecipientResolver().resolveRecipient(aci
));
224 return new UserStatus(number
.isEmpty() ?
null : number
,
225 aci
== null ?
null : aci
.uuid(),
227 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
232 public void updateAccountAttributes(String deviceName
) throws IOException
{
233 if (deviceName
!= null) {
234 context
.getAccountHelper().setDeviceName(deviceName
);
236 context
.getAccountHelper().updateAccountAttributes();
237 context
.getAccountHelper().checkWhoAmiI();
241 public Configuration
getConfiguration() {
242 final var configurationStore
= account
.getConfigurationStore();
243 return Configuration
.from(configurationStore
);
247 public void updateConfiguration(
248 Configuration configuration
249 ) throws NotPrimaryDeviceException
{
250 if (!account
.isPrimaryDevice()) {
251 throw new NotPrimaryDeviceException();
254 final var configurationStore
= account
.getConfigurationStore();
255 if (configuration
.readReceipts().isPresent()) {
256 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
258 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
259 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
261 if (configuration
.typingIndicators().isPresent()) {
262 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
264 if (configuration
.linkPreviews().isPresent()) {
265 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
267 context
.getSyncHelper().sendConfigurationMessage();
271 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
272 context
.getProfileHelper()
273 .setProfile(updateProfile
.getGivenName(),
274 updateProfile
.getFamilyName(),
275 updateProfile
.getAbout(),
276 updateProfile
.getAboutEmoji(),
277 updateProfile
.isDeleteAvatar()
279 : updateProfile
.getAvatar() == null ?
null : Optional
.of(updateProfile
.getAvatar()),
280 updateProfile
.getMobileCoinAddress());
281 context
.getSyncHelper().sendSyncFetchProfileMessage();
285 public void unregister() throws IOException
{
286 context
.getAccountHelper().unregister();
290 public void deleteAccount() throws IOException
{
291 context
.getAccountHelper().deleteAccount();
295 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
296 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
298 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
302 public List
<Device
> getLinkedDevices() throws IOException
{
303 var devices
= dependencies
.getAccountManager().getDevices();
304 account
.setMultiDevice(devices
.size() > 1);
305 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
306 return devices
.stream().map(d
-> {
307 String deviceName
= d
.getName();
308 if (deviceName
!= null) {
310 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
311 } catch (IOException e
) {
312 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
315 return new Device(d
.getId(),
319 d
.getId() == account
.getDeviceId());
324 public void removeLinkedDevices(int deviceId
) throws IOException
{
325 context
.getAccountHelper().removeLinkedDevices(deviceId
);
329 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
330 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
331 context
.getAccountHelper().addDevice(deviceLinkInfo
);
335 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotPrimaryDeviceException
{
336 if (!account
.isPrimaryDevice()) {
337 throw new NotPrimaryDeviceException();
339 if (pin
.isPresent()) {
340 context
.getAccountHelper().setRegistrationPin(pin
.get());
342 context
.getAccountHelper().removeRegistrationPin();
346 void refreshPreKeys() throws IOException
{
347 context
.getPreKeyHelper().refreshPreKeys();
351 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
352 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
356 public List
<Group
> getGroups() {
357 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
360 private Group
toGroup(final GroupInfo groupInfo
) {
361 if (groupInfo
== null) {
365 return Group
.from(groupInfo
, account
.getRecipientAddressResolver(), account
.getSelfRecipientId());
369 public SendGroupMessageResults
quitGroup(
370 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
371 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
372 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
373 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
377 public void deleteGroup(GroupId groupId
) throws IOException
{
378 final var group
= context
.getGroupHelper().getGroup(groupId
);
379 if (group
.isMember(account
.getSelfRecipientId())) {
380 throw new IOException(
381 "The local group information cannot be removed, as the user is still a member of the group");
383 context
.getGroupHelper().deleteGroup(groupId
);
387 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
388 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
389 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
390 return context
.getGroupHelper()
392 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
397 public SendGroupMessageResults
updateGroup(
398 final GroupId groupId
, final UpdateGroup updateGroup
399 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
400 return context
.getGroupHelper()
401 .updateGroup(groupId
,
402 updateGroup
.getName(),
403 updateGroup
.getDescription(),
404 updateGroup
.getMembers() == null
406 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
407 updateGroup
.getRemoveMembers() == null
409 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
410 updateGroup
.getAdmins() == null
412 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
413 updateGroup
.getRemoveAdmins() == null
415 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
416 updateGroup
.getBanMembers() == null
418 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
419 updateGroup
.getUnbanMembers() == null
421 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
422 updateGroup
.isResetGroupLink(),
423 updateGroup
.getGroupLinkState(),
424 updateGroup
.getAddMemberPermission(),
425 updateGroup
.getEditDetailsPermission(),
426 updateGroup
.getAvatarFile(),
427 updateGroup
.getExpirationTimer(),
428 updateGroup
.getIsAnnouncementGroup());
432 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
433 GroupInviteLinkUrl inviteLinkUrl
434 ) throws IOException
, InactiveGroupLinkException
{
435 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
438 private SendMessageResults
sendMessage(
439 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
440 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
441 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
442 long timestamp
= System
.currentTimeMillis();
443 messageBuilder
.withTimestamp(timestamp
);
444 for (final var recipient
: recipients
) {
445 if (recipient
instanceof RecipientIdentifier
.Single single
) {
447 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
448 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
449 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
450 } catch (UnregisteredRecipientException e
) {
451 results
.put(recipient
,
452 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
454 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
455 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
456 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
457 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
458 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
459 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
462 return new SendMessageResults(timestamp
, results
);
465 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
466 return SendMessageResult
.from(result
, account
.getRecipientResolver(), account
.getRecipientAddressResolver());
469 private SendMessageResults
sendTypingMessage(
470 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
471 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
472 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
473 final var timestamp
= System
.currentTimeMillis();
474 for (var recipient
: recipients
) {
475 if (recipient
instanceof RecipientIdentifier
.Single single
) {
476 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
478 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
479 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
480 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
481 } catch (UnregisteredRecipientException e
) {
482 results
.put(recipient
,
483 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
485 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
486 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
487 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
488 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
489 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
492 return new SendMessageResults(timestamp
, results
);
496 public SendMessageResults
sendTypingMessage(
497 TypingAction action
, Set
<RecipientIdentifier
> recipients
498 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
499 return sendTypingMessage(action
.toSignalService(), recipients
);
503 public SendMessageResults
sendReadReceipt(
504 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
506 final var timestamp
= System
.currentTimeMillis();
507 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
511 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
515 public SendMessageResults
sendViewedReceipt(
516 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
518 final var timestamp
= System
.currentTimeMillis();
519 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
523 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
526 private SendMessageResults
sendReceiptMessage(
527 final RecipientIdentifier
.Single sender
,
528 final long timestamp
,
529 final SignalServiceReceiptMessage receiptMessage
532 final var result
= context
.getSendHelper()
533 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
534 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
535 } catch (UnregisteredRecipientException e
) {
536 return new SendMessageResults(timestamp
,
537 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
542 public SendMessageResults
sendMessage(
543 Message message
, Set
<RecipientIdentifier
> recipients
544 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
545 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
546 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
548 "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.");
550 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
551 applyMessage(messageBuilder
, message
);
552 return sendMessage(messageBuilder
, recipients
);
555 private void applyMessage(
556 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
557 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
558 messageBuilder
.withBody(message
.messageText());
559 if (message
.attachments().size() > 0) {
560 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(message
.attachments()));
562 if (message
.mentions().size() > 0) {
563 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
565 if (message
.quote().isPresent()) {
566 final var quote
= message
.quote().get();
567 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
568 context
.getRecipientHelper()
569 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author()))
573 resolveMentions(quote
.mentions()),
574 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
576 if (message
.sticker().isPresent()) {
577 final var sticker
= message
.sticker().get();
578 final var packId
= StickerPackId
.deserialize(sticker
.packId());
579 final var stickerId
= sticker
.stickerId();
581 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
582 if (stickerPack
== null) {
583 throw new InvalidStickerException("Sticker pack not found");
585 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.packKey());
586 if (manifest
.stickers().size() <= stickerId
) {
587 throw new InvalidStickerException("Sticker id not part of this pack");
589 final var manifestSticker
= manifest
.stickers().get(stickerId
);
590 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
591 if (streamDetails
== null) {
592 throw new InvalidStickerException("Missing local sticker file");
594 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
595 stickerPack
.packKey(),
597 manifestSticker
.emoji(),
598 AttachmentUtils
.createAttachmentStream(streamDetails
, Optional
.empty())));
600 if (message
.previews().size() > 0) {
601 final var previews
= new ArrayList
<SignalServicePreview
>(message
.previews().size());
602 for (final var p
: message
.previews()) {
603 final var image
= p
.image().isPresent() ? context
.getAttachmentHelper()
604 .uploadAttachment(p
.image().get()) : null;
605 previews
.add(new SignalServicePreview(p
.url(),
609 Optional
.ofNullable(image
)));
611 messageBuilder
.withPreviews(previews
);
615 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
616 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
617 for (final var m
: mentionList
) {
618 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
619 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
620 .resolveSignalServiceAddress(recipientId
)
621 .getServiceId(), m
.start(), m
.length()));
627 public SendMessageResults
sendRemoteDeleteMessage(
628 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
629 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
630 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
631 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
632 for (final var recipient
: recipients
) {
633 if (recipient
instanceof RecipientIdentifier
.Single r
) {
635 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
636 account
.getMessageSendLogStore()
637 .deleteEntryForRecipientNonGroup(targetSentTimestamp
,
638 account
.getRecipientAddressResolver()
639 .resolveRecipientAddress(recipientId
)
641 } catch (UnregisteredRecipientException ignored
) {
643 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
644 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
647 return sendMessage(messageBuilder
, recipients
);
651 public SendMessageResults
sendMessageReaction(
654 RecipientIdentifier
.Single targetAuthor
,
655 long targetSentTimestamp
,
656 Set
<RecipientIdentifier
> recipients
657 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
658 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
659 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
661 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
).getServiceId(),
662 targetSentTimestamp
);
663 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
664 return sendMessage(messageBuilder
, recipients
);
668 public SendMessageResults
sendPaymentNotificationMessage(
669 byte[] receipt
, String note
, RecipientIdentifier
.Single recipient
670 ) throws IOException
{
671 final var paymentNotification
= new SignalServiceDataMessage
.PaymentNotification(receipt
, note
);
672 final var payment
= new SignalServiceDataMessage
.Payment(paymentNotification
);
673 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withPayment(payment
);
675 return sendMessage(messageBuilder
, Set
.of(recipient
));
676 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
677 throw new AssertionError(e
);
682 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
683 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
686 return sendMessage(messageBuilder
,
687 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
688 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
689 throw new AssertionError(e
);
691 for (var recipient
: recipients
) {
692 final RecipientId recipientId
;
694 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
695 } catch (UnregisteredRecipientException e
) {
698 final var serviceId
= context
.getAccount()
699 .getRecipientAddressResolver()
700 .resolveRecipientAddress(recipientId
)
702 account
.getAciSessionStore().deleteAllSessions(serviceId
);
708 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
709 account
.removeRecipient(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
713 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
714 account
.getContactStore()
715 .deleteContact(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
719 public void setContactName(
720 RecipientIdentifier
.Single recipient
, String givenName
, final String familyName
721 ) throws NotPrimaryDeviceException
, UnregisteredRecipientException
{
722 if (!account
.isPrimaryDevice()) {
723 throw new NotPrimaryDeviceException();
725 context
.getContactHelper()
726 .setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), givenName
, familyName
);
730 public void setContactsBlocked(
731 Collection
<RecipientIdentifier
.Single
> recipients
, boolean blocked
732 ) throws NotPrimaryDeviceException
, IOException
, UnregisteredRecipientException
{
733 if (!account
.isPrimaryDevice()) {
734 throw new NotPrimaryDeviceException();
736 if (recipients
.size() == 0) {
739 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
740 final var selfRecipientId
= account
.getSelfRecipientId();
741 boolean shouldRotateProfileKey
= false;
742 for (final var recipientId
: recipientIds
) {
743 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
746 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
747 // if we don't have a common group with the blocked contact we need to rotate the profile key
748 shouldRotateProfileKey
= blocked
&& (
749 shouldRotateProfileKey
|| account
.getGroupStore()
752 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
755 if (shouldRotateProfileKey
) {
756 context
.getProfileHelper().rotateProfileKey();
758 context
.getSyncHelper().sendBlockedList();
762 public void setGroupsBlocked(
763 final Collection
<GroupId
> groupIds
, final boolean blocked
764 ) throws GroupNotFoundException
, NotPrimaryDeviceException
, IOException
{
765 if (!account
.isPrimaryDevice()) {
766 throw new NotPrimaryDeviceException();
768 if (groupIds
.size() == 0) {
771 boolean shouldRotateProfileKey
= false;
772 for (final var groupId
: groupIds
) {
773 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
776 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
777 shouldRotateProfileKey
= blocked
;
779 if (shouldRotateProfileKey
) {
780 context
.getProfileHelper().rotateProfileKey();
782 context
.getSyncHelper().sendBlockedList();
786 public void setExpirationTimer(
787 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
788 ) throws IOException
, UnregisteredRecipientException
{
789 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
790 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
791 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
793 sendMessage(messageBuilder
, Set
.of(recipient
));
794 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
795 throw new AssertionError(e
);
800 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
801 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
803 var messageSender
= dependencies
.getMessageSender();
805 var packKey
= KeyUtils
.createStickerUploadKey();
806 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
807 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
809 var sticker
= new StickerPack(packId
, packKey
);
810 account
.getStickerStore().addStickerPack(sticker
);
812 return new StickerPackUrl(packId
, packKey
);
816 public List
<org
.asamk
.signal
.manager
.api
.StickerPack
> getStickerPacks() {
817 final var stickerPackStore
= context
.getStickerPackStore();
818 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
819 if (stickerPackStore
.existsStickerPack(pack
.packId())) {
821 final var manifest
= stickerPackStore
.retrieveManifest(pack
.packId());
822 return new org
.asamk
.signal
.manager
.api
.StickerPack(pack
.packId(),
823 new StickerPackUrl(pack
.packId(), pack
.packKey()),
827 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
828 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
829 } catch (Exception e
) {
830 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
834 return new org
.asamk
.signal
.manager
.api
.StickerPack(pack
.packId(), pack
.packKey(), pack
.isInstalled());
839 public void requestAllSyncData() throws IOException
{
840 context
.getSyncHelper().requestAllSyncData();
841 retrieveRemoteStorage();
844 void retrieveRemoteStorage() throws IOException
{
845 context
.getStorageHelper().readDataFromStorage();
849 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
850 if (isReceivingSynchronous
) {
851 throw new IllegalStateException("Already receiving message synchronously.");
853 synchronized (messageHandlers
) {
854 if (isWeakListener
) {
855 weakHandlers
.add(handler
);
857 messageHandlers
.add(handler
);
858 startReceiveThreadIfRequired();
863 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
865 private void startReceiveThreadIfRequired() {
866 if (receiveThread
!= null) {
869 receiveThread
= new Thread(() -> {
870 logger
.debug("Starting receiving messages");
871 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
872 synchronized (messageHandlers
) {
873 final var handlers
= Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).toList();
874 handlers
.forEach(h
-> {
876 h
.handleMessage(envelope
, e
);
877 } catch (Throwable ex
) {
878 logger
.warn("Message handler failed, ignoring", ex
);
883 logger
.debug("Finished receiving messages");
884 synchronized (messageHandlers
) {
885 receiveThread
= null;
887 // Check if in the meantime another handler has been registered
888 if (!messageHandlers
.isEmpty()) {
889 logger
.debug("Another handler has been registered, starting receive thread again");
890 startReceiveThreadIfRequired();
894 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
896 receiveThread
.start();
900 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
902 synchronized (messageHandlers
) {
903 weakHandlers
.remove(handler
);
904 messageHandlers
.remove(handler
);
905 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
908 thread
= receiveThread
;
909 receiveThread
= null;
912 stopReceiveThread(thread
);
915 private void stopReceiveThread(final Thread thread
) {
916 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
917 logger
.debug("Receive stop requested, interrupting read from server.");
922 } catch (InterruptedException ignored
) {
927 public boolean isReceiving() {
928 if (isReceivingSynchronous
) {
931 synchronized (messageHandlers
) {
932 return messageHandlers
.size() > 0;
937 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
938 receiveMessages(timeout
, true, handler
);
942 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
943 receiveMessages(Duration
.ofMinutes(1), false, handler
);
946 private void receiveMessages(
947 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
948 ) throws IOException
{
950 throw new IllegalStateException("Already receiving message.");
952 isReceivingSynchronous
= true;
953 receiveThread
= Thread
.currentThread();
955 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
957 receiveThread
= null;
958 isReceivingSynchronous
= false;
963 public void setReceiveConfig(final ReceiveConfig receiveConfig
) {
964 context
.getReceiveHelper().setReceiveConfig(receiveConfig
);
968 public boolean hasCaughtUpWithOldMessages() {
969 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
973 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
974 final RecipientId recipientId
;
976 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
977 } catch (UnregisteredRecipientException e
) {
980 return context
.getContactHelper().isContactBlocked(recipientId
);
984 public void sendContacts() throws IOException
{
985 context
.getSyncHelper().sendContacts();
989 public List
<Recipient
> getRecipients(
990 boolean onlyContacts
,
991 Optional
<Boolean
> blocked
,
992 Collection
<RecipientIdentifier
.Single
> recipients
,
993 Optional
<String
> name
995 final var recipientIds
= recipients
.stream().map(a
-> {
997 return context
.getRecipientHelper().resolveRecipient(a
);
998 } catch (UnregisteredRecipientException e
) {
1001 }).filter(Objects
::nonNull
).collect(Collectors
.toSet());
1002 if (!recipients
.isEmpty() && recipientIds
.isEmpty()) {
1005 // refresh profiles of explicitly given recipients
1006 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
1007 return account
.getRecipientStore().getRecipients(onlyContacts
, blocked
, recipientIds
, name
);
1011 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1012 final RecipientId recipientId
;
1014 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1015 } catch (UnregisteredRecipientException e
) {
1019 final var contact
= account
.getContactStore().getContact(recipientId
);
1020 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1021 return contact
.getName();
1024 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
1025 if (profile
!= null) {
1026 return profile
.getDisplayName();
1033 public Group
getGroup(GroupId groupId
) {
1034 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1038 public List
<Identity
> getIdentities() {
1039 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1042 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1043 if (identityInfo
== null) {
1047 final var address
= account
.getRecipientAddressResolver()
1048 .resolveRecipientAddress(account
.getRecipientResolver().resolveRecipient(identityInfo
.getServiceId()));
1049 final var scannableFingerprint
= context
.getIdentityHelper()
1050 .computeSafetyNumberForScanning(identityInfo
.getServiceId(), identityInfo
.getIdentityKey());
1051 return new Identity(address
,
1052 identityInfo
.getIdentityKey(),
1053 context
.getIdentityHelper()
1054 .computeSafetyNumber(identityInfo
.getServiceId(), identityInfo
.getIdentityKey()),
1055 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1056 identityInfo
.getTrustLevel(),
1057 identityInfo
.getDateAddedTimestamp());
1061 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1062 ServiceId serviceId
;
1064 serviceId
= account
.getRecipientAddressResolver()
1065 .resolveRecipientAddress(context
.getRecipientHelper().resolveRecipient(recipient
))
1067 } catch (UnregisteredRecipientException e
) {
1070 final var identity
= account
.getIdentityKeyStore().getIdentityInfo(serviceId
);
1071 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1075 public boolean trustIdentityVerified(
1076 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1077 ) throws UnregisteredRecipientException
{
1078 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
1082 public boolean trustIdentityVerifiedSafetyNumber(
1083 RecipientIdentifier
.Single recipient
, String safetyNumber
1084 ) throws UnregisteredRecipientException
{
1085 return trustIdentity(recipient
,
1086 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1090 public boolean trustIdentityVerifiedSafetyNumber(
1091 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1092 ) throws UnregisteredRecipientException
{
1093 return trustIdentity(recipient
,
1094 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1098 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1099 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1102 private boolean trustIdentity(
1103 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1104 ) throws UnregisteredRecipientException
{
1105 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1106 final var updated
= trustMethod
.apply(recipientId
);
1107 if (updated
&& this.isReceiving()) {
1108 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1114 public void addAddressChangedListener(final Runnable listener
) {
1115 synchronized (addressChangedListeners
) {
1116 addressChangedListeners
.add(listener
);
1121 public void addClosedListener(final Runnable listener
) {
1122 synchronized (closedListeners
) {
1123 closedListeners
.add(listener
);
1128 public void close() {
1130 synchronized (messageHandlers
) {
1131 weakHandlers
.clear();
1132 messageHandlers
.clear();
1133 thread
= receiveThread
;
1134 receiveThread
= null;
1136 if (thread
!= null) {
1137 stopReceiveThread(thread
);
1139 executor
.shutdown();
1141 dependencies
.getSignalWebSocket().disconnect();
1142 disposable
.dispose();
1144 if (account
!= null) {
1148 synchronized (closedListeners
) {
1149 closedListeners
.forEach(Runnable
::run
);
1150 closedListeners
.clear();