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
.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
.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
.util
.DeviceNameUtil
;
73 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
74 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
75 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
76 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
79 import java
.io
.IOException
;
81 import java
.time
.Duration
;
82 import java
.util
.ArrayList
;
83 import java
.util
.Collection
;
84 import java
.util
.HashMap
;
85 import java
.util
.HashSet
;
86 import java
.util
.List
;
88 import java
.util
.Objects
;
89 import java
.util
.Optional
;
91 import java
.util
.concurrent
.ExecutorService
;
92 import java
.util
.concurrent
.Executors
;
93 import java
.util
.concurrent
.atomic
.AtomicInteger
;
94 import java
.util
.concurrent
.locks
.ReentrantLock
;
95 import java
.util
.function
.Function
;
96 import java
.util
.stream
.Collectors
;
97 import java
.util
.stream
.Stream
;
99 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
101 class ManagerImpl
implements Manager
{
103 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
105 private SignalAccount account
;
106 private final SignalDependencies dependencies
;
107 private final Context context
;
109 private final ExecutorService executor
= Executors
.newCachedThreadPool();
111 private Thread receiveThread
;
112 private boolean isReceivingSynchronous
;
113 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
114 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
115 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
116 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
117 private final CompositeDisposable disposable
= new CompositeDisposable();
120 SignalAccount account
,
121 PathConfig pathConfig
,
122 AccountFileUpdater accountFileUpdater
,
123 ServiceEnvironmentConfig serviceEnvironmentConfig
,
126 this.account
= account
;
128 final var sessionLock
= new SignalSessionLock() {
129 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
132 public Lock
acquire() {
134 return LEGACY_LOCK
::unlock
;
137 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
139 account
.getCredentialsProvider(),
140 account
.getSignalServiceDataStore(),
143 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
144 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
145 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
147 this.context
= new Context(account
, new AccountFileUpdater() {
149 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
150 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
151 synchronized (addressChangedListeners
) {
152 addressChangedListeners
.forEach(Runnable
::run
);
157 public void removeAccount() {
158 accountFileUpdater
.removeAccount();
160 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
161 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
162 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
163 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
164 synchronized (this) {
168 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
169 logger
.trace("Archiving old sessions for {}", recipientId
);
170 account
.getSessionStore().archiveSessions(recipientId
);
171 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
172 final var profile
= account
.getProfileStore().getProfile(recipientId
);
173 if (profile
!= null) {
174 account
.getProfileStore()
175 .storeProfile(recipientId
,
176 Profile
.newBuilder(profile
)
177 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
178 .withLastUpdateTimestamp(0)
185 public String
getSelfNumber() {
186 return account
.getNumber();
189 void checkAccountState() throws IOException
{
190 context
.getAccountHelper().checkAccountState();
194 public Map
<String
, UserStatus
> getUserStatus(Set
<String
> numbers
) throws IOException
{
195 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
197 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
198 if (!canonicalizedNumber
.equals(n
)) {
199 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
201 return canonicalizedNumber
;
202 } catch (InvalidNumberException e
) {
207 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
208 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
210 .filter(s
-> !s
.isEmpty())
211 .collect(Collectors
.toSet());
212 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
214 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
215 final var number
= canonicalizedNumbers
.get(n
);
216 final var aci
= registeredUsers
.get(number
);
217 final var profile
= aci
== null
219 : context
.getProfileHelper()
220 .getRecipientProfile(account
.getRecipientResolver().resolveRecipient(aci
));
221 return new UserStatus(number
.isEmpty() ?
null : number
,
222 aci
== null ?
null : aci
.uuid(),
224 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
229 public void updateAccountAttributes(String deviceName
) throws IOException
{
230 if (deviceName
!= null) {
231 context
.getAccountHelper().setDeviceName(deviceName
);
233 context
.getAccountHelper().updateAccountAttributes();
237 public Configuration
getConfiguration() {
238 final var configurationStore
= account
.getConfigurationStore();
239 return Configuration
.from(configurationStore
);
243 public void updateConfiguration(
244 Configuration configuration
245 ) throws NotPrimaryDeviceException
{
246 if (!account
.isPrimaryDevice()) {
247 throw new NotPrimaryDeviceException();
250 final var configurationStore
= account
.getConfigurationStore();
251 if (configuration
.readReceipts().isPresent()) {
252 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
254 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
255 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
257 if (configuration
.typingIndicators().isPresent()) {
258 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
260 if (configuration
.linkPreviews().isPresent()) {
261 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
263 context
.getSyncHelper().sendConfigurationMessage();
267 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
268 context
.getProfileHelper()
269 .setProfile(updateProfile
.getGivenName(),
270 updateProfile
.getFamilyName(),
271 updateProfile
.getAbout(),
272 updateProfile
.getAboutEmoji(),
273 updateProfile
.isDeleteAvatar()
275 : updateProfile
.getAvatar() == null ?
null : Optional
.of(updateProfile
.getAvatar()),
276 updateProfile
.getMobileCoinAddress());
277 context
.getSyncHelper().sendSyncFetchProfileMessage();
281 public void unregister() throws IOException
{
282 context
.getAccountHelper().unregister();
286 public void deleteAccount() throws IOException
{
287 context
.getAccountHelper().deleteAccount();
291 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
292 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
294 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
298 public List
<Device
> getLinkedDevices() throws IOException
{
299 var devices
= dependencies
.getAccountManager().getDevices();
300 account
.setMultiDevice(devices
.size() > 1);
301 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
302 return devices
.stream().map(d
-> {
303 String deviceName
= d
.getName();
304 if (deviceName
!= null) {
306 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
307 } catch (IOException e
) {
308 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
311 return new Device(d
.getId(),
315 d
.getId() == account
.getDeviceId());
320 public void removeLinkedDevices(int deviceId
) throws IOException
{
321 context
.getAccountHelper().removeLinkedDevices(deviceId
);
325 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
326 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
327 context
.getAccountHelper().addDevice(deviceLinkInfo
);
331 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotPrimaryDeviceException
{
332 if (!account
.isPrimaryDevice()) {
333 throw new NotPrimaryDeviceException();
335 if (pin
.isPresent()) {
336 context
.getAccountHelper().setRegistrationPin(pin
.get());
338 context
.getAccountHelper().removeRegistrationPin();
342 void refreshPreKeys() throws IOException
{
343 context
.getPreKeyHelper().refreshPreKeys();
347 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
348 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
352 public List
<Group
> getGroups() {
353 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
356 private Group
toGroup(final GroupInfo groupInfo
) {
357 if (groupInfo
== null) {
361 return Group
.from(groupInfo
, account
.getRecipientAddressResolver(), account
.getSelfRecipientId());
365 public SendGroupMessageResults
quitGroup(
366 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
367 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
368 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
369 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
373 public void deleteGroup(GroupId groupId
) throws IOException
{
374 final var group
= context
.getGroupHelper().getGroup(groupId
);
375 if (group
.isMember(account
.getSelfRecipientId())) {
376 throw new IOException(
377 "The local group information cannot be removed, as the user is still a member of the group");
379 context
.getGroupHelper().deleteGroup(groupId
);
383 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
384 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
385 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
386 return context
.getGroupHelper()
388 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
393 public SendGroupMessageResults
updateGroup(
394 final GroupId groupId
, final UpdateGroup updateGroup
395 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
396 return context
.getGroupHelper()
397 .updateGroup(groupId
,
398 updateGroup
.getName(),
399 updateGroup
.getDescription(),
400 updateGroup
.getMembers() == null
402 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
403 updateGroup
.getRemoveMembers() == null
405 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
406 updateGroup
.getAdmins() == null
408 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
409 updateGroup
.getRemoveAdmins() == null
411 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
412 updateGroup
.getBanMembers() == null
414 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
415 updateGroup
.getUnbanMembers() == null
417 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
418 updateGroup
.isResetGroupLink(),
419 updateGroup
.getGroupLinkState(),
420 updateGroup
.getAddMemberPermission(),
421 updateGroup
.getEditDetailsPermission(),
422 updateGroup
.getAvatarFile(),
423 updateGroup
.getExpirationTimer(),
424 updateGroup
.getIsAnnouncementGroup());
428 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
429 GroupInviteLinkUrl inviteLinkUrl
430 ) throws IOException
, InactiveGroupLinkException
{
431 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
434 private SendMessageResults
sendMessage(
435 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
436 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
437 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
438 long timestamp
= System
.currentTimeMillis();
439 messageBuilder
.withTimestamp(timestamp
);
440 for (final var recipient
: recipients
) {
441 if (recipient
instanceof RecipientIdentifier
.Single single
) {
443 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
444 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
445 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
446 } catch (UnregisteredRecipientException e
) {
447 results
.put(recipient
,
448 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
450 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
451 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
452 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
453 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
454 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
455 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
458 return new SendMessageResults(timestamp
, results
);
461 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
462 return SendMessageResult
.from(result
, account
.getRecipientResolver(), account
.getRecipientAddressResolver());
465 private SendMessageResults
sendTypingMessage(
466 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
467 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
468 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
469 final var timestamp
= System
.currentTimeMillis();
470 for (var recipient
: recipients
) {
471 if (recipient
instanceof RecipientIdentifier
.Single single
) {
472 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
474 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
475 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
476 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
477 } catch (UnregisteredRecipientException e
) {
478 results
.put(recipient
,
479 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
481 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
482 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
483 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
484 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
485 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
488 return new SendMessageResults(timestamp
, results
);
492 public SendMessageResults
sendTypingMessage(
493 TypingAction action
, Set
<RecipientIdentifier
> recipients
494 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
495 return sendTypingMessage(action
.toSignalService(), recipients
);
499 public SendMessageResults
sendReadReceipt(
500 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
502 final var timestamp
= System
.currentTimeMillis();
503 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
507 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
511 public SendMessageResults
sendViewedReceipt(
512 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
514 final var timestamp
= System
.currentTimeMillis();
515 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
519 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
522 private SendMessageResults
sendReceiptMessage(
523 final RecipientIdentifier
.Single sender
,
524 final long timestamp
,
525 final SignalServiceReceiptMessage receiptMessage
528 final var result
= context
.getSendHelper()
529 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
530 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
531 } catch (UnregisteredRecipientException e
) {
532 return new SendMessageResults(timestamp
,
533 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
538 public SendMessageResults
sendMessage(
539 Message message
, Set
<RecipientIdentifier
> recipients
540 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
541 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
542 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
544 "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.");
546 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
547 applyMessage(messageBuilder
, message
);
548 return sendMessage(messageBuilder
, recipients
);
551 private void applyMessage(
552 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
553 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
554 messageBuilder
.withBody(message
.messageText());
555 if (message
.attachments().size() > 0) {
556 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(message
.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
.createAttachmentStream(streamDetails
, Optional
.empty())));
595 if (message
.previews().size() > 0) {
596 final var previews
= new ArrayList
<SignalServicePreview
>(message
.previews().size());
597 for (final var p
: message
.previews()) {
598 final var image
= p
.image().isPresent() ? context
.getAttachmentHelper()
599 .uploadAttachment(p
.image().get()) : null;
600 previews
.add(new SignalServicePreview(p
.url(),
604 Optional
.ofNullable(image
)));
606 messageBuilder
.withPreviews(previews
);
610 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
611 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
612 for (final var m
: mentionList
) {
613 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
614 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
615 .resolveSignalServiceAddress(recipientId
)
616 .getServiceId(), m
.start(), m
.length()));
622 public SendMessageResults
sendRemoteDeleteMessage(
623 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
624 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
625 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
626 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
627 for (final var recipient
: recipients
) {
628 if (recipient
instanceof RecipientIdentifier
.Single r
) {
630 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
631 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
632 } catch (UnregisteredRecipientException ignored
) {
634 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
635 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
638 return sendMessage(messageBuilder
, recipients
);
642 public SendMessageResults
sendMessageReaction(
645 RecipientIdentifier
.Single targetAuthor
,
646 long targetSentTimestamp
,
647 Set
<RecipientIdentifier
> recipients
648 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
649 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
650 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
652 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
653 targetSentTimestamp
);
654 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
655 return sendMessage(messageBuilder
, recipients
);
659 public SendMessageResults
sendPaymentNotificationMessage(
660 byte[] receipt
, String note
, RecipientIdentifier
.Single recipient
661 ) throws IOException
{
662 final var paymentNotification
= new SignalServiceDataMessage
.PaymentNotification(receipt
, note
);
663 final var payment
= new SignalServiceDataMessage
.Payment(paymentNotification
);
664 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withPayment(payment
);
666 return sendMessage(messageBuilder
, Set
.of(recipient
));
667 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
668 throw new AssertionError(e
);
673 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
674 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
677 return sendMessage(messageBuilder
,
678 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
679 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
680 throw new AssertionError(e
);
682 for (var recipient
: recipients
) {
683 final RecipientId recipientId
;
685 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
686 } catch (UnregisteredRecipientException e
) {
689 account
.getSessionStore().deleteAllSessions(recipientId
);
695 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
696 account
.removeRecipient(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
700 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
701 account
.getContactStore()
702 .deleteContact(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
706 public void setContactName(
707 RecipientIdentifier
.Single recipient
, String name
708 ) throws NotPrimaryDeviceException
, UnregisteredRecipientException
{
709 if (!account
.isPrimaryDevice()) {
710 throw new NotPrimaryDeviceException();
712 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
716 public void setContactsBlocked(
717 Collection
<RecipientIdentifier
.Single
> recipients
, boolean blocked
718 ) throws NotPrimaryDeviceException
, IOException
, UnregisteredRecipientException
{
719 if (!account
.isPrimaryDevice()) {
720 throw new NotPrimaryDeviceException();
722 if (recipients
.size() == 0) {
725 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
726 final var selfRecipientId
= account
.getSelfRecipientId();
727 boolean shouldRotateProfileKey
= false;
728 for (final var recipientId
: recipientIds
) {
729 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
732 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
733 // if we don't have a common group with the blocked contact we need to rotate the profile key
734 shouldRotateProfileKey
= blocked
&& (
735 shouldRotateProfileKey
|| account
.getGroupStore()
738 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
741 if (shouldRotateProfileKey
) {
742 context
.getProfileHelper().rotateProfileKey();
744 context
.getSyncHelper().sendBlockedList();
748 public void setGroupsBlocked(
749 final Collection
<GroupId
> groupIds
, final boolean blocked
750 ) throws GroupNotFoundException
, NotPrimaryDeviceException
, IOException
{
751 if (!account
.isPrimaryDevice()) {
752 throw new NotPrimaryDeviceException();
754 if (groupIds
.size() == 0) {
757 boolean shouldRotateProfileKey
= false;
758 for (final var groupId
: groupIds
) {
759 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
762 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
763 shouldRotateProfileKey
= blocked
;
765 if (shouldRotateProfileKey
) {
766 context
.getProfileHelper().rotateProfileKey();
768 context
.getSyncHelper().sendBlockedList();
772 public void setExpirationTimer(
773 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
774 ) throws IOException
, UnregisteredRecipientException
{
775 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
776 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
777 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
779 sendMessage(messageBuilder
, Set
.of(recipient
));
780 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
781 throw new AssertionError(e
);
786 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
787 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
789 var messageSender
= dependencies
.getMessageSender();
791 var packKey
= KeyUtils
.createStickerUploadKey();
792 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
793 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
795 var sticker
= new Sticker(packId
, packKey
);
796 account
.getStickerStore().updateSticker(sticker
);
798 return new StickerPackUrl(packId
, packKey
);
802 public List
<StickerPack
> getStickerPacks() {
803 final var stickerPackStore
= context
.getStickerPackStore();
804 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
805 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
807 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
808 return new StickerPack(pack
.getPackId(),
809 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
813 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
814 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
815 } catch (Exception e
) {
816 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
820 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
825 public void requestAllSyncData() throws IOException
{
826 context
.getSyncHelper().requestAllSyncData();
827 retrieveRemoteStorage();
830 void retrieveRemoteStorage() throws IOException
{
831 if (account
.getStorageKey() != null) {
832 context
.getStorageHelper().readDataFromStorage();
837 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
838 if (isReceivingSynchronous
) {
839 throw new IllegalStateException("Already receiving message synchronously.");
841 synchronized (messageHandlers
) {
842 if (isWeakListener
) {
843 weakHandlers
.add(handler
);
845 messageHandlers
.add(handler
);
846 startReceiveThreadIfRequired();
851 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
853 private void startReceiveThreadIfRequired() {
854 if (receiveThread
!= null) {
857 receiveThread
= new Thread(() -> {
858 logger
.debug("Starting receiving messages");
859 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
860 synchronized (messageHandlers
) {
861 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
863 h
.handleMessage(envelope
, e
);
864 } catch (Throwable ex
) {
865 logger
.warn("Message handler failed, ignoring", ex
);
870 logger
.debug("Finished receiving messages");
871 synchronized (messageHandlers
) {
872 receiveThread
= null;
874 // Check if in the meantime another handler has been registered
875 if (!messageHandlers
.isEmpty()) {
876 logger
.debug("Another handler has been registered, starting receive thread again");
877 startReceiveThreadIfRequired();
881 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
883 receiveThread
.start();
887 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
889 synchronized (messageHandlers
) {
890 weakHandlers
.remove(handler
);
891 messageHandlers
.remove(handler
);
892 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
895 thread
= receiveThread
;
896 receiveThread
= null;
899 stopReceiveThread(thread
);
902 private void stopReceiveThread(final Thread thread
) {
903 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
904 logger
.debug("Receive stop requested, interrupting read from server.");
909 } catch (InterruptedException ignored
) {
914 public boolean isReceiving() {
915 if (isReceivingSynchronous
) {
918 synchronized (messageHandlers
) {
919 return messageHandlers
.size() > 0;
924 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
925 receiveMessages(timeout
, true, handler
);
929 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
930 receiveMessages(Duration
.ofMinutes(1), false, handler
);
933 private void receiveMessages(
934 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
935 ) throws IOException
{
937 throw new IllegalStateException("Already receiving message.");
939 isReceivingSynchronous
= true;
940 receiveThread
= Thread
.currentThread();
942 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
944 receiveThread
= null;
945 isReceivingSynchronous
= false;
950 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
951 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
955 public boolean hasCaughtUpWithOldMessages() {
956 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
960 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
961 final RecipientId recipientId
;
963 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
964 } catch (UnregisteredRecipientException e
) {
967 return context
.getContactHelper().isContactBlocked(recipientId
);
971 public void sendContacts() throws IOException
{
972 context
.getSyncHelper().sendContacts();
976 public List
<Recipient
> getRecipients(
977 boolean onlyContacts
,
978 Optional
<Boolean
> blocked
,
979 Collection
<RecipientIdentifier
.Single
> recipients
,
980 Optional
<String
> name
982 final var recipientIds
= recipients
.stream().map(a
-> {
984 return context
.getRecipientHelper().resolveRecipient(a
);
985 } catch (UnregisteredRecipientException e
) {
988 }).filter(Objects
::nonNull
).collect(Collectors
.toSet());
989 // refresh profiles of explicitly given recipients
990 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
991 return account
.getRecipientStore().getRecipients(onlyContacts
, blocked
, recipientIds
, name
);
995 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
996 final RecipientId recipientId
;
998 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
999 } catch (UnregisteredRecipientException e
) {
1003 final var contact
= account
.getContactStore().getContact(recipientId
);
1004 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1005 return contact
.getName();
1008 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
1009 if (profile
!= null) {
1010 return profile
.getDisplayName();
1017 public Group
getGroup(GroupId groupId
) {
1018 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1022 public List
<Identity
> getIdentities() {
1023 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1026 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1027 if (identityInfo
== null) {
1031 final var address
= account
.getRecipientAddressResolver()
1032 .resolveRecipientAddress(identityInfo
.getRecipientId());
1033 final var scannableFingerprint
= context
.getIdentityHelper()
1034 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
1035 return new Identity(address
,
1036 identityInfo
.getIdentityKey(),
1037 context
.getIdentityHelper()
1038 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1039 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1040 identityInfo
.getTrustLevel(),
1041 identityInfo
.getDateAdded());
1045 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1046 IdentityInfo identity
;
1048 identity
= account
.getIdentityKeyStore()
1049 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
1050 } catch (UnregisteredRecipientException e
) {
1053 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1057 public boolean trustIdentityVerified(
1058 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1059 ) throws UnregisteredRecipientException
{
1060 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
1064 public boolean trustIdentityVerifiedSafetyNumber(
1065 RecipientIdentifier
.Single recipient
, String safetyNumber
1066 ) throws UnregisteredRecipientException
{
1067 return trustIdentity(recipient
,
1068 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1072 public boolean trustIdentityVerifiedSafetyNumber(
1073 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1074 ) throws UnregisteredRecipientException
{
1075 return trustIdentity(recipient
,
1076 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1080 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1081 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1084 private boolean trustIdentity(
1085 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1086 ) throws UnregisteredRecipientException
{
1087 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1088 final var updated
= trustMethod
.apply(recipientId
);
1089 if (updated
&& this.isReceiving()) {
1090 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1096 public void addAddressChangedListener(final Runnable listener
) {
1097 synchronized (addressChangedListeners
) {
1098 addressChangedListeners
.add(listener
);
1103 public void addClosedListener(final Runnable listener
) {
1104 synchronized (closedListeners
) {
1105 closedListeners
.add(listener
);
1110 public void close() {
1112 synchronized (messageHandlers
) {
1113 weakHandlers
.clear();
1114 messageHandlers
.clear();
1115 thread
= receiveThread
;
1116 receiveThread
= null;
1118 if (thread
!= null) {
1119 stopReceiveThread(thread
);
1121 executor
.shutdown();
1123 dependencies
.getSignalWebSocket().disconnect();
1124 disposable
.dispose();
1126 if (account
!= null) {
1130 synchronized (closedListeners
) {
1131 closedListeners
.forEach(Runnable
::run
);
1132 closedListeners
.clear();