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
.Contact
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
57 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
58 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
59 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
60 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
61 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
62 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
63 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
64 import org
.slf4j
.Logger
;
65 import org
.slf4j
.LoggerFactory
;
66 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
70 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
71 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
72 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
73 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
74 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
75 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
78 import java
.io
.IOException
;
80 import java
.time
.Duration
;
81 import java
.util
.ArrayList
;
82 import java
.util
.HashMap
;
83 import java
.util
.HashSet
;
84 import java
.util
.List
;
86 import java
.util
.Optional
;
88 import java
.util
.concurrent
.ExecutorService
;
89 import java
.util
.concurrent
.Executors
;
90 import java
.util
.concurrent
.atomic
.AtomicInteger
;
91 import java
.util
.concurrent
.locks
.ReentrantLock
;
92 import java
.util
.function
.Function
;
93 import java
.util
.stream
.Collectors
;
94 import java
.util
.stream
.Stream
;
96 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
98 class ManagerImpl
implements Manager
{
100 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
102 private SignalAccount account
;
103 private AccountFileUpdater accountFileUpdater
;
104 private final SignalDependencies dependencies
;
105 private final Context context
;
107 private final ExecutorService executor
= Executors
.newCachedThreadPool();
109 private Thread receiveThread
;
110 private boolean isReceivingSynchronous
;
111 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
112 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
113 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
114 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
115 private final CompositeDisposable disposable
= new CompositeDisposable();
118 SignalAccount account
,
119 PathConfig pathConfig
,
120 AccountFileUpdater accountFileUpdater
,
121 ServiceEnvironmentConfig serviceEnvironmentConfig
,
124 this.account
= account
;
125 this.accountFileUpdater
= accountFileUpdater
;
127 final var sessionLock
= new SignalSessionLock() {
128 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
131 public Lock
acquire() {
133 return LEGACY_LOCK
::unlock
;
136 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
138 account
.getCredentialsProvider(),
139 account
.getSignalServiceDataStore(),
142 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
143 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
144 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
146 this.context
= new Context(account
, new AccountFileUpdater() {
148 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
149 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
150 synchronized (addressChangedListeners
) {
151 addressChangedListeners
.forEach(Runnable
::run
);
156 public void removeAccount() {
157 accountFileUpdater
.removeAccount();
159 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
160 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
161 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
162 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
163 synchronized (this) {
167 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
168 logger
.trace("Archiving old sessions for {}", recipientId
);
169 account
.getSessionStore().archiveSessions(recipientId
);
170 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
171 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
172 if (profile
!= null) {
173 account
.getRecipientStore()
174 .storeProfile(recipientId
,
175 Profile
.newBuilder(profile
)
176 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
177 .withLastUpdateTimestamp(0)
184 public String
getSelfNumber() {
185 return account
.getNumber();
188 void checkAccountState() throws IOException
{
189 context
.getAccountHelper().checkAccountState();
193 public Map
<String
, UserStatus
> getUserStatus(Set
<String
> numbers
) throws IOException
{
194 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
196 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
197 if (!canonicalizedNumber
.equals(n
)) {
198 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
200 return canonicalizedNumber
;
201 } catch (InvalidNumberException e
) {
206 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
207 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
209 .filter(s
-> !s
.isEmpty())
210 .collect(Collectors
.toSet());
211 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
213 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
214 final var number
= canonicalizedNumbers
.get(n
);
215 final var aci
= registeredUsers
.get(number
);
216 final var profile
= aci
== null
218 : context
.getProfileHelper().getRecipientProfile(account
.getRecipientStore().resolveRecipient(aci
));
219 return new UserStatus(number
.isEmpty() ?
null : number
,
220 aci
== null ?
null : aci
.uuid(),
222 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
227 public void updateAccountAttributes(String deviceName
) throws IOException
{
228 if (deviceName
!= null) {
229 context
.getAccountHelper().setDeviceName(deviceName
);
231 context
.getAccountHelper().updateAccountAttributes();
235 public Configuration
getConfiguration() {
236 final var configurationStore
= account
.getConfigurationStore();
237 return Configuration
.from(configurationStore
);
241 public void updateConfiguration(
242 Configuration configuration
243 ) throws NotMasterDeviceException
{
244 if (!account
.isMasterDevice()) {
245 throw new NotMasterDeviceException();
248 final var configurationStore
= account
.getConfigurationStore();
249 if (configuration
.readReceipts().isPresent()) {
250 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
252 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
253 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
255 if (configuration
.typingIndicators().isPresent()) {
256 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
258 if (configuration
.linkPreviews().isPresent()) {
259 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
261 context
.getSyncHelper().sendConfigurationMessage();
265 public void setProfile(
266 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
267 ) throws IOException
{
268 context
.getProfileHelper().setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
269 context
.getSyncHelper().sendSyncFetchProfileMessage();
273 public void unregister() throws IOException
{
274 context
.getAccountHelper().unregister();
278 public void deleteAccount() throws IOException
{
279 context
.getAccountHelper().deleteAccount();
283 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
284 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
286 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
290 public List
<Device
> getLinkedDevices() throws IOException
{
291 var devices
= dependencies
.getAccountManager().getDevices();
292 account
.setMultiDevice(devices
.size() > 1);
293 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
294 return devices
.stream().map(d
-> {
295 String deviceName
= d
.getName();
296 if (deviceName
!= null) {
298 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
299 } catch (IOException e
) {
300 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
303 return new Device(d
.getId(),
307 d
.getId() == account
.getDeviceId());
312 public void removeLinkedDevices(int deviceId
) throws IOException
{
313 context
.getAccountHelper().removeLinkedDevices(deviceId
);
317 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
318 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
319 context
.getAccountHelper().addDevice(deviceLinkInfo
);
323 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
324 if (!account
.isMasterDevice()) {
325 throw new NotMasterDeviceException();
327 if (pin
.isPresent()) {
328 context
.getAccountHelper().setRegistrationPin(pin
.get());
330 context
.getAccountHelper().removeRegistrationPin();
334 void refreshPreKeys() throws IOException
{
335 context
.getPreKeyHelper().refreshPreKeys();
339 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
340 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
344 public List
<Group
> getGroups() {
345 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
348 private Group
toGroup(final GroupInfo groupInfo
) {
349 if (groupInfo
== null) {
353 return Group
.from(groupInfo
,
354 account
.getRecipientStore()::resolveRecipientAddress
,
355 account
.getSelfRecipientId());
359 public SendGroupMessageResults
quitGroup(
360 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
361 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
362 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
363 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
367 public void deleteGroup(GroupId groupId
) throws IOException
{
368 final var group
= context
.getGroupHelper().getGroup(groupId
);
369 if (group
.isMember(account
.getSelfRecipientId())) {
370 throw new IOException(
371 "The local group information cannot be removed, as the user is still a member of the group");
373 context
.getGroupHelper().deleteGroup(groupId
);
377 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
378 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
379 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
380 return context
.getGroupHelper()
382 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
387 public SendGroupMessageResults
updateGroup(
388 final GroupId groupId
, final UpdateGroup updateGroup
389 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
390 return context
.getGroupHelper()
391 .updateGroup(groupId
,
392 updateGroup
.getName(),
393 updateGroup
.getDescription(),
394 updateGroup
.getMembers() == null
396 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
397 updateGroup
.getRemoveMembers() == null
399 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
400 updateGroup
.getAdmins() == null
402 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
403 updateGroup
.getRemoveAdmins() == null
405 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
406 updateGroup
.getBanMembers() == null
408 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
409 updateGroup
.getUnbanMembers() == null
411 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
412 updateGroup
.isResetGroupLink(),
413 updateGroup
.getGroupLinkState(),
414 updateGroup
.getAddMemberPermission(),
415 updateGroup
.getEditDetailsPermission(),
416 updateGroup
.getAvatarFile(),
417 updateGroup
.getExpirationTimer(),
418 updateGroup
.getIsAnnouncementGroup());
422 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
423 GroupInviteLinkUrl inviteLinkUrl
424 ) throws IOException
, InactiveGroupLinkException
{
425 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
428 private SendMessageResults
sendMessage(
429 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
430 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
431 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
432 long timestamp
= System
.currentTimeMillis();
433 messageBuilder
.withTimestamp(timestamp
);
434 for (final var recipient
: recipients
) {
435 if (recipient
instanceof RecipientIdentifier
.Single single
) {
437 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
438 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
439 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
440 } catch (UnregisteredRecipientException e
) {
441 results
.put(recipient
,
442 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
444 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
445 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
446 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
447 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
448 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
449 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
452 return new SendMessageResults(timestamp
, results
);
455 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
456 return SendMessageResult
.from(result
,
457 account
.getRecipientStore(),
458 account
.getRecipientStore()::resolveRecipientAddress
);
461 private SendMessageResults
sendTypingMessage(
462 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
463 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
464 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
465 final var timestamp
= System
.currentTimeMillis();
466 for (var recipient
: recipients
) {
467 if (recipient
instanceof RecipientIdentifier
.Single single
) {
468 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
470 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
471 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
472 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
473 } catch (UnregisteredRecipientException e
) {
474 results
.put(recipient
,
475 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
477 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
478 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
479 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
480 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
481 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
484 return new SendMessageResults(timestamp
, results
);
488 public SendMessageResults
sendTypingMessage(
489 TypingAction action
, Set
<RecipientIdentifier
> recipients
490 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
491 return sendTypingMessage(action
.toSignalService(), recipients
);
495 public SendMessageResults
sendReadReceipt(
496 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
497 ) throws IOException
{
498 final var timestamp
= System
.currentTimeMillis();
499 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
503 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
507 public SendMessageResults
sendViewedReceipt(
508 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
509 ) throws IOException
{
510 final var timestamp
= System
.currentTimeMillis();
511 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
515 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
518 private SendMessageResults
sendReceiptMessage(
519 final RecipientIdentifier
.Single sender
,
520 final long timestamp
,
521 final SignalServiceReceiptMessage receiptMessage
522 ) throws IOException
{
524 final var result
= context
.getSendHelper()
525 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
526 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
527 } catch (UnregisteredRecipientException e
) {
528 return new SendMessageResults(timestamp
,
529 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
534 public SendMessageResults
sendMessage(
535 Message message
, Set
<RecipientIdentifier
> recipients
536 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
537 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
538 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
540 "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.");
542 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
543 applyMessage(messageBuilder
, message
);
544 return sendMessage(messageBuilder
, recipients
);
547 private void applyMessage(
548 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
549 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
550 messageBuilder
.withBody(message
.messageText());
551 final var attachments
= message
.attachments();
552 if (attachments
!= null) {
553 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
555 if (message
.mentions().size() > 0) {
556 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
558 if (message
.quote().isPresent()) {
559 final var quote
= message
.quote().get();
560 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
561 context
.getRecipientHelper()
562 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
565 resolveMentions(quote
.mentions()),
566 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
568 if (message
.sticker().isPresent()) {
569 final var sticker
= message
.sticker().get();
570 final var packId
= StickerPackId
.deserialize(sticker
.packId());
571 final var stickerId
= sticker
.stickerId();
573 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
574 if (stickerPack
== null) {
575 throw new InvalidStickerException("Sticker pack not found");
577 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
578 if (manifest
.stickers().size() <= stickerId
) {
579 throw new InvalidStickerException("Sticker id not part of this pack");
581 final var manifestSticker
= manifest
.stickers().get(stickerId
);
582 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
583 if (streamDetails
== null) {
584 throw new InvalidStickerException("Missing local sticker file");
586 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
587 stickerPack
.getPackKey(),
589 manifestSticker
.emoji(),
590 AttachmentUtils
.createAttachment(streamDetails
, Optional
.empty())));
594 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
595 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
596 for (final var m
: mentionList
) {
597 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
598 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
599 .resolveSignalServiceAddress(recipientId
)
600 .getServiceId(), m
.start(), m
.length()));
606 public SendMessageResults
sendRemoteDeleteMessage(
607 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
608 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
609 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
610 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
611 for (final var recipient
: recipients
) {
612 if (recipient
instanceof RecipientIdentifier
.Single r
) {
614 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
615 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
616 } catch (UnregisteredRecipientException ignored
) {
618 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
619 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
622 return sendMessage(messageBuilder
, recipients
);
626 public SendMessageResults
sendMessageReaction(
629 RecipientIdentifier
.Single targetAuthor
,
630 long targetSentTimestamp
,
631 Set
<RecipientIdentifier
> recipients
632 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
633 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
634 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
636 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
637 targetSentTimestamp
);
638 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
639 return sendMessage(messageBuilder
, recipients
);
643 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
644 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
647 return sendMessage(messageBuilder
,
648 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
649 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
650 throw new AssertionError(e
);
652 for (var recipient
: recipients
) {
653 final RecipientId recipientId
;
655 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
656 } catch (UnregisteredRecipientException e
) {
659 account
.getSessionStore().deleteAllSessions(recipientId
);
665 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
666 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
670 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
671 account
.getContactStore()
672 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
676 public void setContactName(
677 RecipientIdentifier
.Single recipient
, String name
678 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
679 if (!account
.isMasterDevice()) {
680 throw new NotMasterDeviceException();
682 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
686 public void setContactBlocked(
687 RecipientIdentifier
.Single recipient
, boolean blocked
688 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
689 if (!account
.isMasterDevice()) {
690 throw new NotMasterDeviceException();
692 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
693 // TODO cycle our profile key, if we're not together in a group with recipient
694 context
.getSyncHelper().sendBlockedList();
698 public void setGroupBlocked(
699 final GroupId groupId
, final boolean blocked
700 ) throws GroupNotFoundException
, NotMasterDeviceException
{
701 if (!account
.isMasterDevice()) {
702 throw new NotMasterDeviceException();
704 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
705 // TODO cycle our profile key
706 context
.getSyncHelper().sendBlockedList();
710 public void setExpirationTimer(
711 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
712 ) throws IOException
, UnregisteredRecipientException
{
713 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
714 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
715 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
717 sendMessage(messageBuilder
, Set
.of(recipient
));
718 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
719 throw new AssertionError(e
);
724 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
725 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
727 var messageSender
= dependencies
.getMessageSender();
729 var packKey
= KeyUtils
.createStickerUploadKey();
730 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
731 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
733 var sticker
= new Sticker(packId
, packKey
);
734 account
.getStickerStore().updateSticker(sticker
);
736 return new StickerPackUrl(packId
, packKey
);
740 public List
<StickerPack
> getStickerPacks() {
741 final var stickerPackStore
= context
.getStickerPackStore();
742 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
743 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
745 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
746 return new StickerPack(pack
.getPackId(),
747 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
751 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
752 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
753 } catch (Exception e
) {
754 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
758 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
763 public void requestAllSyncData() throws IOException
{
764 context
.getSyncHelper().requestAllSyncData();
765 retrieveRemoteStorage();
768 void retrieveRemoteStorage() throws IOException
{
769 if (account
.getStorageKey() != null) {
770 context
.getStorageHelper().readDataFromStorage();
775 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
776 if (isReceivingSynchronous
) {
777 throw new IllegalStateException("Already receiving message synchronously.");
779 synchronized (messageHandlers
) {
780 if (isWeakListener
) {
781 weakHandlers
.add(handler
);
783 messageHandlers
.add(handler
);
784 startReceiveThreadIfRequired();
789 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
791 private void startReceiveThreadIfRequired() {
792 if (receiveThread
!= null) {
795 receiveThread
= new Thread(() -> {
796 logger
.debug("Starting receiving messages");
797 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
798 synchronized (messageHandlers
) {
799 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
801 h
.handleMessage(envelope
, e
);
802 } catch (Throwable ex
) {
803 logger
.warn("Message handler failed, ignoring", ex
);
808 logger
.debug("Finished receiving messages");
809 synchronized (messageHandlers
) {
810 receiveThread
= null;
812 // Check if in the meantime another handler has been registered
813 if (!messageHandlers
.isEmpty()) {
814 logger
.debug("Another handler has been registered, starting receive thread again");
815 startReceiveThreadIfRequired();
819 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
821 receiveThread
.start();
825 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
827 synchronized (messageHandlers
) {
828 weakHandlers
.remove(handler
);
829 messageHandlers
.remove(handler
);
830 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
833 thread
= receiveThread
;
834 receiveThread
= null;
837 stopReceiveThread(thread
);
840 private void stopReceiveThread(final Thread thread
) {
841 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
842 logger
.debug("Receive stop requested, interrupting read from server.");
847 } catch (InterruptedException ignored
) {
852 public boolean isReceiving() {
853 if (isReceivingSynchronous
) {
856 synchronized (messageHandlers
) {
857 return messageHandlers
.size() > 0;
862 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
863 receiveMessages(timeout
, true, handler
);
867 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
868 receiveMessages(Duration
.ofMinutes(1), false, handler
);
871 private void receiveMessages(
872 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
873 ) throws IOException
{
875 throw new IllegalStateException("Already receiving message.");
877 isReceivingSynchronous
= true;
878 receiveThread
= Thread
.currentThread();
880 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
882 receiveThread
= null;
883 isReceivingSynchronous
= false;
888 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
889 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
893 public boolean hasCaughtUpWithOldMessages() {
894 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
898 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
899 final RecipientId recipientId
;
901 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
902 } catch (IOException
| UnregisteredRecipientException e
) {
905 return context
.getContactHelper().isContactBlocked(recipientId
);
909 public void sendContacts() throws IOException
{
910 context
.getSyncHelper().sendContacts();
914 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
915 return account
.getContactStore()
918 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
923 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
924 final RecipientId recipientId
;
926 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
927 } catch (IOException
| UnregisteredRecipientException e
) {
931 final var contact
= account
.getContactStore().getContact(recipientId
);
932 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
933 return contact
.getName();
936 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
937 if (profile
!= null) {
938 return profile
.getDisplayName();
945 public Group
getGroup(GroupId groupId
) {
946 return toGroup(context
.getGroupHelper().getGroup(groupId
));
950 public List
<Identity
> getIdentities() {
951 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
954 private Identity
toIdentity(final IdentityInfo identityInfo
) {
955 if (identityInfo
== null) {
959 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
960 final var scannableFingerprint
= context
.getIdentityHelper()
961 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
962 return new Identity(address
,
963 identityInfo
.getIdentityKey(),
964 context
.getIdentityHelper()
965 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
966 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
967 identityInfo
.getTrustLevel(),
968 identityInfo
.getDateAdded());
972 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
973 IdentityInfo identity
;
975 identity
= account
.getIdentityKeyStore()
976 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
977 } catch (IOException
| UnregisteredRecipientException e
) {
980 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
984 public boolean trustIdentityVerified(
985 RecipientIdentifier
.Single recipient
, byte[] fingerprint
986 ) throws UnregisteredRecipientException
{
987 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
991 public boolean trustIdentityVerifiedSafetyNumber(
992 RecipientIdentifier
.Single recipient
, String safetyNumber
993 ) throws UnregisteredRecipientException
{
994 return trustIdentity(recipient
,
995 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
999 public boolean trustIdentityVerifiedSafetyNumber(
1000 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1001 ) throws UnregisteredRecipientException
{
1002 return trustIdentity(recipient
,
1003 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1007 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1008 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1011 private boolean trustIdentity(
1012 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1013 ) throws UnregisteredRecipientException
{
1014 RecipientId recipientId
;
1016 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1017 } catch (IOException e
) {
1020 final var updated
= trustMethod
.apply(recipientId
);
1021 if (updated
&& this.isReceiving()) {
1022 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1028 public void addAddressChangedListener(final Runnable listener
) {
1029 synchronized (addressChangedListeners
) {
1030 addressChangedListeners
.add(listener
);
1035 public void addClosedListener(final Runnable listener
) {
1036 synchronized (closedListeners
) {
1037 closedListeners
.add(listener
);
1042 public void close() {
1044 synchronized (messageHandlers
) {
1045 weakHandlers
.clear();
1046 messageHandlers
.clear();
1047 thread
= receiveThread
;
1048 receiveThread
= null;
1050 if (thread
!= null) {
1051 stopReceiveThread(thread
);
1053 executor
.shutdown();
1055 dependencies
.getSignalWebSocket().disconnect();
1056 disposable
.dispose();
1058 if (account
!= null) {
1062 synchronized (closedListeners
) {
1063 closedListeners
.forEach(Runnable
::run
);
1064 closedListeners
.clear();