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();
235 context
.getAccountHelper().checkWhoAmiI();
239 public Configuration
getConfiguration() {
240 final var configurationStore
= account
.getConfigurationStore();
241 return Configuration
.from(configurationStore
);
245 public void updateConfiguration(
246 Configuration configuration
247 ) throws NotPrimaryDeviceException
{
248 if (!account
.isPrimaryDevice()) {
249 throw new NotPrimaryDeviceException();
252 final var configurationStore
= account
.getConfigurationStore();
253 if (configuration
.readReceipts().isPresent()) {
254 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
256 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
257 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
259 if (configuration
.typingIndicators().isPresent()) {
260 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
262 if (configuration
.linkPreviews().isPresent()) {
263 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
265 context
.getSyncHelper().sendConfigurationMessage();
269 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
270 context
.getProfileHelper()
271 .setProfile(updateProfile
.getGivenName(),
272 updateProfile
.getFamilyName(),
273 updateProfile
.getAbout(),
274 updateProfile
.getAboutEmoji(),
275 updateProfile
.isDeleteAvatar()
277 : updateProfile
.getAvatar() == null ?
null : Optional
.of(updateProfile
.getAvatar()),
278 updateProfile
.getMobileCoinAddress());
279 context
.getSyncHelper().sendSyncFetchProfileMessage();
283 public void unregister() throws IOException
{
284 context
.getAccountHelper().unregister();
288 public void deleteAccount() throws IOException
{
289 context
.getAccountHelper().deleteAccount();
293 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
294 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
296 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
300 public List
<Device
> getLinkedDevices() throws IOException
{
301 var devices
= dependencies
.getAccountManager().getDevices();
302 account
.setMultiDevice(devices
.size() > 1);
303 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
304 return devices
.stream().map(d
-> {
305 String deviceName
= d
.getName();
306 if (deviceName
!= null) {
308 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
309 } catch (IOException e
) {
310 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
313 return new Device(d
.getId(),
317 d
.getId() == account
.getDeviceId());
322 public void removeLinkedDevices(int deviceId
) throws IOException
{
323 context
.getAccountHelper().removeLinkedDevices(deviceId
);
327 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
328 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
329 context
.getAccountHelper().addDevice(deviceLinkInfo
);
333 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotPrimaryDeviceException
{
334 if (!account
.isPrimaryDevice()) {
335 throw new NotPrimaryDeviceException();
337 if (pin
.isPresent()) {
338 context
.getAccountHelper().setRegistrationPin(pin
.get());
340 context
.getAccountHelper().removeRegistrationPin();
344 void refreshPreKeys() throws IOException
{
345 context
.getPreKeyHelper().refreshPreKeys();
349 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
350 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
354 public List
<Group
> getGroups() {
355 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
358 private Group
toGroup(final GroupInfo groupInfo
) {
359 if (groupInfo
== null) {
363 return Group
.from(groupInfo
, account
.getRecipientAddressResolver(), account
.getSelfRecipientId());
367 public SendGroupMessageResults
quitGroup(
368 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
369 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
370 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
371 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
375 public void deleteGroup(GroupId groupId
) throws IOException
{
376 final var group
= context
.getGroupHelper().getGroup(groupId
);
377 if (group
.isMember(account
.getSelfRecipientId())) {
378 throw new IOException(
379 "The local group information cannot be removed, as the user is still a member of the group");
381 context
.getGroupHelper().deleteGroup(groupId
);
385 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
386 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
387 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
388 return context
.getGroupHelper()
390 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
395 public SendGroupMessageResults
updateGroup(
396 final GroupId groupId
, final UpdateGroup updateGroup
397 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
398 return context
.getGroupHelper()
399 .updateGroup(groupId
,
400 updateGroup
.getName(),
401 updateGroup
.getDescription(),
402 updateGroup
.getMembers() == null
404 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
405 updateGroup
.getRemoveMembers() == null
407 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
408 updateGroup
.getAdmins() == null
410 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
411 updateGroup
.getRemoveAdmins() == null
413 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
414 updateGroup
.getBanMembers() == null
416 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
417 updateGroup
.getUnbanMembers() == null
419 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
420 updateGroup
.isResetGroupLink(),
421 updateGroup
.getGroupLinkState(),
422 updateGroup
.getAddMemberPermission(),
423 updateGroup
.getEditDetailsPermission(),
424 updateGroup
.getAvatarFile(),
425 updateGroup
.getExpirationTimer(),
426 updateGroup
.getIsAnnouncementGroup());
430 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
431 GroupInviteLinkUrl inviteLinkUrl
432 ) throws IOException
, InactiveGroupLinkException
{
433 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
436 private SendMessageResults
sendMessage(
437 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
438 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
439 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
440 long timestamp
= System
.currentTimeMillis();
441 messageBuilder
.withTimestamp(timestamp
);
442 for (final var recipient
: recipients
) {
443 if (recipient
instanceof RecipientIdentifier
.Single single
) {
445 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
446 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
447 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
448 } catch (UnregisteredRecipientException e
) {
449 results
.put(recipient
,
450 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
452 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
453 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
454 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
455 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
456 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
457 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
460 return new SendMessageResults(timestamp
, results
);
463 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
464 return SendMessageResult
.from(result
, account
.getRecipientResolver(), account
.getRecipientAddressResolver());
467 private SendMessageResults
sendTypingMessage(
468 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
469 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
470 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
471 final var timestamp
= System
.currentTimeMillis();
472 for (var recipient
: recipients
) {
473 if (recipient
instanceof RecipientIdentifier
.Single single
) {
474 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
476 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
477 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
478 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
479 } catch (UnregisteredRecipientException e
) {
480 results
.put(recipient
,
481 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
483 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
484 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
485 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
486 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
487 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
490 return new SendMessageResults(timestamp
, results
);
494 public SendMessageResults
sendTypingMessage(
495 TypingAction action
, Set
<RecipientIdentifier
> recipients
496 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
497 return sendTypingMessage(action
.toSignalService(), recipients
);
501 public SendMessageResults
sendReadReceipt(
502 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
504 final var timestamp
= System
.currentTimeMillis();
505 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
509 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
513 public SendMessageResults
sendViewedReceipt(
514 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
516 final var timestamp
= System
.currentTimeMillis();
517 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
521 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
524 private SendMessageResults
sendReceiptMessage(
525 final RecipientIdentifier
.Single sender
,
526 final long timestamp
,
527 final SignalServiceReceiptMessage receiptMessage
530 final var result
= context
.getSendHelper()
531 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
532 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
533 } catch (UnregisteredRecipientException e
) {
534 return new SendMessageResults(timestamp
,
535 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
540 public SendMessageResults
sendMessage(
541 Message message
, Set
<RecipientIdentifier
> recipients
542 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
543 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
544 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
546 "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.");
548 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
549 applyMessage(messageBuilder
, message
);
550 return sendMessage(messageBuilder
, recipients
);
553 private void applyMessage(
554 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
555 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
556 messageBuilder
.withBody(message
.messageText());
557 if (message
.attachments().size() > 0) {
558 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(message
.attachments()));
560 if (message
.mentions().size() > 0) {
561 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
563 if (message
.quote().isPresent()) {
564 final var quote
= message
.quote().get();
565 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
566 context
.getRecipientHelper()
567 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author()))
571 resolveMentions(quote
.mentions()),
572 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
574 if (message
.sticker().isPresent()) {
575 final var sticker
= message
.sticker().get();
576 final var packId
= StickerPackId
.deserialize(sticker
.packId());
577 final var stickerId
= sticker
.stickerId();
579 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
580 if (stickerPack
== null) {
581 throw new InvalidStickerException("Sticker pack not found");
583 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
584 if (manifest
.stickers().size() <= stickerId
) {
585 throw new InvalidStickerException("Sticker id not part of this pack");
587 final var manifestSticker
= manifest
.stickers().get(stickerId
);
588 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
589 if (streamDetails
== null) {
590 throw new InvalidStickerException("Missing local sticker file");
592 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
593 stickerPack
.getPackKey(),
595 manifestSticker
.emoji(),
596 AttachmentUtils
.createAttachmentStream(streamDetails
, Optional
.empty())));
598 if (message
.previews().size() > 0) {
599 final var previews
= new ArrayList
<SignalServicePreview
>(message
.previews().size());
600 for (final var p
: message
.previews()) {
601 final var image
= p
.image().isPresent() ? context
.getAttachmentHelper()
602 .uploadAttachment(p
.image().get()) : null;
603 previews
.add(new SignalServicePreview(p
.url(),
607 Optional
.ofNullable(image
)));
609 messageBuilder
.withPreviews(previews
);
613 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
614 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
615 for (final var m
: mentionList
) {
616 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
617 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
618 .resolveSignalServiceAddress(recipientId
)
619 .getServiceId(), m
.start(), m
.length()));
625 public SendMessageResults
sendRemoteDeleteMessage(
626 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
627 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
628 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
629 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
630 for (final var recipient
: recipients
) {
631 if (recipient
instanceof RecipientIdentifier
.Single r
) {
633 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
634 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
635 } catch (UnregisteredRecipientException ignored
) {
637 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
638 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
641 return sendMessage(messageBuilder
, recipients
);
645 public SendMessageResults
sendMessageReaction(
648 RecipientIdentifier
.Single targetAuthor
,
649 long targetSentTimestamp
,
650 Set
<RecipientIdentifier
> recipients
651 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
652 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
653 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
655 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
).getServiceId(),
656 targetSentTimestamp
);
657 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
658 return sendMessage(messageBuilder
, recipients
);
662 public SendMessageResults
sendPaymentNotificationMessage(
663 byte[] receipt
, String note
, RecipientIdentifier
.Single recipient
664 ) throws IOException
{
665 final var paymentNotification
= new SignalServiceDataMessage
.PaymentNotification(receipt
, note
);
666 final var payment
= new SignalServiceDataMessage
.Payment(paymentNotification
);
667 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withPayment(payment
);
669 return sendMessage(messageBuilder
, Set
.of(recipient
));
670 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
671 throw new AssertionError(e
);
676 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
677 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
680 return sendMessage(messageBuilder
,
681 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
682 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
683 throw new AssertionError(e
);
685 for (var recipient
: recipients
) {
686 final RecipientId recipientId
;
688 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
689 } catch (UnregisteredRecipientException e
) {
692 account
.getSessionStore().deleteAllSessions(recipientId
);
698 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
699 account
.removeRecipient(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
703 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
704 account
.getContactStore()
705 .deleteContact(account
.getRecipientResolver().resolveRecipient(recipient
.toPartialRecipientAddress()));
709 public void setContactName(
710 RecipientIdentifier
.Single recipient
, String givenName
, final String familyName
711 ) throws NotPrimaryDeviceException
, UnregisteredRecipientException
{
712 if (!account
.isPrimaryDevice()) {
713 throw new NotPrimaryDeviceException();
715 context
.getContactHelper()
716 .setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), givenName
, familyName
);
720 public void setContactsBlocked(
721 Collection
<RecipientIdentifier
.Single
> recipients
, boolean blocked
722 ) throws NotPrimaryDeviceException
, IOException
, UnregisteredRecipientException
{
723 if (!account
.isPrimaryDevice()) {
724 throw new NotPrimaryDeviceException();
726 if (recipients
.size() == 0) {
729 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
730 final var selfRecipientId
= account
.getSelfRecipientId();
731 boolean shouldRotateProfileKey
= false;
732 for (final var recipientId
: recipientIds
) {
733 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
736 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
737 // if we don't have a common group with the blocked contact we need to rotate the profile key
738 shouldRotateProfileKey
= blocked
&& (
739 shouldRotateProfileKey
|| account
.getGroupStore()
742 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
745 if (shouldRotateProfileKey
) {
746 context
.getProfileHelper().rotateProfileKey();
748 context
.getSyncHelper().sendBlockedList();
752 public void setGroupsBlocked(
753 final Collection
<GroupId
> groupIds
, final boolean blocked
754 ) throws GroupNotFoundException
, NotPrimaryDeviceException
, IOException
{
755 if (!account
.isPrimaryDevice()) {
756 throw new NotPrimaryDeviceException();
758 if (groupIds
.size() == 0) {
761 boolean shouldRotateProfileKey
= false;
762 for (final var groupId
: groupIds
) {
763 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
766 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
767 shouldRotateProfileKey
= blocked
;
769 if (shouldRotateProfileKey
) {
770 context
.getProfileHelper().rotateProfileKey();
772 context
.getSyncHelper().sendBlockedList();
776 public void setExpirationTimer(
777 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
778 ) throws IOException
, UnregisteredRecipientException
{
779 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
780 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
781 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
783 sendMessage(messageBuilder
, Set
.of(recipient
));
784 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
785 throw new AssertionError(e
);
790 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
791 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
793 var messageSender
= dependencies
.getMessageSender();
795 var packKey
= KeyUtils
.createStickerUploadKey();
796 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
797 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
799 var sticker
= new Sticker(packId
, packKey
);
800 account
.getStickerStore().updateSticker(sticker
);
802 return new StickerPackUrl(packId
, packKey
);
806 public List
<StickerPack
> getStickerPacks() {
807 final var stickerPackStore
= context
.getStickerPackStore();
808 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
809 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
811 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
812 return new StickerPack(pack
.getPackId(),
813 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
817 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
818 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
819 } catch (Exception e
) {
820 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
824 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
829 public void requestAllSyncData() throws IOException
{
830 context
.getSyncHelper().requestAllSyncData();
831 retrieveRemoteStorage();
834 void retrieveRemoteStorage() throws IOException
{
835 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 if (!recipients
.isEmpty() && recipientIds
.isEmpty()) {
995 // refresh profiles of explicitly given recipients
996 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
997 return account
.getRecipientStore().getRecipients(onlyContacts
, blocked
, recipientIds
, name
);
1001 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1002 final RecipientId recipientId
;
1004 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1005 } catch (UnregisteredRecipientException e
) {
1009 final var contact
= account
.getContactStore().getContact(recipientId
);
1010 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1011 return contact
.getName();
1014 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
1015 if (profile
!= null) {
1016 return profile
.getDisplayName();
1023 public Group
getGroup(GroupId groupId
) {
1024 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1028 public List
<Identity
> getIdentities() {
1029 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1032 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1033 if (identityInfo
== null) {
1037 final var address
= account
.getRecipientAddressResolver()
1038 .resolveRecipientAddress(identityInfo
.getRecipientId());
1039 final var scannableFingerprint
= context
.getIdentityHelper()
1040 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
1041 return new Identity(address
,
1042 identityInfo
.getIdentityKey(),
1043 context
.getIdentityHelper()
1044 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1045 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1046 identityInfo
.getTrustLevel(),
1047 identityInfo
.getDateAdded());
1051 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1052 IdentityInfo identity
;
1054 identity
= account
.getIdentityKeyStore()
1055 .getIdentityInfo(context
.getRecipientHelper().resolveRecipient(recipient
));
1056 } catch (UnregisteredRecipientException e
) {
1059 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1063 public boolean trustIdentityVerified(
1064 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1065 ) throws UnregisteredRecipientException
{
1066 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
1070 public boolean trustIdentityVerifiedSafetyNumber(
1071 RecipientIdentifier
.Single recipient
, String safetyNumber
1072 ) throws UnregisteredRecipientException
{
1073 return trustIdentity(recipient
,
1074 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1078 public boolean trustIdentityVerifiedSafetyNumber(
1079 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1080 ) throws UnregisteredRecipientException
{
1081 return trustIdentity(recipient
,
1082 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1086 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1087 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1090 private boolean trustIdentity(
1091 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1092 ) throws UnregisteredRecipientException
{
1093 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1094 final var updated
= trustMethod
.apply(recipientId
);
1095 if (updated
&& this.isReceiving()) {
1096 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1102 public void addAddressChangedListener(final Runnable listener
) {
1103 synchronized (addressChangedListeners
) {
1104 addressChangedListeners
.add(listener
);
1109 public void addClosedListener(final Runnable listener
) {
1110 synchronized (closedListeners
) {
1111 closedListeners
.add(listener
);
1116 public void close() {
1118 synchronized (messageHandlers
) {
1119 weakHandlers
.clear();
1120 messageHandlers
.clear();
1121 thread
= receiveThread
;
1122 receiveThread
= null;
1124 if (thread
!= null) {
1125 stopReceiveThread(thread
);
1127 executor
.shutdown();
1129 dependencies
.getSignalWebSocket().disconnect();
1130 disposable
.dispose();
1132 if (account
!= null) {
1136 synchronized (closedListeners
) {
1137 closedListeners
.forEach(Runnable
::run
);
1138 closedListeners
.clear();