2 Copyright (C) 2015-2022 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
20 import org
.asamk
.signal
.manager
.api
.Configuration
;
21 import org
.asamk
.signal
.manager
.api
.Device
;
22 import org
.asamk
.signal
.manager
.api
.Group
;
23 import org
.asamk
.signal
.manager
.api
.Identity
;
24 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
25 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
26 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
27 import org
.asamk
.signal
.manager
.api
.Message
;
28 import org
.asamk
.signal
.manager
.api
.NotPrimaryDeviceException
;
29 import org
.asamk
.signal
.manager
.api
.Pair
;
30 import org
.asamk
.signal
.manager
.api
.ReceiveConfig
;
31 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
32 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
33 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
34 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
35 import org
.asamk
.signal
.manager
.api
.StickerPack
;
36 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
37 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
38 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
39 import org
.asamk
.signal
.manager
.api
.TypingAction
;
40 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
41 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
42 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
43 import org
.asamk
.signal
.manager
.api
.UserStatus
;
44 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
45 import org
.asamk
.signal
.manager
.groups
.GroupId
;
46 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
47 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
48 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
49 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
50 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
51 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
52 import org
.asamk
.signal
.manager
.helper
.Context
;
53 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
54 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
55 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
57 import org
.asamk
.signal
.manager
.storage
.recipients
.Recipient
;
58 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
59 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
60 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
61 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
62 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
63 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
64 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
65 import org
.slf4j
.Logger
;
66 import org
.slf4j
.LoggerFactory
;
67 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServicePreview
;
70 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
71 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
72 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
73 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
74 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
75 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
76 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
77 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
80 import java
.io
.IOException
;
82 import java
.time
.Duration
;
83 import java
.util
.ArrayList
;
84 import java
.util
.Collection
;
85 import java
.util
.HashMap
;
86 import java
.util
.HashSet
;
87 import java
.util
.List
;
89 import java
.util
.Objects
;
90 import java
.util
.Optional
;
92 import java
.util
.concurrent
.ExecutorService
;
93 import java
.util
.concurrent
.Executors
;
94 import java
.util
.concurrent
.atomic
.AtomicInteger
;
95 import java
.util
.concurrent
.locks
.ReentrantLock
;
96 import java
.util
.function
.Function
;
97 import java
.util
.stream
.Collectors
;
98 import java
.util
.stream
.Stream
;
100 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
102 class ManagerImpl
implements Manager
{
104 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
106 private SignalAccount account
;
107 private final SignalDependencies dependencies
;
108 private final Context context
;
110 private final ExecutorService executor
= Executors
.newCachedThreadPool();
112 private Thread receiveThread
;
113 private boolean isReceivingSynchronous
;
114 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
115 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
116 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
117 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
118 private final CompositeDisposable disposable
= new CompositeDisposable();
121 SignalAccount account
,
122 PathConfig pathConfig
,
123 AccountFileUpdater accountFileUpdater
,
124 ServiceEnvironmentConfig serviceEnvironmentConfig
,
127 this.account
= account
;
129 final var sessionLock
= new SignalSessionLock() {
130 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
133 public Lock
acquire() {
135 return LEGACY_LOCK
::unlock
;
138 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
140 account
.getCredentialsProvider(),
141 account
.getSignalServiceDataStore(),
144 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
145 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
146 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
148 this.context
= new Context(account
, new AccountFileUpdater() {
150 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
151 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
152 synchronized (addressChangedListeners
) {
153 addressChangedListeners
.forEach(Runnable
::run
);
158 public void removeAccount() {
159 accountFileUpdater
.removeAccount();
161 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
162 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
163 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
164 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
165 synchronized (this) {
169 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
170 logger
.trace("Archiving old sessions for {}", recipientId
);
171 account
.getSessionStore().archiveSessions(recipientId
);
172 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
173 final var profile
= account
.getProfileStore().getProfile(recipientId
);
174 if (profile
!= null) {
175 account
.getProfileStore()
176 .storeProfile(recipientId
,
177 Profile
.newBuilder(profile
)
178 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
179 .withLastUpdateTimestamp(0)
186 public String
getSelfNumber() {
187 return account
.getNumber();
190 void checkAccountState() throws IOException
{
191 context
.getAccountHelper().checkAccountState();
195 public Map
<String
, UserStatus
> getUserStatus(Set
<String
> numbers
) throws IOException
{
196 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
198 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
199 if (!canonicalizedNumber
.equals(n
)) {
200 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
202 return canonicalizedNumber
;
203 } catch (InvalidNumberException e
) {
208 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
209 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
211 .filter(s
-> !s
.isEmpty())
212 .collect(Collectors
.toSet());
213 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
215 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
216 final var number
= canonicalizedNumbers
.get(n
);
217 final var aci
= registeredUsers
.get(number
);
218 final var profile
= aci
== null
220 : context
.getProfileHelper()
221 .getRecipientProfile(account
.getRecipientResolver().resolveRecipient(aci
));
222 return new UserStatus(number
.isEmpty() ?
null : number
,
223 aci
== null ?
null : aci
.uuid(),
225 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
230 public void updateAccountAttributes(String deviceName
) throws IOException
{
231 if (deviceName
!= null) {
232 context
.getAccountHelper().setDeviceName(deviceName
);
234 context
.getAccountHelper().updateAccountAttributes();
238 public Configuration
getConfiguration() {
239 final var configurationStore
= account
.getConfigurationStore();
240 return Configuration
.from(configurationStore
);
244 public void updateConfiguration(
245 Configuration configuration
246 ) throws NotPrimaryDeviceException
{
247 if (!account
.isPrimaryDevice()) {
248 throw new NotPrimaryDeviceException();
251 final var configurationStore
= account
.getConfigurationStore();
252 if (configuration
.readReceipts().isPresent()) {
253 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
255 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
256 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
258 if (configuration
.typingIndicators().isPresent()) {
259 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
261 if (configuration
.linkPreviews().isPresent()) {
262 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
264 context
.getSyncHelper().sendConfigurationMessage();
268 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
269 context
.getProfileHelper()
270 .setProfile(updateProfile
.getGivenName(),
271 updateProfile
.getFamilyName(),
272 updateProfile
.getAbout(),
273 updateProfile
.getAboutEmoji(),
274 updateProfile
.isDeleteAvatar()
276 : updateProfile
.getAvatar() == null ?
null : Optional
.of(updateProfile
.getAvatar()),
277 updateProfile
.getMobileCoinAddress());
278 context
.getSyncHelper().sendSyncFetchProfileMessage();
282 public void unregister() throws IOException
{
283 context
.getAccountHelper().unregister();
287 public void deleteAccount() throws IOException
{
288 context
.getAccountHelper().deleteAccount();
292 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
293 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
295 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
299 public List
<Device
> getLinkedDevices() throws IOException
{
300 var devices
= dependencies
.getAccountManager().getDevices();
301 account
.setMultiDevice(devices
.size() > 1);
302 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
303 return devices
.stream().map(d
-> {
304 String deviceName
= d
.getName();
305 if (deviceName
!= null) {
307 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
308 } catch (IOException e
) {
309 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
312 return new Device(d
.getId(),
316 d
.getId() == account
.getDeviceId());
321 public void removeLinkedDevices(int deviceId
) throws IOException
{
322 context
.getAccountHelper().removeLinkedDevices(deviceId
);
326 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
327 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
328 context
.getAccountHelper().addDevice(deviceLinkInfo
);
332 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotPrimaryDeviceException
{
333 if (!account
.isPrimaryDevice()) {
334 throw new NotPrimaryDeviceException();
336 if (pin
.isPresent()) {
337 context
.getAccountHelper().setRegistrationPin(pin
.get());
339 context
.getAccountHelper().removeRegistrationPin();
343 void refreshPreKeys() throws IOException
{
344 context
.getPreKeyHelper().refreshPreKeys();
348 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
349 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
353 public List
<Group
> getGroups() {
354 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
357 private Group
toGroup(final GroupInfo groupInfo
) {
358 if (groupInfo
== null) {
362 return Group
.from(groupInfo
, account
.getRecipientAddressResolver(), account
.getSelfRecipientId());
366 public SendGroupMessageResults
quitGroup(
367 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
368 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
369 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
370 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
374 public void deleteGroup(GroupId groupId
) throws IOException
{
375 final var group
= context
.getGroupHelper().getGroup(groupId
);
376 if (group
.isMember(account
.getSelfRecipientId())) {
377 throw new IOException(
378 "The local group information cannot be removed, as the user is still a member of the group");
380 context
.getGroupHelper().deleteGroup(groupId
);
384 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
385 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
386 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
387 return context
.getGroupHelper()
389 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
394 public SendGroupMessageResults
updateGroup(
395 final GroupId groupId
, final UpdateGroup updateGroup
396 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
397 return context
.getGroupHelper()
398 .updateGroup(groupId
,
399 updateGroup
.getName(),
400 updateGroup
.getDescription(),
401 updateGroup
.getMembers() == null
403 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
404 updateGroup
.getRemoveMembers() == null
406 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
407 updateGroup
.getAdmins() == null
409 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
410 updateGroup
.getRemoveAdmins() == null
412 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
413 updateGroup
.getBanMembers() == null
415 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
416 updateGroup
.getUnbanMembers() == null
418 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
419 updateGroup
.isResetGroupLink(),
420 updateGroup
.getGroupLinkState(),
421 updateGroup
.getAddMemberPermission(),
422 updateGroup
.getEditDetailsPermission(),
423 updateGroup
.getAvatarFile(),
424 updateGroup
.getExpirationTimer(),
425 updateGroup
.getIsAnnouncementGroup());
429 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
430 GroupInviteLinkUrl inviteLinkUrl
431 ) throws IOException
, InactiveGroupLinkException
{
432 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
435 private SendMessageResults
sendMessage(
436 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
437 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
438 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
439 long timestamp
= System
.currentTimeMillis();
440 messageBuilder
.withTimestamp(timestamp
);
441 for (final var recipient
: recipients
) {
442 if (recipient
instanceof RecipientIdentifier
.Single single
) {
444 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
445 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
446 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
447 } catch (UnregisteredRecipientException e
) {
448 results
.put(recipient
,
449 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
451 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
452 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
453 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
454 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
455 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
456 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
459 return new SendMessageResults(timestamp
, results
);
462 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
463 return SendMessageResult
.from(result
, account
.getRecipientResolver(), account
.getRecipientAddressResolver());
466 private SendMessageResults
sendTypingMessage(
467 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
468 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
469 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
470 final var timestamp
= System
.currentTimeMillis();
471 for (var recipient
: recipients
) {
472 if (recipient
instanceof RecipientIdentifier
.Single single
) {
473 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
475 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
476 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
477 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
478 } catch (UnregisteredRecipientException e
) {
479 results
.put(recipient
,
480 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
482 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
483 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
484 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
485 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
486 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
489 return new SendMessageResults(timestamp
, results
);
493 public SendMessageResults
sendTypingMessage(
494 TypingAction action
, Set
<RecipientIdentifier
> recipients
495 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
496 return sendTypingMessage(action
.toSignalService(), recipients
);
500 public SendMessageResults
sendReadReceipt(
501 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
503 final var timestamp
= System
.currentTimeMillis();
504 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
508 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
512 public SendMessageResults
sendViewedReceipt(
513 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
515 final var timestamp
= System
.currentTimeMillis();
516 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
520 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
523 private SendMessageResults
sendReceiptMessage(
524 final RecipientIdentifier
.Single sender
,
525 final long timestamp
,
526 final SignalServiceReceiptMessage receiptMessage
529 final var result
= context
.getSendHelper()
530 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
531 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
532 } catch (UnregisteredRecipientException e
) {
533 return new SendMessageResults(timestamp
,
534 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
539 public SendMessageResults
sendMessage(
540 Message message
, Set
<RecipientIdentifier
> recipients
541 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
542 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
543 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
545 "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.");
547 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
548 applyMessage(messageBuilder
, message
);
549 return sendMessage(messageBuilder
, recipients
);
552 private void applyMessage(
553 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
554 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
555 messageBuilder
.withBody(message
.messageText());
556 if (message
.attachments().size() > 0) {
557 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(message
.attachments()));
559 if (message
.mentions().size() > 0) {
560 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
562 if (message
.quote().isPresent()) {
563 final var quote
= message
.quote().get();
564 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
565 context
.getRecipientHelper()
566 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
569 resolveMentions(quote
.mentions()),
570 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
572 if (message
.sticker().isPresent()) {
573 final var sticker
= message
.sticker().get();
574 final var packId
= StickerPackId
.deserialize(sticker
.packId());
575 final var stickerId
= sticker
.stickerId();
577 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
578 if (stickerPack
== null) {
579 throw new InvalidStickerException("Sticker pack not found");
581 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
582 if (manifest
.stickers().size() <= stickerId
) {
583 throw new InvalidStickerException("Sticker id not part of this pack");
585 final var manifestSticker
= manifest
.stickers().get(stickerId
);
586 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
587 if (streamDetails
== null) {
588 throw new InvalidStickerException("Missing local sticker file");
590 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
591 stickerPack
.getPackKey(),
593 manifestSticker
.emoji(),
594 AttachmentUtils
.createAttachmentStream(streamDetails
, Optional
.empty())));
596 if (message
.previews().size() > 0) {
597 final var previews
= new ArrayList
<SignalServicePreview
>(message
.previews().size());
598 for (final var p
: message
.previews()) {
599 final var image
= p
.image().isPresent() ? context
.getAttachmentHelper()
600 .uploadAttachment(p
.image().get()) : null;
601 previews
.add(new SignalServicePreview(p
.url(),
605 Optional
.ofNullable(image
)));
607 messageBuilder
.withPreviews(previews
);
611 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
612 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
613 for (final var m
: mentionList
) {
614 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
615 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
616 .resolveSignalServiceAddress(recipientId
)
617 .getServiceId(), m
.start(), m
.length()));
623 public SendMessageResults
sendRemoteDeleteMessage(
624 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
625 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
626 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
627 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
628 for (final var recipient
: recipients
) {
629 if (recipient
instanceof RecipientIdentifier
.Single r
) {
631 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
632 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
633 } catch (UnregisteredRecipientException ignored
) {
635 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
636 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
639 return sendMessage(messageBuilder
, recipients
);
643 public SendMessageResults
sendMessageReaction(
646 RecipientIdentifier
.Single targetAuthor
,
647 long targetSentTimestamp
,
648 Set
<RecipientIdentifier
> recipients
649 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
650 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
651 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
653 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
654 targetSentTimestamp
);
655 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
656 return sendMessage(messageBuilder
, recipients
);
660 public SendMessageResults
sendPaymentNotificationMessage(
661 byte[] receipt
, String note
, RecipientIdentifier
.Single recipient
662 ) throws IOException
{
663 final var paymentNotification
= new SignalServiceDataMessage
.PaymentNotification(receipt
, note
);
664 final var payment
= new SignalServiceDataMessage
.Payment(paymentNotification
);
665 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withPayment(payment
);
667 return sendMessage(messageBuilder
, Set
.of(recipient
));
668 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
669 throw new AssertionError(e
);
674 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
675 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
678 return sendMessage(messageBuilder
,
679 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
680 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
681 throw new AssertionError(e
);
683 for (var recipient
: recipients
) {
684 final RecipientId recipientId
;
686 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
687 } catch (UnregisteredRecipientException e
) {
690 account
.getSessionStore().deleteAllSessions(recipientId
);
696 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
697 account
.removeRecipient(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
701 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
702 account
.getContactStore()
703 .deleteContact(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
707 public void setContactName(
708 RecipientIdentifier
.Single recipient
, String givenName
, final String familyName
709 ) throws NotPrimaryDeviceException
, UnregisteredRecipientException
{
710 if (!account
.isPrimaryDevice()) {
711 throw new NotPrimaryDeviceException();
713 context
.getContactHelper()
714 .setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), givenName
, familyName
);
718 public void setContactsBlocked(
719 Collection
<RecipientIdentifier
.Single
> recipients
, boolean blocked
720 ) throws NotPrimaryDeviceException
, IOException
, UnregisteredRecipientException
{
721 if (!account
.isPrimaryDevice()) {
722 throw new NotPrimaryDeviceException();
724 if (recipients
.size() == 0) {
727 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
728 final var selfRecipientId
= account
.getSelfRecipientId();
729 boolean shouldRotateProfileKey
= false;
730 for (final var recipientId
: recipientIds
) {
731 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
734 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
735 // if we don't have a common group with the blocked contact we need to rotate the profile key
736 shouldRotateProfileKey
= blocked
&& (
737 shouldRotateProfileKey
|| account
.getGroupStore()
740 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
743 if (shouldRotateProfileKey
) {
744 context
.getProfileHelper().rotateProfileKey();
746 context
.getSyncHelper().sendBlockedList();
750 public void setGroupsBlocked(
751 final Collection
<GroupId
> groupIds
, final boolean blocked
752 ) throws GroupNotFoundException
, NotPrimaryDeviceException
, IOException
{
753 if (!account
.isPrimaryDevice()) {
754 throw new NotPrimaryDeviceException();
756 if (groupIds
.size() == 0) {
759 boolean shouldRotateProfileKey
= false;
760 for (final var groupId
: groupIds
) {
761 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
764 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
765 shouldRotateProfileKey
= blocked
;
767 if (shouldRotateProfileKey
) {
768 context
.getProfileHelper().rotateProfileKey();
770 context
.getSyncHelper().sendBlockedList();
774 public void setExpirationTimer(
775 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
776 ) throws IOException
, UnregisteredRecipientException
{
777 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
778 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
779 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
781 sendMessage(messageBuilder
, Set
.of(recipient
));
782 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
783 throw new AssertionError(e
);
788 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
789 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
791 var messageSender
= dependencies
.getMessageSender();
793 var packKey
= KeyUtils
.createStickerUploadKey();
794 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
795 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
797 var sticker
= new Sticker(packId
, packKey
);
798 account
.getStickerStore().updateSticker(sticker
);
800 return new StickerPackUrl(packId
, packKey
);
804 public List
<StickerPack
> getStickerPacks() {
805 final var stickerPackStore
= context
.getStickerPackStore();
806 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
807 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
809 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
810 return new StickerPack(pack
.getPackId(),
811 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
815 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
816 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
817 } catch (Exception e
) {
818 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
822 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
827 public void requestAllSyncData() throws IOException
{
828 context
.getSyncHelper().requestAllSyncData();
829 retrieveRemoteStorage();
832 void retrieveRemoteStorage() throws IOException
{
833 if (account
.getStorageKey() != null) {
834 context
.getStorageHelper().readDataFromStorage();
839 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
840 if (isReceivingSynchronous
) {
841 throw new IllegalStateException("Already receiving message synchronously.");
843 synchronized (messageHandlers
) {
844 if (isWeakListener
) {
845 weakHandlers
.add(handler
);
847 messageHandlers
.add(handler
);
848 startReceiveThreadIfRequired();
853 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
855 private void startReceiveThreadIfRequired() {
856 if (receiveThread
!= null) {
859 receiveThread
= new Thread(() -> {
860 logger
.debug("Starting receiving messages");
861 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
862 synchronized (messageHandlers
) {
863 final var handlers
= Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).toList();
864 handlers
.forEach(h
-> {
866 h
.handleMessage(envelope
, e
);
867 } catch (Throwable ex
) {
868 logger
.warn("Message handler failed, ignoring", ex
);
873 logger
.debug("Finished receiving messages");
874 synchronized (messageHandlers
) {
875 receiveThread
= null;
877 // Check if in the meantime another handler has been registered
878 if (!messageHandlers
.isEmpty()) {
879 logger
.debug("Another handler has been registered, starting receive thread again");
880 startReceiveThreadIfRequired();
884 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
886 receiveThread
.start();
890 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
892 synchronized (messageHandlers
) {
893 weakHandlers
.remove(handler
);
894 messageHandlers
.remove(handler
);
895 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
898 thread
= receiveThread
;
899 receiveThread
= null;
902 stopReceiveThread(thread
);
905 private void stopReceiveThread(final Thread thread
) {
906 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
907 logger
.debug("Receive stop requested, interrupting read from server.");
912 } catch (InterruptedException ignored
) {
917 public boolean isReceiving() {
918 if (isReceivingSynchronous
) {
921 synchronized (messageHandlers
) {
922 return messageHandlers
.size() > 0;
927 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
928 receiveMessages(timeout
, true, handler
);
932 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
933 receiveMessages(Duration
.ofMinutes(1), false, handler
);
936 private void receiveMessages(
937 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
938 ) throws IOException
{
940 throw new IllegalStateException("Already receiving message.");
942 isReceivingSynchronous
= true;
943 receiveThread
= Thread
.currentThread();
945 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
947 receiveThread
= null;
948 isReceivingSynchronous
= false;
953 public void setReceiveConfig(final ReceiveConfig receiveConfig
) {
954 context
.getReceiveHelper().setReceiveConfig(receiveConfig
);
958 public boolean hasCaughtUpWithOldMessages() {
959 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
963 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
964 final RecipientId recipientId
;
966 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
967 } catch (UnregisteredRecipientException e
) {
970 return context
.getContactHelper().isContactBlocked(recipientId
);
974 public void sendContacts() throws IOException
{
975 context
.getSyncHelper().sendContacts();
979 public List
<Recipient
> getRecipients(
980 boolean onlyContacts
,
981 Optional
<Boolean
> blocked
,
982 Collection
<RecipientIdentifier
.Single
> recipients
,
983 Optional
<String
> name
985 final var recipientIds
= recipients
.stream().map(a
-> {
987 return context
.getRecipientHelper().resolveRecipient(a
);
988 } catch (UnregisteredRecipientException e
) {
991 }).filter(Objects
::nonNull
).collect(Collectors
.toSet());
992 // refresh profiles of explicitly given recipients
993 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
994 return account
.getRecipientStore().getRecipients(onlyContacts
, blocked
, recipientIds
, name
);
998 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
999 final RecipientId recipientId
;
1001 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1002 } catch (UnregisteredRecipientException e
) {
1006 final var contact
= account
.getContactStore().getContact(recipientId
);
1007 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1008 return contact
.getName();
1011 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
1012 if (profile
!= null) {
1013 return profile
.getDisplayName();
1020 public Group
getGroup(GroupId groupId
) {
1021 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1025 public List
<Identity
> getIdentities() {
1026 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1029 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1030 if (identityInfo
== null) {
1034 final var address
= account
.getRecipientAddressResolver()
1035 .resolveRecipientAddress(identityInfo
.getRecipientId());
1036 final var scannableFingerprint
= context
.getIdentityHelper()
1037 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
1038 return new Identity(address
,
1039 identityInfo
.getIdentityKey(),
1040 context
.getIdentityHelper()
1041 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1042 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1043 identityInfo
.getTrustLevel(),
1044 identityInfo
.getDateAdded());
1048 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1049 IdentityInfo identity
;
1051 identity
= account
.getIdentityKeyStore()
1052 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
1053 } catch (UnregisteredRecipientException e
) {
1056 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1060 public boolean trustIdentityVerified(
1061 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1062 ) throws UnregisteredRecipientException
{
1063 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
1067 public boolean trustIdentityVerifiedSafetyNumber(
1068 RecipientIdentifier
.Single recipient
, String safetyNumber
1069 ) throws UnregisteredRecipientException
{
1070 return trustIdentity(recipient
,
1071 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1075 public boolean trustIdentityVerifiedSafetyNumber(
1076 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1077 ) throws UnregisteredRecipientException
{
1078 return trustIdentity(recipient
,
1079 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1083 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1084 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1087 private boolean trustIdentity(
1088 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1089 ) throws UnregisteredRecipientException
{
1090 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1091 final var updated
= trustMethod
.apply(recipientId
);
1092 if (updated
&& this.isReceiving()) {
1093 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1099 public void addAddressChangedListener(final Runnable listener
) {
1100 synchronized (addressChangedListeners
) {
1101 addressChangedListeners
.add(listener
);
1106 public void addClosedListener(final Runnable listener
) {
1107 synchronized (closedListeners
) {
1108 closedListeners
.add(listener
);
1113 public void close() {
1115 synchronized (messageHandlers
) {
1116 weakHandlers
.clear();
1117 messageHandlers
.clear();
1118 thread
= receiveThread
;
1119 receiveThread
= null;
1121 if (thread
!= null) {
1122 stopReceiveThread(thread
);
1124 executor
.shutdown();
1126 dependencies
.getSignalWebSocket().disconnect();
1127 disposable
.dispose();
1129 if (account
!= null) {
1133 synchronized (closedListeners
) {
1134 closedListeners
.forEach(Runnable
::run
);
1135 closedListeners
.clear();