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
.Configuration
;
20 import org
.asamk
.signal
.manager
.api
.Device
;
21 import org
.asamk
.signal
.manager
.api
.Group
;
22 import org
.asamk
.signal
.manager
.api
.Identity
;
23 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
24 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
25 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
26 import org
.asamk
.signal
.manager
.api
.Message
;
27 import org
.asamk
.signal
.manager
.api
.Pair
;
28 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
29 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
30 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
31 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
32 import org
.asamk
.signal
.manager
.api
.StickerPack
;
33 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
34 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
35 import org
.asamk
.signal
.manager
.api
.TypingAction
;
36 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
37 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
38 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
39 import org
.asamk
.signal
.manager
.groups
.GroupId
;
40 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
41 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
42 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
43 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
44 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
45 import org
.asamk
.signal
.manager
.helper
.Context
;
46 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
47 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
48 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
49 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
50 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
51 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
52 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
53 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
54 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
55 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
56 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
57 import org
.slf4j
.Logger
;
58 import org
.slf4j
.LoggerFactory
;
59 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
60 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
61 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
62 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
63 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
64 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
65 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
66 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
67 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
68 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
69 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
72 import java
.io
.IOException
;
74 import java
.time
.Duration
;
75 import java
.util
.ArrayList
;
76 import java
.util
.HashMap
;
77 import java
.util
.HashSet
;
78 import java
.util
.List
;
81 import java
.util
.UUID
;
82 import java
.util
.concurrent
.ExecutorService
;
83 import java
.util
.concurrent
.Executors
;
84 import java
.util
.concurrent
.locks
.ReentrantLock
;
85 import java
.util
.function
.Function
;
86 import java
.util
.stream
.Collectors
;
87 import java
.util
.stream
.Stream
;
89 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
91 public class ManagerImpl
implements Manager
{
93 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
95 private SignalAccount account
;
96 private final SignalDependencies dependencies
;
97 private final Context context
;
99 private final ExecutorService executor
= Executors
.newCachedThreadPool();
101 private Thread receiveThread
;
102 private boolean isReceivingSynchronous
;
103 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
104 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
105 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
106 private final CompositeDisposable disposable
= new CompositeDisposable();
109 SignalAccount account
,
110 PathConfig pathConfig
,
111 ServiceEnvironmentConfig serviceEnvironmentConfig
,
114 this.account
= account
;
116 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getAci(),
117 account
.getAccount(),
118 account
.getPassword(),
119 account
.getDeviceId());
120 final var sessionLock
= new SignalSessionLock() {
121 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
124 public Lock
acquire() {
126 return LEGACY_LOCK
::unlock
;
129 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
132 account
.getSignalProtocolStore(),
135 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
136 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
137 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
139 this.context
= new Context(account
, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
140 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
141 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
142 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
143 synchronized (this) {
147 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
148 logger
.trace("Archiving old sessions for {}", recipientId
);
149 account
.getSessionStore().archiveSessions(recipientId
);
150 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
151 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
152 if (profile
!= null) {
153 account
.getRecipientStore()
154 .storeProfile(recipientId
,
155 Profile
.newBuilder(profile
)
156 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
157 .withLastUpdateTimestamp(0)
164 public String
getSelfNumber() {
165 return account
.getAccount();
169 public void checkAccountState() throws IOException
{
170 context
.getAccountHelper().checkAccountState();
174 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
175 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
177 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getAccount());
178 if (!canonicalizedNumber
.equals(n
)) {
179 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
181 return canonicalizedNumber
;
182 } catch (InvalidNumberException e
) {
187 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
188 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
190 .filter(s
-> !s
.isEmpty())
191 .collect(Collectors
.toSet());
192 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
194 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
195 final var number
= canonicalizedNumbers
.get(n
);
196 final var aci
= registeredUsers
.get(number
);
197 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
202 public void updateAccountAttributes(String deviceName
) throws IOException
{
203 if (deviceName
!= null) {
204 context
.getAccountHelper().setDeviceName(deviceName
);
206 context
.getAccountHelper().updateAccountAttributes();
210 public Configuration
getConfiguration() {
211 final var configurationStore
= account
.getConfigurationStore();
212 return Configuration
.from(configurationStore
);
216 public void updateConfiguration(
217 Configuration configuration
218 ) throws NotMasterDeviceException
{
219 if (!account
.isMasterDevice()) {
220 throw new NotMasterDeviceException();
223 final var configurationStore
= account
.getConfigurationStore();
224 if (configuration
.readReceipts().isPresent()) {
225 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
227 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
228 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
230 if (configuration
.typingIndicators().isPresent()) {
231 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
233 if (configuration
.linkPreviews().isPresent()) {
234 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
236 context
.getSyncHelper().sendConfigurationMessage();
240 public void setProfile(
241 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
242 ) throws IOException
{
243 context
.getProfileHelper()
244 .setProfile(givenName
,
248 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
249 context
.getSyncHelper().sendSyncFetchProfileMessage();
253 public void unregister() throws IOException
{
254 context
.getAccountHelper().unregister();
258 public void deleteAccount() throws IOException
{
259 context
.getAccountHelper().deleteAccount();
263 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
264 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
266 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
270 public List
<Device
> getLinkedDevices() throws IOException
{
271 var devices
= dependencies
.getAccountManager().getDevices();
272 account
.setMultiDevice(devices
.size() > 1);
273 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
274 return devices
.stream().map(d
-> {
275 String deviceName
= d
.getName();
276 if (deviceName
!= null) {
278 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
279 } catch (IOException e
) {
280 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
283 return new Device(d
.getId(),
287 d
.getId() == account
.getDeviceId());
292 public void removeLinkedDevices(int deviceId
) throws IOException
{
293 context
.getAccountHelper().removeLinkedDevices(deviceId
);
297 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
298 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
299 context
.getAccountHelper().addDevice(deviceLinkInfo
);
303 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
304 if (!account
.isMasterDevice()) {
305 throw new NotMasterDeviceException();
307 if (pin
.isPresent()) {
308 context
.getAccountHelper().setRegistrationPin(pin
.get());
310 context
.getAccountHelper().removeRegistrationPin();
314 void refreshPreKeys() throws IOException
{
315 context
.getPreKeyHelper().refreshPreKeys();
319 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
320 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
324 public List
<Group
> getGroups() {
325 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
328 private Group
toGroup(final GroupInfo groupInfo
) {
329 if (groupInfo
== null) {
333 return Group
.from(groupInfo
,
334 account
.getRecipientStore()::resolveRecipientAddress
,
335 account
.getSelfRecipientId());
339 public SendGroupMessageResults
quitGroup(
340 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
341 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
342 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
343 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
347 public void deleteGroup(GroupId groupId
) throws IOException
{
348 context
.getGroupHelper().deleteGroup(groupId
);
352 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
353 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
354 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
355 return context
.getGroupHelper()
357 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
362 public SendGroupMessageResults
updateGroup(
363 final GroupId groupId
, final UpdateGroup updateGroup
364 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
365 return context
.getGroupHelper()
366 .updateGroup(groupId
,
367 updateGroup
.getName(),
368 updateGroup
.getDescription(),
369 updateGroup
.getMembers() == null
371 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
372 updateGroup
.getRemoveMembers() == null
374 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
375 updateGroup
.getAdmins() == null
377 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
378 updateGroup
.getRemoveAdmins() == null
380 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
381 updateGroup
.isResetGroupLink(),
382 updateGroup
.getGroupLinkState(),
383 updateGroup
.getAddMemberPermission(),
384 updateGroup
.getEditDetailsPermission(),
385 updateGroup
.getAvatarFile(),
386 updateGroup
.getExpirationTimer(),
387 updateGroup
.getIsAnnouncementGroup());
391 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
392 GroupInviteLinkUrl inviteLinkUrl
393 ) throws IOException
, InactiveGroupLinkException
{
394 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
397 private SendMessageResults
sendMessage(
398 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
399 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
400 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
401 long timestamp
= System
.currentTimeMillis();
402 messageBuilder
.withTimestamp(timestamp
);
403 for (final var recipient
: recipients
) {
404 if (recipient
instanceof RecipientIdentifier
.Single single
) {
406 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
407 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
408 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
409 } catch (UnregisteredRecipientException e
) {
410 results
.put(recipient
,
411 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
413 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
414 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
415 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
416 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
417 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
418 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
421 return new SendMessageResults(timestamp
, results
);
424 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
425 return SendMessageResult
.from(result
,
426 account
.getRecipientStore(),
427 account
.getRecipientStore()::resolveRecipientAddress
);
430 private SendMessageResults
sendTypingMessage(
431 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
432 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
433 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
434 final var timestamp
= System
.currentTimeMillis();
435 for (var recipient
: recipients
) {
436 if (recipient
instanceof RecipientIdentifier
.Single single
) {
437 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
439 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
440 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
441 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
442 } catch (UnregisteredRecipientException e
) {
443 results
.put(recipient
,
444 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
446 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
447 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
448 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
449 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
450 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
453 return new SendMessageResults(timestamp
, results
);
457 public SendMessageResults
sendTypingMessage(
458 TypingAction action
, Set
<RecipientIdentifier
> recipients
459 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
460 return sendTypingMessage(action
.toSignalService(), recipients
);
464 public SendMessageResults
sendReadReceipt(
465 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
466 ) throws IOException
{
467 final var timestamp
= System
.currentTimeMillis();
468 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
472 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
476 public SendMessageResults
sendViewedReceipt(
477 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
478 ) throws IOException
{
479 final var timestamp
= System
.currentTimeMillis();
480 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
484 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
487 private SendMessageResults
sendReceiptMessage(
488 final RecipientIdentifier
.Single sender
,
489 final long timestamp
,
490 final SignalServiceReceiptMessage receiptMessage
491 ) throws IOException
{
493 final var result
= context
.getSendHelper()
494 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
495 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
496 } catch (UnregisteredRecipientException e
) {
497 return new SendMessageResults(timestamp
,
498 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
503 public SendMessageResults
sendMessage(
504 Message message
, Set
<RecipientIdentifier
> recipients
505 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
506 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
507 applyMessage(messageBuilder
, message
);
508 return sendMessage(messageBuilder
, recipients
);
511 private void applyMessage(
512 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
513 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
514 messageBuilder
.withBody(message
.messageText());
515 final var attachments
= message
.attachments();
516 if (attachments
!= null) {
517 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
519 if (message
.mentions().size() > 0) {
520 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
522 if (message
.quote().isPresent()) {
523 final var quote
= message
.quote().get();
524 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
525 context
.getRecipientHelper()
526 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
529 resolveMentions(quote
.mentions())));
531 if (message
.sticker().isPresent()) {
532 final var sticker
= message
.sticker().get();
533 final var packId
= StickerPackId
.deserialize(sticker
.packId());
534 final var stickerId
= sticker
.stickerId();
536 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
537 if (stickerPack
== null) {
538 throw new InvalidStickerException("Sticker pack not found");
540 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
541 if (manifest
.stickers().size() <= stickerId
) {
542 throw new InvalidStickerException("Sticker id not part of this pack");
544 final var manifestSticker
= manifest
.stickers().get(stickerId
);
545 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
546 if (streamDetails
== null) {
547 throw new InvalidStickerException("Missing local sticker file");
549 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
550 stickerPack
.getPackKey(),
552 manifestSticker
.emoji(),
553 AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent())));
557 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
558 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
559 for (final var m
: mentionList
) {
560 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
561 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
562 .resolveSignalServiceAddress(recipientId
)
563 .getAci(), m
.start(), m
.length()));
569 public SendMessageResults
sendRemoteDeleteMessage(
570 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
571 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
572 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
573 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
574 return sendMessage(messageBuilder
, recipients
);
578 public SendMessageResults
sendMessageReaction(
581 RecipientIdentifier
.Single targetAuthor
,
582 long targetSentTimestamp
,
583 Set
<RecipientIdentifier
> recipients
584 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
585 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
586 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
588 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
589 targetSentTimestamp
);
590 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
591 return sendMessage(messageBuilder
, recipients
);
595 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
596 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
599 return sendMessage(messageBuilder
,
600 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
601 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
602 throw new AssertionError(e
);
604 for (var recipient
: recipients
) {
605 final RecipientId recipientId
;
607 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
608 } catch (UnregisteredRecipientException e
) {
611 account
.getSessionStore().deleteAllSessions(recipientId
);
617 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
618 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
622 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
623 account
.getContactStore()
624 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
628 public void setContactName(
629 RecipientIdentifier
.Single recipient
, String name
630 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
631 if (!account
.isMasterDevice()) {
632 throw new NotMasterDeviceException();
634 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
638 public void setContactBlocked(
639 RecipientIdentifier
.Single recipient
, boolean blocked
640 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
641 if (!account
.isMasterDevice()) {
642 throw new NotMasterDeviceException();
644 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
645 // TODO cycle our profile key, if we're not together in a group with recipient
646 context
.getSyncHelper().sendBlockedList();
650 public void setGroupBlocked(
651 final GroupId groupId
, final boolean blocked
652 ) throws GroupNotFoundException
, NotMasterDeviceException
{
653 if (!account
.isMasterDevice()) {
654 throw new NotMasterDeviceException();
656 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
657 // TODO cycle our profile key
658 context
.getSyncHelper().sendBlockedList();
662 public void setExpirationTimer(
663 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
664 ) throws IOException
, UnregisteredRecipientException
{
665 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
666 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
667 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
669 sendMessage(messageBuilder
, Set
.of(recipient
));
670 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
671 throw new AssertionError(e
);
676 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
677 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
679 var messageSender
= dependencies
.getMessageSender();
681 var packKey
= KeyUtils
.createStickerUploadKey();
682 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
683 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
685 var sticker
= new Sticker(packId
, packKey
);
686 account
.getStickerStore().updateSticker(sticker
);
688 return new StickerPackUrl(packId
, packKey
);
692 public List
<StickerPack
> getStickerPacks() {
693 final var stickerPackStore
= context
.getStickerPackStore();
694 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
695 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
697 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
698 return new StickerPack(pack
.getPackId(),
699 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
703 java
.util
.Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
704 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
705 } catch (Exception e
) {
706 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
710 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
715 public void requestAllSyncData() throws IOException
{
716 context
.getSyncHelper().requestAllSyncData();
717 retrieveRemoteStorage();
720 void retrieveRemoteStorage() throws IOException
{
721 if (account
.getStorageKey() != null) {
722 context
.getStorageHelper().readDataFromStorage();
727 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
728 if (isReceivingSynchronous
) {
729 throw new IllegalStateException("Already receiving message synchronously.");
731 synchronized (messageHandlers
) {
732 if (isWeakListener
) {
733 weakHandlers
.add(handler
);
735 messageHandlers
.add(handler
);
736 startReceiveThreadIfRequired();
741 private void startReceiveThreadIfRequired() {
742 if (receiveThread
!= null) {
745 receiveThread
= new Thread(() -> {
746 logger
.debug("Starting receiving messages");
747 while (!Thread
.interrupted()) {
749 context
.getReceiveHelper().receiveMessages(Duration
.ofMinutes(1), false, (envelope
, e
) -> {
750 synchronized (messageHandlers
) {
751 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
753 h
.handleMessage(envelope
, e
);
754 } catch (Exception ex
) {
755 logger
.warn("Message handler failed, ignoring", ex
);
761 } catch (IOException e
) {
762 logger
.warn("Receiving messages failed, retrying", e
);
765 logger
.debug("Finished receiving messages");
766 synchronized (messageHandlers
) {
767 receiveThread
= null;
769 // Check if in the meantime another handler has been registered
770 if (!messageHandlers
.isEmpty()) {
771 logger
.debug("Another handler has been registered, starting receive thread again");
772 startReceiveThreadIfRequired();
777 receiveThread
.start();
781 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
783 synchronized (messageHandlers
) {
784 weakHandlers
.remove(handler
);
785 messageHandlers
.remove(handler
);
786 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
789 thread
= receiveThread
;
790 receiveThread
= null;
793 stopReceiveThread(thread
);
796 private void stopReceiveThread(final Thread thread
) {
800 } catch (InterruptedException ignored
) {
805 public boolean isReceiving() {
806 if (isReceivingSynchronous
) {
809 synchronized (messageHandlers
) {
810 return messageHandlers
.size() > 0;
815 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
816 receiveMessages(timeout
, true, handler
);
820 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
821 receiveMessages(Duration
.ofMinutes(1), false, handler
);
824 private void receiveMessages(
825 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
826 ) throws IOException
{
828 throw new IllegalStateException("Already receiving message.");
830 isReceivingSynchronous
= true;
831 receiveThread
= Thread
.currentThread();
833 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
835 receiveThread
= null;
836 isReceivingSynchronous
= false;
841 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
842 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
846 public boolean hasCaughtUpWithOldMessages() {
847 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
851 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
852 final RecipientId recipientId
;
854 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
855 } catch (IOException
| UnregisteredRecipientException e
) {
858 return context
.getContactHelper().isContactBlocked(recipientId
);
862 public void sendContacts() throws IOException
{
863 context
.getSyncHelper().sendContacts();
867 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
868 return account
.getContactStore()
871 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
876 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
877 final RecipientId recipientId
;
879 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
880 } catch (IOException
| UnregisteredRecipientException e
) {
884 final var contact
= account
.getContactStore().getContact(recipientId
);
885 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
886 return contact
.getName();
889 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
890 if (profile
!= null) {
891 return profile
.getDisplayName();
898 public Group
getGroup(GroupId groupId
) {
899 return toGroup(context
.getGroupHelper().getGroup(groupId
));
903 public List
<Identity
> getIdentities() {
904 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
907 private Identity
toIdentity(final IdentityInfo identityInfo
) {
908 if (identityInfo
== null) {
912 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
913 final var scannableFingerprint
= context
.getIdentityHelper()
914 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
915 return new Identity(address
,
916 identityInfo
.getIdentityKey(),
917 context
.getIdentityHelper()
918 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
919 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
920 identityInfo
.getTrustLevel(),
921 identityInfo
.getDateAdded());
925 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
926 IdentityInfo identity
;
928 identity
= account
.getIdentityKeyStore()
929 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
930 } catch (IOException
| UnregisteredRecipientException e
) {
933 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
937 public boolean trustIdentityVerified(
938 RecipientIdentifier
.Single recipient
, byte[] fingerprint
939 ) throws UnregisteredRecipientException
{
940 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
944 public boolean trustIdentityVerifiedSafetyNumber(
945 RecipientIdentifier
.Single recipient
, String safetyNumber
946 ) throws UnregisteredRecipientException
{
947 return trustIdentity(recipient
,
948 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
952 public boolean trustIdentityVerifiedSafetyNumber(
953 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
954 ) throws UnregisteredRecipientException
{
955 return trustIdentity(recipient
,
956 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
960 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
961 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
964 private boolean trustIdentity(
965 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
966 ) throws UnregisteredRecipientException
{
967 RecipientId recipientId
;
969 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
970 } catch (IOException e
) {
973 final var updated
= trustMethod
.apply(recipientId
);
974 if (updated
&& this.isReceiving()) {
975 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
981 public void addClosedListener(final Runnable listener
) {
982 synchronized (closedListeners
) {
983 closedListeners
.add(listener
);
988 public void close() {
990 synchronized (messageHandlers
) {
991 weakHandlers
.clear();
992 messageHandlers
.clear();
993 thread
= receiveThread
;
994 receiveThread
= null;
996 if (thread
!= null) {
997 stopReceiveThread(thread
);
1001 dependencies
.getSignalWebSocket().disconnect();
1002 disposable
.dispose();
1004 synchronized (closedListeners
) {
1005 closedListeners
.forEach(Runnable
::run
);
1006 closedListeners
.clear();
1009 if (account
!= null) {