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
.PendingAdminApprovalException
;
31 import org
.asamk
.signal
.manager
.api
.ReceiveConfig
;
32 import org
.asamk
.signal
.manager
.api
.Recipient
;
33 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
34 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
35 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
36 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
37 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
38 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
39 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
40 import org
.asamk
.signal
.manager
.api
.TypingAction
;
41 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
42 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
43 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
44 import org
.asamk
.signal
.manager
.api
.UserStatus
;
45 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
46 import org
.asamk
.signal
.manager
.groups
.GroupId
;
47 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
48 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
49 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
50 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
51 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
52 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
53 import org
.asamk
.signal
.manager
.helper
.Context
;
54 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
55 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
56 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
57 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
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
.StickerPack
;
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
.push
.ServiceId
;
74 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
75 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
76 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
77 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
78 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
81 import java
.io
.IOException
;
83 import java
.time
.Duration
;
84 import java
.util
.ArrayList
;
85 import java
.util
.Collection
;
86 import java
.util
.HashMap
;
87 import java
.util
.HashSet
;
88 import java
.util
.List
;
90 import java
.util
.Objects
;
91 import java
.util
.Optional
;
93 import java
.util
.concurrent
.ExecutorService
;
94 import java
.util
.concurrent
.Executors
;
95 import java
.util
.concurrent
.atomic
.AtomicInteger
;
96 import java
.util
.concurrent
.locks
.ReentrantLock
;
97 import java
.util
.function
.Function
;
98 import java
.util
.stream
.Collectors
;
99 import java
.util
.stream
.Stream
;
101 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
103 class ManagerImpl
implements Manager
{
105 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
107 private SignalAccount account
;
108 private final SignalDependencies dependencies
;
109 private final Context context
;
111 private final ExecutorService executor
= Executors
.newCachedThreadPool();
113 private Thread receiveThread
;
114 private boolean isReceivingSynchronous
;
115 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
116 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
117 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
118 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
119 private final CompositeDisposable disposable
= new CompositeDisposable();
122 SignalAccount account
,
123 PathConfig pathConfig
,
124 AccountFileUpdater accountFileUpdater
,
125 ServiceEnvironmentConfig serviceEnvironmentConfig
,
128 this.account
= account
;
130 final var sessionLock
= new SignalSessionLock() {
131 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
134 public Lock
acquire() {
136 return LEGACY_LOCK
::unlock
;
139 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
141 account
.getCredentialsProvider(),
142 account
.getSignalServiceDataStore(),
145 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
146 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
147 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
149 this.context
= new Context(account
, new AccountFileUpdater() {
151 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
152 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
153 synchronized (addressChangedListeners
) {
154 addressChangedListeners
.forEach(Runnable
::run
);
159 public void removeAccount() {
160 accountFileUpdater
.removeAccount();
162 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
163 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
164 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
165 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
166 synchronized (this) {
170 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(serviceId
-> {
171 logger
.trace("Archiving old sessions for {}", serviceId
);
172 account
.getAciSessionStore().archiveSessions(serviceId
);
173 account
.getPniSessionStore().archiveSessions(serviceId
);
174 account
.getSenderKeyStore().deleteSharedWith(serviceId
);
175 final var recipientId
= account
.getRecipientResolver().resolveRecipient(serviceId
);
176 final var profile
= account
.getProfileStore().getProfile(recipientId
);
177 if (profile
!= null) {
178 account
.getProfileStore()
179 .storeProfile(recipientId
,
180 Profile
.newBuilder(profile
)
181 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
182 .withLastUpdateTimestamp(0)
189 public String
getSelfNumber() {
190 return account
.getNumber();
193 void checkAccountState() throws IOException
{
194 context
.getAccountHelper().checkAccountState();
198 public Map
<String
, UserStatus
> getUserStatus(Set
<String
> numbers
) throws IOException
{
199 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
201 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
202 if (!canonicalizedNumber
.equals(n
)) {
203 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
205 return canonicalizedNumber
;
206 } catch (InvalidNumberException e
) {
211 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
212 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
214 .filter(s
-> !s
.isEmpty())
215 .collect(Collectors
.toSet());
216 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
218 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
219 final var number
= canonicalizedNumbers
.get(n
);
220 final var user
= registeredUsers
.get(number
);
221 final var serviceId
= user
== null ?
null : user
.getServiceId();
222 final var profile
= serviceId
== null
224 : context
.getProfileHelper()
225 .getRecipientProfile(account
.getRecipientResolver().resolveRecipient(serviceId
));
226 return new UserStatus(number
.isEmpty() ?
null : number
,
227 serviceId
== null ?
null : serviceId
.uuid(),
229 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
234 public void updateAccountAttributes(String deviceName
) throws IOException
{
235 if (deviceName
!= null) {
236 context
.getAccountHelper().setDeviceName(deviceName
);
238 context
.getAccountHelper().updateAccountAttributes();
239 context
.getAccountHelper().checkWhoAmiI();
243 public Configuration
getConfiguration() {
244 final var configurationStore
= account
.getConfigurationStore();
245 return Configuration
.from(configurationStore
);
249 public void updateConfiguration(
250 Configuration configuration
251 ) throws NotPrimaryDeviceException
{
252 if (!account
.isPrimaryDevice()) {
253 throw new NotPrimaryDeviceException();
256 final var configurationStore
= account
.getConfigurationStore();
257 if (configuration
.readReceipts().isPresent()) {
258 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
260 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
261 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
263 if (configuration
.typingIndicators().isPresent()) {
264 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
266 if (configuration
.linkPreviews().isPresent()) {
267 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
269 context
.getSyncHelper().sendConfigurationMessage();
273 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
274 context
.getProfileHelper()
275 .setProfile(updateProfile
.getGivenName(),
276 updateProfile
.getFamilyName(),
277 updateProfile
.getAbout(),
278 updateProfile
.getAboutEmoji(),
279 updateProfile
.isDeleteAvatar()
281 : updateProfile
.getAvatar() == null ?
null : Optional
.of(updateProfile
.getAvatar()),
282 updateProfile
.getMobileCoinAddress());
283 context
.getSyncHelper().sendSyncFetchProfileMessage();
287 public void unregister() throws IOException
{
288 context
.getAccountHelper().unregister();
292 public void deleteAccount() throws IOException
{
293 context
.getAccountHelper().deleteAccount();
297 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
298 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
300 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
304 public List
<Device
> getLinkedDevices() throws IOException
{
305 var devices
= dependencies
.getAccountManager().getDevices();
306 account
.setMultiDevice(devices
.size() > 1);
307 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
308 return devices
.stream().map(d
-> {
309 String deviceName
= d
.getName();
310 if (deviceName
!= null) {
312 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
313 } catch (IOException e
) {
314 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
317 return new Device(d
.getId(),
321 d
.getId() == account
.getDeviceId());
326 public void removeLinkedDevices(int deviceId
) throws IOException
{
327 context
.getAccountHelper().removeLinkedDevices(deviceId
);
331 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
332 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
333 context
.getAccountHelper().addDevice(deviceLinkInfo
);
337 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotPrimaryDeviceException
{
338 if (!account
.isPrimaryDevice()) {
339 throw new NotPrimaryDeviceException();
341 if (pin
.isPresent()) {
342 context
.getAccountHelper().setRegistrationPin(pin
.get());
344 context
.getAccountHelper().removeRegistrationPin();
348 void refreshPreKeys() throws IOException
{
349 context
.getPreKeyHelper().refreshPreKeys();
353 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
354 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
358 public List
<Group
> getGroups() {
359 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
362 private Group
toGroup(final GroupInfo groupInfo
) {
363 if (groupInfo
== null) {
367 return Group
.from(groupInfo
, account
.getRecipientAddressResolver(), account
.getSelfRecipientId());
371 public SendGroupMessageResults
quitGroup(
372 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
373 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
374 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
375 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
379 public void deleteGroup(GroupId groupId
) throws IOException
{
380 final var group
= context
.getGroupHelper().getGroup(groupId
);
381 if (group
.isMember(account
.getSelfRecipientId())) {
382 throw new IOException(
383 "The local group information cannot be removed, as the user is still a member of the group");
385 context
.getGroupHelper().deleteGroup(groupId
);
389 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
390 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
391 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
392 return context
.getGroupHelper()
394 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
399 public SendGroupMessageResults
updateGroup(
400 final GroupId groupId
, final UpdateGroup updateGroup
401 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
402 return context
.getGroupHelper()
403 .updateGroup(groupId
,
404 updateGroup
.getName(),
405 updateGroup
.getDescription(),
406 updateGroup
.getMembers() == null
408 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
409 updateGroup
.getRemoveMembers() == null
411 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
412 updateGroup
.getAdmins() == null
414 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
415 updateGroup
.getRemoveAdmins() == null
417 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
418 updateGroup
.getBanMembers() == null
420 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
421 updateGroup
.getUnbanMembers() == null
423 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
424 updateGroup
.isResetGroupLink(),
425 updateGroup
.getGroupLinkState(),
426 updateGroup
.getAddMemberPermission(),
427 updateGroup
.getEditDetailsPermission(),
428 updateGroup
.getAvatarFile(),
429 updateGroup
.getExpirationTimer(),
430 updateGroup
.getIsAnnouncementGroup());
434 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
435 GroupInviteLinkUrl inviteLinkUrl
436 ) throws IOException
, InactiveGroupLinkException
, PendingAdminApprovalException
{
437 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
440 private SendMessageResults
sendMessage(
441 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
442 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
443 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
444 long timestamp
= System
.currentTimeMillis();
445 messageBuilder
.withTimestamp(timestamp
);
446 for (final var recipient
: recipients
) {
447 if (recipient
instanceof RecipientIdentifier
.Single single
) {
449 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
450 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
451 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
452 } catch (UnregisteredRecipientException e
) {
453 results
.put(recipient
,
454 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
456 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
457 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
458 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
459 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
460 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
461 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
464 return new SendMessageResults(timestamp
, results
);
467 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
468 return SendMessageResult
.from(result
, account
.getRecipientResolver(), account
.getRecipientAddressResolver());
471 private SendMessageResults
sendTypingMessage(
472 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
473 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
474 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
475 final var timestamp
= System
.currentTimeMillis();
476 for (var recipient
: recipients
) {
477 if (recipient
instanceof RecipientIdentifier
.Single single
) {
478 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
480 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
481 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
482 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
483 } catch (UnregisteredRecipientException e
) {
484 results
.put(recipient
,
485 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
487 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
488 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
489 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
490 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
491 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
494 return new SendMessageResults(timestamp
, results
);
498 public SendMessageResults
sendTypingMessage(
499 TypingAction action
, Set
<RecipientIdentifier
> recipients
500 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
501 return sendTypingMessage(action
.toSignalService(), recipients
);
505 public SendMessageResults
sendReadReceipt(
506 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
508 final var timestamp
= System
.currentTimeMillis();
509 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
513 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
517 public SendMessageResults
sendViewedReceipt(
518 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
520 final var timestamp
= System
.currentTimeMillis();
521 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
525 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
528 private SendMessageResults
sendReceiptMessage(
529 final RecipientIdentifier
.Single sender
,
530 final long timestamp
,
531 final SignalServiceReceiptMessage receiptMessage
534 final var result
= context
.getSendHelper()
535 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
536 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
537 } catch (UnregisteredRecipientException e
) {
538 return new SendMessageResults(timestamp
,
539 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
544 public SendMessageResults
sendMessage(
545 Message message
, Set
<RecipientIdentifier
> recipients
546 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
547 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
548 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
550 "No profile name set. When sending a message it's recommended to set a profile name with the updateProfile command. This may become mandatory in the future.");
552 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
553 applyMessage(messageBuilder
, message
);
554 return sendMessage(messageBuilder
, recipients
);
557 private void applyMessage(
558 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
559 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
560 messageBuilder
.withBody(message
.messageText());
561 if (message
.attachments().size() > 0) {
562 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(message
.attachments()));
564 if (message
.mentions().size() > 0) {
565 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
567 if (message
.quote().isPresent()) {
568 final var quote
= message
.quote().get();
569 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
570 context
.getRecipientHelper()
571 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author()))
575 resolveMentions(quote
.mentions()),
576 SignalServiceDataMessage
.Quote
.Type
.NORMAL
));
578 if (message
.sticker().isPresent()) {
579 final var sticker
= message
.sticker().get();
580 final var packId
= StickerPackId
.deserialize(sticker
.packId());
581 final var stickerId
= sticker
.stickerId();
583 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
584 if (stickerPack
== null) {
585 throw new InvalidStickerException("Sticker pack not found");
587 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.packKey());
588 if (manifest
.stickers().size() <= stickerId
) {
589 throw new InvalidStickerException("Sticker id not part of this pack");
591 final var manifestSticker
= manifest
.stickers().get(stickerId
);
592 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
593 if (streamDetails
== null) {
594 throw new InvalidStickerException("Missing local sticker file");
596 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
597 stickerPack
.packKey(),
599 manifestSticker
.emoji(),
600 AttachmentUtils
.createAttachmentStream(streamDetails
, Optional
.empty())));
602 if (message
.previews().size() > 0) {
603 final var previews
= new ArrayList
<SignalServicePreview
>(message
.previews().size());
604 for (final var p
: message
.previews()) {
605 final var image
= p
.image().isPresent() ? context
.getAttachmentHelper()
606 .uploadAttachment(p
.image().get()) : null;
607 previews
.add(new SignalServicePreview(p
.url(),
611 Optional
.ofNullable(image
)));
613 messageBuilder
.withPreviews(previews
);
617 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
618 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
619 for (final var m
: mentionList
) {
620 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
621 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
622 .resolveSignalServiceAddress(recipientId
)
623 .getServiceId(), m
.start(), m
.length()));
629 public SendMessageResults
sendRemoteDeleteMessage(
630 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
631 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
632 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
633 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
634 for (final var recipient
: recipients
) {
635 if (recipient
instanceof RecipientIdentifier
.Single r
) {
637 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
638 account
.getMessageSendLogStore()
639 .deleteEntryForRecipientNonGroup(targetSentTimestamp
,
640 account
.getRecipientAddressResolver()
641 .resolveRecipientAddress(recipientId
)
643 } catch (UnregisteredRecipientException ignored
) {
645 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
646 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
649 return sendMessage(messageBuilder
, recipients
);
653 public SendMessageResults
sendMessageReaction(
656 RecipientIdentifier
.Single targetAuthor
,
657 long targetSentTimestamp
,
658 Set
<RecipientIdentifier
> recipients
659 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
660 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
661 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
663 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
).getServiceId(),
664 targetSentTimestamp
);
665 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
666 return sendMessage(messageBuilder
, recipients
);
670 public SendMessageResults
sendPaymentNotificationMessage(
671 byte[] receipt
, String note
, RecipientIdentifier
.Single recipient
672 ) throws IOException
{
673 final var paymentNotification
= new SignalServiceDataMessage
.PaymentNotification(receipt
, note
);
674 final var payment
= new SignalServiceDataMessage
.Payment(paymentNotification
);
675 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withPayment(payment
);
677 return sendMessage(messageBuilder
, Set
.of(recipient
));
678 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
679 throw new AssertionError(e
);
684 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
685 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
688 return sendMessage(messageBuilder
,
689 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
690 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
691 throw new AssertionError(e
);
693 for (var recipient
: recipients
) {
694 final RecipientId recipientId
;
696 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
697 } catch (UnregisteredRecipientException e
) {
700 final var serviceId
= context
.getAccount()
701 .getRecipientAddressResolver()
702 .resolveRecipientAddress(recipientId
)
704 account
.getAciSessionStore().deleteAllSessions(serviceId
);
710 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
711 account
.removeRecipient(account
.getRecipientResolver().resolveRecipient(recipient
.getIdentifier()));
715 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
716 account
.getContactStore()
717 .deleteContact(account
.getRecipientResolver().resolveRecipient(recipient
.getIdentifier()));
721 public void setContactName(
722 RecipientIdentifier
.Single recipient
, String givenName
, final String familyName
723 ) throws NotPrimaryDeviceException
, UnregisteredRecipientException
{
724 if (!account
.isPrimaryDevice()) {
725 throw new NotPrimaryDeviceException();
727 context
.getContactHelper()
728 .setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), givenName
, familyName
);
732 public void setContactsBlocked(
733 Collection
<RecipientIdentifier
.Single
> recipients
, boolean blocked
734 ) throws NotPrimaryDeviceException
, IOException
, UnregisteredRecipientException
{
735 if (!account
.isPrimaryDevice()) {
736 throw new NotPrimaryDeviceException();
738 if (recipients
.size() == 0) {
741 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
742 final var selfRecipientId
= account
.getSelfRecipientId();
743 boolean shouldRotateProfileKey
= false;
744 for (final var recipientId
: recipientIds
) {
745 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
748 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
749 // if we don't have a common group with the blocked contact we need to rotate the profile key
750 shouldRotateProfileKey
= blocked
&& (
751 shouldRotateProfileKey
|| account
.getGroupStore()
754 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
757 if (shouldRotateProfileKey
) {
758 context
.getProfileHelper().rotateProfileKey();
760 context
.getSyncHelper().sendBlockedList();
764 public void setGroupsBlocked(
765 final Collection
<GroupId
> groupIds
, final boolean blocked
766 ) throws GroupNotFoundException
, NotPrimaryDeviceException
, IOException
{
767 if (!account
.isPrimaryDevice()) {
768 throw new NotPrimaryDeviceException();
770 if (groupIds
.size() == 0) {
773 boolean shouldRotateProfileKey
= false;
774 for (final var groupId
: groupIds
) {
775 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
778 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
779 shouldRotateProfileKey
= blocked
;
781 if (shouldRotateProfileKey
) {
782 context
.getProfileHelper().rotateProfileKey();
784 context
.getSyncHelper().sendBlockedList();
788 public void setExpirationTimer(
789 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
790 ) throws IOException
, UnregisteredRecipientException
{
791 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
792 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
793 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
795 sendMessage(messageBuilder
, Set
.of(recipient
));
796 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
797 throw new AssertionError(e
);
802 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
803 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
805 var messageSender
= dependencies
.getMessageSender();
807 var packKey
= KeyUtils
.createStickerUploadKey();
808 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
809 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
811 var sticker
= new StickerPack(packId
, packKey
);
812 account
.getStickerStore().addStickerPack(sticker
);
814 return new StickerPackUrl(packId
, packKey
);
818 public List
<org
.asamk
.signal
.manager
.api
.StickerPack
> getStickerPacks() {
819 final var stickerPackStore
= context
.getStickerPackStore();
820 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
821 if (stickerPackStore
.existsStickerPack(pack
.packId())) {
823 final var manifest
= stickerPackStore
.retrieveManifest(pack
.packId());
824 return new org
.asamk
.signal
.manager
.api
.StickerPack(pack
.packId(),
825 new StickerPackUrl(pack
.packId(), pack
.packKey()),
829 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
830 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
831 } catch (Exception e
) {
832 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
836 return new org
.asamk
.signal
.manager
.api
.StickerPack(pack
.packId(), pack
.packKey(), pack
.isInstalled());
841 public void requestAllSyncData() throws IOException
{
842 context
.getSyncHelper().requestAllSyncData();
843 retrieveRemoteStorage();
846 void retrieveRemoteStorage() throws IOException
{
847 context
.getStorageHelper().readDataFromStorage();
851 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
852 if (isReceivingSynchronous
) {
853 throw new IllegalStateException("Already receiving message synchronously.");
855 synchronized (messageHandlers
) {
856 if (isWeakListener
) {
857 weakHandlers
.add(handler
);
859 messageHandlers
.add(handler
);
860 startReceiveThreadIfRequired();
865 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
867 private void startReceiveThreadIfRequired() {
868 if (receiveThread
!= null) {
871 receiveThread
= new Thread(() -> {
872 logger
.debug("Starting receiving messages");
873 context
.getReceiveHelper().receiveMessagesContinuously((envelope
, e
) -> {
874 synchronized (messageHandlers
) {
875 final var handlers
= Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).toList();
876 handlers
.forEach(h
-> {
878 h
.handleMessage(envelope
, e
);
879 } catch (Throwable ex
) {
880 logger
.warn("Message handler failed, ignoring", ex
);
885 logger
.debug("Finished receiving messages");
886 synchronized (messageHandlers
) {
887 receiveThread
= null;
889 // Check if in the meantime another handler has been registered
890 if (!messageHandlers
.isEmpty()) {
891 logger
.debug("Another handler has been registered, starting receive thread again");
892 startReceiveThreadIfRequired();
896 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
898 receiveThread
.start();
902 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
904 synchronized (messageHandlers
) {
905 weakHandlers
.remove(handler
);
906 messageHandlers
.remove(handler
);
907 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
910 thread
= receiveThread
;
911 receiveThread
= null;
914 stopReceiveThread(thread
);
917 private void stopReceiveThread(final Thread thread
) {
918 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
919 logger
.debug("Receive stop requested, interrupting read from server.");
924 } catch (InterruptedException ignored
) {
929 public boolean isReceiving() {
930 if (isReceivingSynchronous
) {
933 synchronized (messageHandlers
) {
934 return messageHandlers
.size() > 0;
939 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
940 receiveMessages(timeout
, true, handler
);
944 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
945 receiveMessages(Duration
.ofMinutes(1), false, handler
);
948 private void receiveMessages(
949 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
950 ) throws IOException
{
952 throw new IllegalStateException("Already receiving message.");
954 isReceivingSynchronous
= true;
955 receiveThread
= Thread
.currentThread();
957 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
959 receiveThread
= null;
960 isReceivingSynchronous
= false;
965 public void setReceiveConfig(final ReceiveConfig receiveConfig
) {
966 context
.getReceiveHelper().setReceiveConfig(receiveConfig
);
970 public boolean hasCaughtUpWithOldMessages() {
971 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
975 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
976 final RecipientId recipientId
;
978 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
979 } catch (UnregisteredRecipientException e
) {
982 return context
.getContactHelper().isContactBlocked(recipientId
);
986 public void sendContacts() throws IOException
{
987 context
.getSyncHelper().sendContacts();
991 public List
<Recipient
> getRecipients(
992 boolean onlyContacts
,
993 Optional
<Boolean
> blocked
,
994 Collection
<RecipientIdentifier
.Single
> recipients
,
995 Optional
<String
> name
997 final var recipientIds
= recipients
.stream().map(a
-> {
999 return context
.getRecipientHelper().resolveRecipient(a
);
1000 } catch (UnregisteredRecipientException e
) {
1003 }).filter(Objects
::nonNull
).collect(Collectors
.toSet());
1004 if (!recipients
.isEmpty() && recipientIds
.isEmpty()) {
1007 // refresh profiles of explicitly given recipients
1008 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
1009 return account
.getRecipientStore()
1010 .getRecipients(onlyContacts
, blocked
, recipientIds
, name
)
1012 .map(s
-> new Recipient(s
.getRecipientId(),
1013 s
.getAddress().toApiRecipientAddress(),
1016 s
.getExpiringProfileKeyCredential(),
1022 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1023 final RecipientId recipientId
;
1025 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1026 } catch (UnregisteredRecipientException e
) {
1030 final var contact
= account
.getContactStore().getContact(recipientId
);
1031 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1032 return contact
.getName();
1035 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
1036 if (profile
!= null) {
1037 return profile
.getDisplayName();
1044 public Group
getGroup(GroupId groupId
) {
1045 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1049 public List
<Identity
> getIdentities() {
1050 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
1053 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1054 if (identityInfo
== null) {
1058 final var address
= account
.getRecipientAddressResolver()
1059 .resolveRecipientAddress(account
.getRecipientResolver().resolveRecipient(identityInfo
.getServiceId()));
1060 final var scannableFingerprint
= context
.getIdentityHelper()
1061 .computeSafetyNumberForScanning(identityInfo
.getServiceId(), identityInfo
.getIdentityKey());
1062 return new Identity(address
.toApiRecipientAddress(),
1063 identityInfo
.getIdentityKey(),
1064 context
.getIdentityHelper()
1065 .computeSafetyNumber(identityInfo
.getServiceId(), identityInfo
.getIdentityKey()),
1066 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1067 identityInfo
.getTrustLevel(),
1068 identityInfo
.getDateAddedTimestamp());
1072 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1073 ServiceId serviceId
;
1075 serviceId
= account
.getRecipientAddressResolver()
1076 .resolveRecipientAddress(context
.getRecipientHelper().resolveRecipient(recipient
))
1078 } catch (UnregisteredRecipientException e
) {
1081 final var identity
= account
.getIdentityKeyStore().getIdentityInfo(serviceId
);
1082 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1086 public boolean trustIdentityVerified(
1087 RecipientIdentifier
.Single recipient
, byte[] fingerprint
1088 ) throws UnregisteredRecipientException
{
1089 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
1093 public boolean trustIdentityVerifiedSafetyNumber(
1094 RecipientIdentifier
.Single recipient
, String safetyNumber
1095 ) throws UnregisteredRecipientException
{
1096 return trustIdentity(recipient
,
1097 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1101 public boolean trustIdentityVerifiedSafetyNumber(
1102 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
1103 ) throws UnregisteredRecipientException
{
1104 return trustIdentity(recipient
,
1105 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
1109 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1110 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1113 private boolean trustIdentity(
1114 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
1115 ) throws UnregisteredRecipientException
{
1116 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1117 final var updated
= trustMethod
.apply(recipientId
);
1118 if (updated
&& this.isReceiving()) {
1119 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1125 public void addAddressChangedListener(final Runnable listener
) {
1126 synchronized (addressChangedListeners
) {
1127 addressChangedListeners
.add(listener
);
1132 public void addClosedListener(final Runnable listener
) {
1133 synchronized (closedListeners
) {
1134 closedListeners
.add(listener
);
1139 public void close() {
1141 synchronized (messageHandlers
) {
1142 weakHandlers
.clear();
1143 messageHandlers
.clear();
1144 thread
= receiveThread
;
1145 receiveThread
= null;
1147 if (thread
!= null) {
1148 stopReceiveThread(thread
);
1150 executor
.shutdown();
1152 dependencies
.getSignalWebSocket().disconnect();
1153 disposable
.dispose();
1155 if (account
!= null) {
1159 synchronized (closedListeners
) {
1160 closedListeners
.forEach(Runnable
::run
);
1161 closedListeners
.clear();