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
.UserStatus
;
42 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
43 import org
.asamk
.signal
.manager
.groups
.GroupId
;
44 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
45 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
46 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
47 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
48 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
49 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
50 import org
.asamk
.signal
.manager
.helper
.Context
;
51 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
52 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
53 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.Recipient
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
57 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
58 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
59 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
60 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
61 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
62 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
63 import org
.slf4j
.Logger
;
64 import org
.slf4j
.LoggerFactory
;
65 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
66 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
69 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
70 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
71 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
72 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
73 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
74 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
77 import java
.io
.IOException
;
79 import java
.time
.Duration
;
80 import java
.util
.ArrayList
;
81 import java
.util
.Collection
;
82 import java
.util
.HashMap
;
83 import java
.util
.HashSet
;
84 import java
.util
.List
;
86 import java
.util
.Objects
;
87 import java
.util
.Optional
;
89 import java
.util
.concurrent
.ExecutorService
;
90 import java
.util
.concurrent
.Executors
;
91 import java
.util
.concurrent
.atomic
.AtomicInteger
;
92 import java
.util
.concurrent
.locks
.ReentrantLock
;
93 import java
.util
.function
.Function
;
94 import java
.util
.stream
.Collectors
;
95 import java
.util
.stream
.Stream
;
97 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
99 class ManagerImpl
implements Manager
{
101 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
103 private SignalAccount account
;
104 private final SignalDependencies dependencies
;
105 private final Context context
;
107 private final ExecutorService executor
= Executors
.newCachedThreadPool();
109 private Thread receiveThread
;
110 private boolean isReceivingSynchronous
;
111 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
112 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
113 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
114 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
115 private final CompositeDisposable disposable
= new CompositeDisposable();
118 SignalAccount account
,
119 PathConfig pathConfig
,
120 AccountFileUpdater accountFileUpdater
,
121 ServiceEnvironmentConfig serviceEnvironmentConfig
,
124 this.account
= account
;
126 final var sessionLock
= new SignalSessionLock() {
127 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
130 public Lock
acquire() {
132 return LEGACY_LOCK
::unlock
;
135 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
137 account
.getCredentialsProvider(),
138 account
.getSignalServiceDataStore(),
141 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
142 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
143 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
145 this.context
= new Context(account
, new AccountFileUpdater() {
147 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
148 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
149 synchronized (addressChangedListeners
) {
150 addressChangedListeners
.forEach(Runnable
::run
);
155 public void removeAccount() {
156 accountFileUpdater
.removeAccount();
158 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
159 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
160 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
161 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
162 synchronized (this) {
166 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
167 logger
.trace("Archiving old sessions for {}", recipientId
);
168 account
.getSessionStore().archiveSessions(recipientId
);
169 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
170 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
171 if (profile
!= null) {
172 account
.getRecipientStore()
173 .storeProfile(recipientId
,
174 Profile
.newBuilder(profile
)
175 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
176 .withLastUpdateTimestamp(0)
183 public String
getSelfNumber() {
184 return account
.getNumber();
187 void checkAccountState() throws IOException
{
188 context
.getAccountHelper().checkAccountState();
192 public Map
<String
, UserStatus
> getUserStatus(Set
<String
> numbers
) throws IOException
{
193 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
195 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
196 if (!canonicalizedNumber
.equals(n
)) {
197 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
199 return canonicalizedNumber
;
200 } catch (InvalidNumberException e
) {
205 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
206 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
208 .filter(s
-> !s
.isEmpty())
209 .collect(Collectors
.toSet());
210 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
212 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
213 final var number
= canonicalizedNumbers
.get(n
);
214 final var aci
= registeredUsers
.get(number
);
215 final var profile
= aci
== null
217 : context
.getProfileHelper().getRecipientProfile(account
.getRecipientStore().resolveRecipient(aci
));
218 return new UserStatus(number
.isEmpty() ?
null : number
,
219 aci
== null ?
null : aci
.uuid(),
221 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
226 public void updateAccountAttributes(String deviceName
) throws IOException
{
227 if (deviceName
!= null) {
228 context
.getAccountHelper().setDeviceName(deviceName
);
230 context
.getAccountHelper().updateAccountAttributes();
234 public Configuration
getConfiguration() {
235 final var configurationStore
= account
.getConfigurationStore();
236 return Configuration
.from(configurationStore
);
240 public void updateConfiguration(
241 Configuration configuration
242 ) throws NotMasterDeviceException
{
243 if (!account
.isMasterDevice()) {
244 throw new NotMasterDeviceException();
247 final var configurationStore
= account
.getConfigurationStore();
248 if (configuration
.readReceipts().isPresent()) {
249 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
251 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
252 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
254 if (configuration
.typingIndicators().isPresent()) {
255 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
257 if (configuration
.linkPreviews().isPresent()) {
258 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
260 context
.getSyncHelper().sendConfigurationMessage();
264 public void setProfile(
265 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
266 ) throws IOException
{
267 context
.getProfileHelper().setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
268 context
.getSyncHelper().sendSyncFetchProfileMessage();
272 public void unregister() throws IOException
{
273 context
.getAccountHelper().unregister();
277 public void deleteAccount() throws IOException
{
278 context
.getAccountHelper().deleteAccount();
282 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
283 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
285 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
289 public List
<Device
> getLinkedDevices() throws IOException
{
290 var devices
= dependencies
.getAccountManager().getDevices();
291 account
.setMultiDevice(devices
.size() > 1);
292 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
293 return devices
.stream().map(d
-> {
294 String deviceName
= d
.getName();
295 if (deviceName
!= null) {
297 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
298 } catch (IOException e
) {
299 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
302 return new Device(d
.getId(),
306 d
.getId() == account
.getDeviceId());
311 public void removeLinkedDevices(int deviceId
) throws IOException
{
312 context
.getAccountHelper().removeLinkedDevices(deviceId
);
316 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
317 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
318 context
.getAccountHelper().addDevice(deviceLinkInfo
);
322 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
323 if (!account
.isMasterDevice()) {
324 throw new NotMasterDeviceException();
326 if (pin
.isPresent()) {
327 context
.getAccountHelper().setRegistrationPin(pin
.get());
329 context
.getAccountHelper().removeRegistrationPin();
333 void refreshPreKeys() throws IOException
{
334 context
.getPreKeyHelper().refreshPreKeys();
338 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
339 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
343 public List
<Group
> getGroups() {
344 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
347 private Group
toGroup(final GroupInfo groupInfo
) {
348 if (groupInfo
== null) {
352 return Group
.from(groupInfo
,
353 account
.getRecipientStore()::resolveRecipientAddress
,
354 account
.getSelfRecipientId());
358 public SendGroupMessageResults
quitGroup(
359 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
360 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
361 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
362 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
366 public void deleteGroup(GroupId groupId
) throws IOException
{
367 final var group
= context
.getGroupHelper().getGroup(groupId
);
368 if (group
.isMember(account
.getSelfRecipientId())) {
369 throw new IOException(
370 "The local group information cannot be removed, as the user is still a member of the group");
372 context
.getGroupHelper().deleteGroup(groupId
);
376 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
377 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
378 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
379 return context
.getGroupHelper()
381 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
386 public SendGroupMessageResults
updateGroup(
387 final GroupId groupId
, final UpdateGroup updateGroup
388 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
389 return context
.getGroupHelper()
390 .updateGroup(groupId
,
391 updateGroup
.getName(),
392 updateGroup
.getDescription(),
393 updateGroup
.getMembers() == null
395 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
396 updateGroup
.getRemoveMembers() == null
398 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
399 updateGroup
.getAdmins() == null
401 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
402 updateGroup
.getRemoveAdmins() == null
404 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
405 updateGroup
.getBanMembers() == null
407 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
408 updateGroup
.getUnbanMembers() == null
410 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
411 updateGroup
.isResetGroupLink(),
412 updateGroup
.getGroupLinkState(),
413 updateGroup
.getAddMemberPermission(),
414 updateGroup
.getEditDetailsPermission(),
415 updateGroup
.getAvatarFile(),
416 updateGroup
.getExpirationTimer(),
417 updateGroup
.getIsAnnouncementGroup());
421 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
422 GroupInviteLinkUrl inviteLinkUrl
423 ) throws IOException
, InactiveGroupLinkException
{
424 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
427 private SendMessageResults
sendMessage(
428 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
429 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
430 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
431 long timestamp
= System
.currentTimeMillis();
432 messageBuilder
.withTimestamp(timestamp
);
433 for (final var recipient
: recipients
) {
434 if (recipient
instanceof RecipientIdentifier
.Single single
) {
436 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
437 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
438 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
439 } catch (UnregisteredRecipientException e
) {
440 results
.put(recipient
,
441 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
443 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
444 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
445 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
446 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
447 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
448 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
451 return new SendMessageResults(timestamp
, results
);
454 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
455 return SendMessageResult
.from(result
,
456 account
.getRecipientStore(),
457 account
.getRecipientStore()::resolveRecipientAddress
);
460 private SendMessageResults
sendTypingMessage(
461 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
462 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
463 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
464 final var timestamp
= System
.currentTimeMillis();
465 for (var recipient
: recipients
) {
466 if (recipient
instanceof RecipientIdentifier
.Single single
) {
467 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
469 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
470 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
471 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
472 } catch (UnregisteredRecipientException e
) {
473 results
.put(recipient
,
474 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
476 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
477 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
478 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
479 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
480 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
483 return new SendMessageResults(timestamp
, results
);
487 public SendMessageResults
sendTypingMessage(
488 TypingAction action
, Set
<RecipientIdentifier
> recipients
489 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
490 return sendTypingMessage(action
.toSignalService(), recipients
);
494 public SendMessageResults
sendReadReceipt(
495 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
497 final var timestamp
= System
.currentTimeMillis();
498 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
502 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
506 public SendMessageResults
sendViewedReceipt(
507 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
509 final var timestamp
= System
.currentTimeMillis();
510 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
514 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
517 private SendMessageResults
sendReceiptMessage(
518 final RecipientIdentifier
.Single sender
,
519 final long timestamp
,
520 final SignalServiceReceiptMessage receiptMessage
523 final var result
= context
.getSendHelper()
524 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
525 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
526 } catch (UnregisteredRecipientException e
) {
527 return new SendMessageResults(timestamp
,
528 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
533 public SendMessageResults
sendMessage(
534 Message message
, Set
<RecipientIdentifier
> recipients
535 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
536 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
537 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
539 "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.");
541 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
542 applyMessage(messageBuilder
, message
);
543 return sendMessage(messageBuilder
, recipients
);
546 private void applyMessage(
547 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
548 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
549 messageBuilder
.withBody(message
.messageText());
550 final var attachments
= message
.attachments();
551 if (attachments
!= null) {
552 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
554 if (message
.mentions().size() > 0) {
555 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
557 if (message
.quote().isPresent()) {
558 final var quote
= message
.quote().get();
559 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
560 context
.getRecipientHelper()
561 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
564 resolveMentions(quote
.mentions()),
565 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
567 if (message
.sticker().isPresent()) {
568 final var sticker
= message
.sticker().get();
569 final var packId
= StickerPackId
.deserialize(sticker
.packId());
570 final var stickerId
= sticker
.stickerId();
572 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
573 if (stickerPack
== null) {
574 throw new InvalidStickerException("Sticker pack not found");
576 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
577 if (manifest
.stickers().size() <= stickerId
) {
578 throw new InvalidStickerException("Sticker id not part of this pack");
580 final var manifestSticker
= manifest
.stickers().get(stickerId
);
581 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
582 if (streamDetails
== null) {
583 throw new InvalidStickerException("Missing local sticker file");
585 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
586 stickerPack
.getPackKey(),
588 manifestSticker
.emoji(),
589 AttachmentUtils
.createAttachment(streamDetails
, Optional
.empty())));
593 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
594 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
595 for (final var m
: mentionList
) {
596 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
597 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
598 .resolveSignalServiceAddress(recipientId
)
599 .getServiceId(), m
.start(), m
.length()));
605 public SendMessageResults
sendRemoteDeleteMessage(
606 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
607 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
608 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
609 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
610 for (final var recipient
: recipients
) {
611 if (recipient
instanceof RecipientIdentifier
.Single r
) {
613 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
614 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
615 } catch (UnregisteredRecipientException ignored
) {
617 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
618 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
621 return sendMessage(messageBuilder
, recipients
);
625 public SendMessageResults
sendMessageReaction(
628 RecipientIdentifier
.Single targetAuthor
,
629 long targetSentTimestamp
,
630 Set
<RecipientIdentifier
> recipients
631 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
632 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
633 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
635 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
636 targetSentTimestamp
);
637 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
638 return sendMessage(messageBuilder
, recipients
);
642 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
643 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
646 return sendMessage(messageBuilder
,
647 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
648 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
649 throw new AssertionError(e
);
651 for (var recipient
: recipients
) {
652 final RecipientId recipientId
;
654 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
655 } catch (UnregisteredRecipientException e
) {
658 account
.getSessionStore().deleteAllSessions(recipientId
);
664 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
665 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
669 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
670 account
.getContactStore()
671 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
675 public void setContactName(
676 RecipientIdentifier
.Single recipient
, String name
677 ) throws NotMasterDeviceException
, UnregisteredRecipientException
{
678 if (!account
.isMasterDevice()) {
679 throw new NotMasterDeviceException();
681 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
685 public void setContactsBlocked(
686 Collection
<RecipientIdentifier
.Single
> recipients
, boolean blocked
687 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
688 if (!account
.isMasterDevice()) {
689 throw new NotMasterDeviceException();
691 if (recipients
.size() == 0) {
694 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
695 final var selfRecipientId
= account
.getSelfRecipientId();
696 boolean shouldRotateProfileKey
= false;
697 for (final var recipientId
: recipientIds
) {
698 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
701 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
702 // if we don't have a common group with the blocked contact we need to rotate the profile key
703 shouldRotateProfileKey
= blocked
&& (
704 shouldRotateProfileKey
|| account
.getGroupStore()
707 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
710 if (shouldRotateProfileKey
) {
711 context
.getProfileHelper().rotateProfileKey();
713 context
.getSyncHelper().sendBlockedList();
717 public void setGroupsBlocked(
718 final Collection
<GroupId
> groupIds
, final boolean blocked
719 ) throws GroupNotFoundException
, NotMasterDeviceException
, IOException
{
720 if (!account
.isMasterDevice()) {
721 throw new NotMasterDeviceException();
723 if (groupIds
.size() == 0) {
726 boolean shouldRotateProfileKey
= false;
727 for (final var groupId
: groupIds
) {
728 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
731 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
732 shouldRotateProfileKey
= blocked
;
734 if (shouldRotateProfileKey
) {
735 context
.getProfileHelper().rotateProfileKey();
737 context
.getSyncHelper().sendBlockedList();
741 public void setExpirationTimer(
742 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
743 ) throws IOException
, UnregisteredRecipientException
{
744 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
745 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
746 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
748 sendMessage(messageBuilder
, Set
.of(recipient
));
749 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
750 throw new AssertionError(e
);
755 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
756 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
758 var messageSender
= dependencies
.getMessageSender();
760 var packKey
= KeyUtils
.createStickerUploadKey();
761 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
762 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
764 var sticker
= new Sticker(packId
, packKey
);
765 account
.getStickerStore().updateSticker(sticker
);
767 return new StickerPackUrl(packId
, packKey
);
771 public List
<StickerPack
> getStickerPacks() {
772 final var stickerPackStore
= context
.getStickerPackStore();
773 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
774 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
776 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
777 return new StickerPack(pack
.getPackId(),
778 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
782 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
783 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
784 } catch (Exception e
) {
785 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
789 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
794 public void requestAllSyncData() throws IOException
{
795 context
.getSyncHelper().requestAllSyncData();
796 retrieveRemoteStorage();
799 void retrieveRemoteStorage() throws IOException
{
800 if (account
.getStorageKey() != null) {
801 context
.getStorageHelper().readDataFromStorage();
806 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
807 if (isReceivingSynchronous
) {
808 throw new IllegalStateException("Already receiving message synchronously.");
810 synchronized (messageHandlers
) {
811 if (isWeakListener
) {
812 weakHandlers
.add(handler
);
814 messageHandlers
.add(handler
);
815 startReceiveThreadIfRequired();
820 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
822 private void startReceiveThreadIfRequired() {
823 if (receiveThread
!= null) {
826 receiveThread
= new Thread(() -> {
827 logger
.debug("Starting receiving messages");
828 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
829 synchronized (messageHandlers
) {
830 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
832 h
.handleMessage(envelope
, e
);
833 } catch (Throwable ex
) {
834 logger
.warn("Message handler failed, ignoring", ex
);
839 logger
.debug("Finished receiving messages");
840 synchronized (messageHandlers
) {
841 receiveThread
= null;
843 // Check if in the meantime another handler has been registered
844 if (!messageHandlers
.isEmpty()) {
845 logger
.debug("Another handler has been registered, starting receive thread again");
846 startReceiveThreadIfRequired();
850 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
852 receiveThread
.start();
856 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
858 synchronized (messageHandlers
) {
859 weakHandlers
.remove(handler
);
860 messageHandlers
.remove(handler
);
861 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
864 thread
= receiveThread
;
865 receiveThread
= null;
868 stopReceiveThread(thread
);
871 private void stopReceiveThread(final Thread thread
) {
872 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
873 logger
.debug("Receive stop requested, interrupting read from server.");
878 } catch (InterruptedException ignored
) {
883 public boolean isReceiving() {
884 if (isReceivingSynchronous
) {
887 synchronized (messageHandlers
) {
888 return messageHandlers
.size() > 0;
893 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
894 receiveMessages(timeout
, true, handler
);
898 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
899 receiveMessages(Duration
.ofMinutes(1), false, handler
);
902 private void receiveMessages(
903 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
904 ) throws IOException
{
906 throw new IllegalStateException("Already receiving message.");
908 isReceivingSynchronous
= true;
909 receiveThread
= Thread
.currentThread();
911 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
913 receiveThread
= null;
914 isReceivingSynchronous
= false;
919 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
920 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
924 public boolean hasCaughtUpWithOldMessages() {
925 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
929 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
930 final RecipientId recipientId
;
932 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
933 } catch (UnregisteredRecipientException e
) {
936 return context
.getContactHelper().isContactBlocked(recipientId
);
940 public void sendContacts() throws IOException
{
941 context
.getSyncHelper().sendContacts();
945 public List
<Recipient
> getRecipients(
946 boolean onlyContacts
,
947 Optional
<Boolean
> blocked
,
948 Collection
<RecipientIdentifier
.Single
> recipients
,
949 Optional
<String
> name
951 final var recipientIds
= recipients
.stream().map(a
-> {
953 return context
.getRecipientHelper().resolveRecipient(a
);
954 } catch (UnregisteredRecipientException e
) {
957 }).filter(Objects
::nonNull
).collect(Collectors
.toSet());
958 // refresh profiles of explicitly given recipients
959 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
960 return account
.getRecipientStore().getRecipients(onlyContacts
, blocked
, recipientIds
, name
);
964 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
965 final RecipientId recipientId
;
967 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
968 } catch (UnregisteredRecipientException e
) {
972 final var contact
= account
.getContactStore().getContact(recipientId
);
973 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
974 return contact
.getName();
977 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
978 if (profile
!= null) {
979 return profile
.getDisplayName();
986 public Group
getGroup(GroupId groupId
) {
987 return toGroup(context
.getGroupHelper().getGroup(groupId
));
991 public List
<Identity
> getIdentities() {
992 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
995 private Identity
toIdentity(final IdentityInfo identityInfo
) {
996 if (identityInfo
== null) {
1000 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1001 final var scannableFingerprint
= context
.getIdentityHelper()
1002 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
1003 return new Identity(address
,
1004 identityInfo
.getIdentityKey(),
1005 context
.getIdentityHelper()
1006 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1007 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1008 identityInfo
.getTrustLevel(),
1009 identityInfo
.getDateAdded());
1013 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1014 IdentityInfo identity
;
1016 identity
= account
.getIdentityKeyStore()
1017 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
1018 } catch (UnregisteredRecipientException e
) {
1021 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1025 public boolean trustIdentityVerified(
1026 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1027 ) throws UnregisteredRecipientException
{
1028 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
1032 public boolean trustIdentityVerifiedSafetyNumber(
1033 RecipientIdentifier
.Single recipient
, String safetyNumber
1034 ) throws UnregisteredRecipientException
{
1035 return trustIdentity(recipient
,
1036 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1040 public boolean trustIdentityVerifiedSafetyNumber(
1041 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1042 ) throws UnregisteredRecipientException
{
1043 return trustIdentity(recipient
,
1044 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1048 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1049 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1052 private boolean trustIdentity(
1053 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1054 ) throws UnregisteredRecipientException
{
1055 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1056 final var updated
= trustMethod
.apply(recipientId
);
1057 if (updated
&& this.isReceiving()) {
1058 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1064 public void addAddressChangedListener(final Runnable listener
) {
1065 synchronized (addressChangedListeners
) {
1066 addressChangedListeners
.add(listener
);
1071 public void addClosedListener(final Runnable listener
) {
1072 synchronized (closedListeners
) {
1073 closedListeners
.add(listener
);
1078 public void close() {
1080 synchronized (messageHandlers
) {
1081 weakHandlers
.clear();
1082 messageHandlers
.clear();
1083 thread
= receiveThread
;
1084 receiveThread
= null;
1086 if (thread
!= null) {
1087 stopReceiveThread(thread
);
1089 executor
.shutdown();
1091 dependencies
.getSignalWebSocket().disconnect();
1092 disposable
.dispose();
1094 if (account
!= null) {
1098 synchronized (closedListeners
) {
1099 closedListeners
.forEach(Runnable
::run
);
1100 closedListeners
.clear();