2 Copyright (C) 2015-2022 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
20 import org
.asamk
.signal
.manager
.api
.Configuration
;
21 import org
.asamk
.signal
.manager
.api
.Device
;
22 import org
.asamk
.signal
.manager
.api
.Group
;
23 import org
.asamk
.signal
.manager
.api
.Identity
;
24 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
25 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
26 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
27 import org
.asamk
.signal
.manager
.api
.Message
;
28 import org
.asamk
.signal
.manager
.api
.NotMasterDeviceException
;
29 import org
.asamk
.signal
.manager
.api
.Pair
;
30 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
31 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
32 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
33 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
34 import org
.asamk
.signal
.manager
.api
.StickerPack
;
35 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
36 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
37 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
38 import org
.asamk
.signal
.manager
.api
.TypingAction
;
39 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
40 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
41 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
42 import org
.asamk
.signal
.manager
.groups
.GroupId
;
43 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
44 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
45 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
46 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
47 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
48 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
49 import org
.asamk
.signal
.manager
.helper
.Context
;
50 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
51 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
52 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
53 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
57 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
58 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
59 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
60 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
61 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
62 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
63 import org
.slf4j
.Logger
;
64 import org
.slf4j
.LoggerFactory
;
65 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
66 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
70 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
71 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
72 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
73 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
74 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
77 import java
.io
.IOException
;
79 import java
.time
.Duration
;
80 import java
.util
.ArrayList
;
81 import java
.util
.HashMap
;
82 import java
.util
.HashSet
;
83 import java
.util
.List
;
86 import java
.util
.UUID
;
87 import java
.util
.concurrent
.ExecutorService
;
88 import java
.util
.concurrent
.Executors
;
89 import java
.util
.concurrent
.atomic
.AtomicInteger
;
90 import java
.util
.concurrent
.locks
.ReentrantLock
;
91 import java
.util
.function
.Function
;
92 import java
.util
.stream
.Collectors
;
93 import java
.util
.stream
.Stream
;
95 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
97 class ManagerImpl
implements Manager
{
99 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
101 private SignalAccount account
;
102 private final SignalDependencies dependencies
;
103 private final Context context
;
105 private final ExecutorService executor
= Executors
.newCachedThreadPool();
107 private Thread receiveThread
;
108 private boolean isReceivingSynchronous
;
109 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
110 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
111 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
112 private final CompositeDisposable disposable
= new CompositeDisposable();
115 SignalAccount account
,
116 PathConfig pathConfig
,
117 AccountFileUpdater accountFileUpdater
,
118 ServiceEnvironmentConfig serviceEnvironmentConfig
,
121 this.account
= account
;
123 final var sessionLock
= new SignalSessionLock() {
124 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
127 public Lock
acquire() {
129 return LEGACY_LOCK
::unlock
;
132 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
134 account
.getCredentialsProvider(),
135 account
.getSignalProtocolStore(),
138 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
139 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
140 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
142 this.context
= new Context(account
,
148 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
149 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
150 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
151 synchronized (this) {
155 disposable
.add(account
.getIdentityKeyStore().getIdentityChanges().subscribe(recipientId
-> {
156 logger
.trace("Archiving old sessions for {}", recipientId
);
157 account
.getSessionStore().archiveSessions(recipientId
);
158 account
.getSenderKeyStore().deleteSharedWith(recipientId
);
159 final var profile
= account
.getRecipientStore().getProfile(recipientId
);
160 if (profile
!= null) {
161 account
.getRecipientStore()
162 .storeProfile(recipientId
,
163 Profile
.newBuilder(profile
)
164 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
165 .withLastUpdateTimestamp(0)
172 public String
getSelfNumber() {
173 return account
.getNumber();
176 void checkAccountState() throws IOException
{
177 context
.getAccountHelper().checkAccountState();
181 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
182 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
184 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
185 if (!canonicalizedNumber
.equals(n
)) {
186 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
188 return canonicalizedNumber
;
189 } catch (InvalidNumberException e
) {
194 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
195 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
197 .filter(s
-> !s
.isEmpty())
198 .collect(Collectors
.toSet());
199 final var registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
201 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
202 final var number
= canonicalizedNumbers
.get(n
);
203 final var aci
= registeredUsers
.get(number
);
204 return new Pair
<>(number
.isEmpty() ?
null : number
, aci
== null ?
null : aci
.uuid());
209 public void updateAccountAttributes(String deviceName
) throws IOException
{
210 if (deviceName
!= null) {
211 context
.getAccountHelper().setDeviceName(deviceName
);
213 context
.getAccountHelper().updateAccountAttributes();
217 public Configuration
getConfiguration() {
218 final var configurationStore
= account
.getConfigurationStore();
219 return Configuration
.from(configurationStore
);
223 public void updateConfiguration(
224 Configuration configuration
225 ) throws NotMasterDeviceException
{
226 if (!account
.isMasterDevice()) {
227 throw new NotMasterDeviceException();
230 final var configurationStore
= account
.getConfigurationStore();
231 if (configuration
.readReceipts().isPresent()) {
232 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
234 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
235 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
237 if (configuration
.typingIndicators().isPresent()) {
238 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
240 if (configuration
.linkPreviews().isPresent()) {
241 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
243 context
.getSyncHelper().sendConfigurationMessage();
247 public void setProfile(
248 String givenName
, final String familyName
, String about
, String aboutEmoji
, java
.util
.Optional
<File
> avatar
249 ) throws IOException
{
250 context
.getProfileHelper()
251 .setProfile(givenName
,
255 avatar
== null ?
null : Optional
.fromNullable(avatar
.orElse(null)));
256 context
.getSyncHelper().sendSyncFetchProfileMessage();
260 public void unregister() throws IOException
{
261 context
.getAccountHelper().unregister();
265 public void deleteAccount() throws IOException
{
266 context
.getAccountHelper().deleteAccount();
270 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
271 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
273 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
277 public List
<Device
> getLinkedDevices() throws IOException
{
278 var devices
= dependencies
.getAccountManager().getDevices();
279 account
.setMultiDevice(devices
.size() > 1);
280 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
281 return devices
.stream().map(d
-> {
282 String deviceName
= d
.getName();
283 if (deviceName
!= null) {
285 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
286 } catch (IOException e
) {
287 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
290 return new Device(d
.getId(),
294 d
.getId() == account
.getDeviceId());
299 public void removeLinkedDevices(int deviceId
) throws IOException
{
300 context
.getAccountHelper().removeLinkedDevices(deviceId
);
304 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
305 var deviceLinkInfo
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
306 context
.getAccountHelper().addDevice(deviceLinkInfo
);
310 public void setRegistrationLockPin(java
.util
.Optional
<String
> pin
) throws IOException
, NotMasterDeviceException
{
311 if (!account
.isMasterDevice()) {
312 throw new NotMasterDeviceException();
314 if (pin
.isPresent()) {
315 context
.getAccountHelper().setRegistrationPin(pin
.get());
317 context
.getAccountHelper().removeRegistrationPin();
321 void refreshPreKeys() throws IOException
{
322 context
.getPreKeyHelper().refreshPreKeys();
326 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
327 return context
.getProfileHelper().getRecipientProfile(context
.getRecipientHelper().resolveRecipient(recipient
));
331 public List
<Group
> getGroups() {
332 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).toList();
335 private Group
toGroup(final GroupInfo groupInfo
) {
336 if (groupInfo
== null) {
340 return Group
.from(groupInfo
,
341 account
.getRecipientStore()::resolveRecipientAddress
,
342 account
.getSelfRecipientId());
346 public SendGroupMessageResults
quitGroup(
347 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
348 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
349 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
350 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
354 public void deleteGroup(GroupId groupId
) throws IOException
{
355 context
.getGroupHelper().deleteGroup(groupId
);
359 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
360 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
361 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
362 return context
.getGroupHelper()
364 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
369 public SendGroupMessageResults
updateGroup(
370 final GroupId groupId
, final UpdateGroup updateGroup
371 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
372 return context
.getGroupHelper()
373 .updateGroup(groupId
,
374 updateGroup
.getName(),
375 updateGroup
.getDescription(),
376 updateGroup
.getMembers() == null
378 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
379 updateGroup
.getRemoveMembers() == null
381 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
382 updateGroup
.getAdmins() == null
384 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
385 updateGroup
.getRemoveAdmins() == null
387 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
388 updateGroup
.isResetGroupLink(),
389 updateGroup
.getGroupLinkState(),
390 updateGroup
.getAddMemberPermission(),
391 updateGroup
.getEditDetailsPermission(),
392 updateGroup
.getAvatarFile(),
393 updateGroup
.getExpirationTimer(),
394 updateGroup
.getIsAnnouncementGroup());
398 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
399 GroupInviteLinkUrl inviteLinkUrl
400 ) throws IOException
, InactiveGroupLinkException
{
401 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
404 private SendMessageResults
sendMessage(
405 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
406 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
407 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
408 long timestamp
= System
.currentTimeMillis();
409 messageBuilder
.withTimestamp(timestamp
);
410 for (final var recipient
: recipients
) {
411 if (recipient
instanceof RecipientIdentifier
.Single single
) {
413 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
414 final var result
= context
.getSendHelper().sendMessage(messageBuilder
, recipientId
);
415 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
416 } catch (UnregisteredRecipientException e
) {
417 results
.put(recipient
,
418 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
420 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
421 final var result
= context
.getSendHelper().sendSelfMessage(messageBuilder
);
422 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
423 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
424 final var result
= context
.getSendHelper().sendAsGroupMessage(messageBuilder
, group
.groupId());
425 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
428 return new SendMessageResults(timestamp
, results
);
431 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
432 return SendMessageResult
.from(result
,
433 account
.getRecipientStore(),
434 account
.getRecipientStore()::resolveRecipientAddress
);
437 private SendMessageResults
sendTypingMessage(
438 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
439 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
440 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
441 final var timestamp
= System
.currentTimeMillis();
442 for (var recipient
: recipients
) {
443 if (recipient
instanceof RecipientIdentifier
.Single single
) {
444 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
446 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
447 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
448 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
449 } catch (UnregisteredRecipientException e
) {
450 results
.put(recipient
,
451 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
453 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
454 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
455 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
456 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
457 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
460 return new SendMessageResults(timestamp
, results
);
464 public SendMessageResults
sendTypingMessage(
465 TypingAction action
, Set
<RecipientIdentifier
> recipients
466 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
467 return sendTypingMessage(action
.toSignalService(), recipients
);
471 public SendMessageResults
sendReadReceipt(
472 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
473 ) throws IOException
{
474 final var timestamp
= System
.currentTimeMillis();
475 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
479 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
483 public SendMessageResults
sendViewedReceipt(
484 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
485 ) throws IOException
{
486 final var timestamp
= System
.currentTimeMillis();
487 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
491 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
494 private SendMessageResults
sendReceiptMessage(
495 final RecipientIdentifier
.Single sender
,
496 final long timestamp
,
497 final SignalServiceReceiptMessage receiptMessage
498 ) throws IOException
{
500 final var result
= context
.getSendHelper()
501 .sendReceiptMessage(receiptMessage
, context
.getRecipientHelper().resolveRecipient(sender
));
502 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
503 } catch (UnregisteredRecipientException e
) {
504 return new SendMessageResults(timestamp
,
505 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
510 public SendMessageResults
sendMessage(
511 Message message
, Set
<RecipientIdentifier
> recipients
512 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
513 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
514 applyMessage(messageBuilder
, message
);
515 return sendMessage(messageBuilder
, recipients
);
518 private void applyMessage(
519 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
520 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
521 messageBuilder
.withBody(message
.messageText());
522 final var attachments
= message
.attachments();
523 if (attachments
!= null) {
524 messageBuilder
.withAttachments(context
.getAttachmentHelper().uploadAttachments(attachments
));
526 if (message
.mentions().size() > 0) {
527 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
529 if (message
.quote().isPresent()) {
530 final var quote
= message
.quote().get();
531 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
532 context
.getRecipientHelper()
533 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author())),
536 resolveMentions(quote
.mentions())));
538 if (message
.sticker().isPresent()) {
539 final var sticker
= message
.sticker().get();
540 final var packId
= StickerPackId
.deserialize(sticker
.packId());
541 final var stickerId
= sticker
.stickerId();
543 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
544 if (stickerPack
== null) {
545 throw new InvalidStickerException("Sticker pack not found");
547 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.getPackKey());
548 if (manifest
.stickers().size() <= stickerId
) {
549 throw new InvalidStickerException("Sticker id not part of this pack");
551 final var manifestSticker
= manifest
.stickers().get(stickerId
);
552 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
553 if (streamDetails
== null) {
554 throw new InvalidStickerException("Missing local sticker file");
556 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
557 stickerPack
.getPackKey(),
559 manifestSticker
.emoji(),
560 AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent())));
564 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws IOException
, UnregisteredRecipientException
{
565 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
566 for (final var m
: mentionList
) {
567 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
568 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
569 .resolveSignalServiceAddress(recipientId
)
570 .getAci(), m
.start(), m
.length()));
576 public SendMessageResults
sendRemoteDeleteMessage(
577 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
578 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
579 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
580 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
581 for (final var recipient
: recipients
) {
582 if (recipient
instanceof RecipientIdentifier
.Single r
) {
584 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
585 account
.getMessageSendLogStore().deleteEntryForRecipientNonGroup(targetSentTimestamp
, recipientId
);
586 } catch (UnregisteredRecipientException ignored
) {
588 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
589 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
592 return sendMessage(messageBuilder
, recipients
);
596 public SendMessageResults
sendMessageReaction(
599 RecipientIdentifier
.Single targetAuthor
,
600 long targetSentTimestamp
,
601 Set
<RecipientIdentifier
> recipients
602 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
603 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
604 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
606 context
.getRecipientHelper().resolveSignalServiceAddress(targetAuthorRecipientId
),
607 targetSentTimestamp
);
608 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
609 return sendMessage(messageBuilder
, recipients
);
613 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
614 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
617 return sendMessage(messageBuilder
,
618 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
619 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
620 throw new AssertionError(e
);
622 for (var recipient
: recipients
) {
623 final RecipientId recipientId
;
625 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
626 } catch (UnregisteredRecipientException e
) {
629 account
.getSessionStore().deleteAllSessions(recipientId
);
635 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
636 account
.removeRecipient(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
640 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
641 account
.getContactStore()
642 .deleteContact(account
.getRecipientStore().resolveRecipient(recipient
.toPartialRecipientAddress()));
646 public void setContactName(
647 RecipientIdentifier
.Single recipient
, String name
648 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
649 if (!account
.isMasterDevice()) {
650 throw new NotMasterDeviceException();
652 context
.getContactHelper().setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), name
);
656 public void setContactBlocked(
657 RecipientIdentifier
.Single recipient
, boolean blocked
658 ) throws NotMasterDeviceException
, IOException
, UnregisteredRecipientException
{
659 if (!account
.isMasterDevice()) {
660 throw new NotMasterDeviceException();
662 context
.getContactHelper().setContactBlocked(context
.getRecipientHelper().resolveRecipient(recipient
), blocked
);
663 // TODO cycle our profile key, if we're not together in a group with recipient
664 context
.getSyncHelper().sendBlockedList();
668 public void setGroupBlocked(
669 final GroupId groupId
, final boolean blocked
670 ) throws GroupNotFoundException
, NotMasterDeviceException
{
671 if (!account
.isMasterDevice()) {
672 throw new NotMasterDeviceException();
674 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
675 // TODO cycle our profile key
676 context
.getSyncHelper().sendBlockedList();
680 public void setExpirationTimer(
681 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
682 ) throws IOException
, UnregisteredRecipientException
{
683 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
684 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
685 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
687 sendMessage(messageBuilder
, Set
.of(recipient
));
688 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
689 throw new AssertionError(e
);
694 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
695 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
697 var messageSender
= dependencies
.getMessageSender();
699 var packKey
= KeyUtils
.createStickerUploadKey();
700 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
701 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
703 var sticker
= new Sticker(packId
, packKey
);
704 account
.getStickerStore().updateSticker(sticker
);
706 return new StickerPackUrl(packId
, packKey
);
710 public List
<StickerPack
> getStickerPacks() {
711 final var stickerPackStore
= context
.getStickerPackStore();
712 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
713 if (stickerPackStore
.existsStickerPack(pack
.getPackId())) {
715 final var manifest
= stickerPackStore
.retrieveManifest(pack
.getPackId());
716 return new StickerPack(pack
.getPackId(),
717 new StickerPackUrl(pack
.getPackId(), pack
.getPackKey()),
721 java
.util
.Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
722 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
723 } catch (Exception e
) {
724 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
728 return new StickerPack(pack
.getPackId(), pack
.getPackKey(), pack
.isInstalled());
733 public void requestAllSyncData() throws IOException
{
734 context
.getSyncHelper().requestAllSyncData();
735 retrieveRemoteStorage();
738 void retrieveRemoteStorage() throws IOException
{
739 if (account
.getStorageKey() != null) {
740 context
.getStorageHelper().readDataFromStorage();
745 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
746 if (isReceivingSynchronous
) {
747 throw new IllegalStateException("Already receiving message synchronously.");
749 synchronized (messageHandlers
) {
750 if (isWeakListener
) {
751 weakHandlers
.add(handler
);
753 messageHandlers
.add(handler
);
754 startReceiveThreadIfRequired();
759 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
761 private void startReceiveThreadIfRequired() {
762 if (receiveThread
!= null) {
765 receiveThread
= new Thread(() -> {
766 logger
.debug("Starting receiving messages");
767 while (!Thread
.interrupted()) {
769 context
.getReceiveHelper().receiveMessages(Duration
.ofMinutes(1), false, (envelope
, e
) -> {
770 synchronized (messageHandlers
) {
771 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
773 h
.handleMessage(envelope
, e
);
774 } catch (Exception ex
) {
775 logger
.warn("Message handler failed, ignoring", ex
);
781 } catch (IOException e
) {
782 logger
.warn("Receiving messages failed, retrying", e
);
785 logger
.debug("Finished receiving messages");
786 synchronized (messageHandlers
) {
787 receiveThread
= null;
789 // Check if in the meantime another handler has been registered
790 if (!messageHandlers
.isEmpty()) {
791 logger
.debug("Another handler has been registered, starting receive thread again");
792 startReceiveThreadIfRequired();
796 receiveThread
.setName("receive-" + threadNumber
.getAndIncrement());
798 receiveThread
.start();
802 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
804 synchronized (messageHandlers
) {
805 weakHandlers
.remove(handler
);
806 messageHandlers
.remove(handler
);
807 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
810 thread
= receiveThread
;
811 receiveThread
= null;
814 stopReceiveThread(thread
);
817 private void stopReceiveThread(final Thread thread
) {
821 } catch (InterruptedException ignored
) {
826 public boolean isReceiving() {
827 if (isReceivingSynchronous
) {
830 synchronized (messageHandlers
) {
831 return messageHandlers
.size() > 0;
836 public void receiveMessages(Duration timeout
, ReceiveMessageHandler handler
) throws IOException
{
837 receiveMessages(timeout
, true, handler
);
841 public void receiveMessages(ReceiveMessageHandler handler
) throws IOException
{
842 receiveMessages(Duration
.ofMinutes(1), false, handler
);
845 private void receiveMessages(
846 Duration timeout
, boolean returnOnTimeout
, ReceiveMessageHandler handler
847 ) throws IOException
{
849 throw new IllegalStateException("Already receiving message.");
851 isReceivingSynchronous
= true;
852 receiveThread
= Thread
.currentThread();
854 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, handler
);
856 receiveThread
= null;
857 isReceivingSynchronous
= false;
862 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
863 context
.getReceiveHelper().setIgnoreAttachments(ignoreAttachments
);
867 public boolean hasCaughtUpWithOldMessages() {
868 return context
.getReceiveHelper().hasCaughtUpWithOldMessages();
872 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
873 final RecipientId recipientId
;
875 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
876 } catch (IOException
| UnregisteredRecipientException e
) {
879 return context
.getContactHelper().isContactBlocked(recipientId
);
883 public void sendContacts() throws IOException
{
884 context
.getSyncHelper().sendContacts();
888 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
889 return account
.getContactStore()
892 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
897 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
898 final RecipientId recipientId
;
900 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
901 } catch (IOException
| UnregisteredRecipientException e
) {
905 final var contact
= account
.getContactStore().getContact(recipientId
);
906 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
907 return contact
.getName();
910 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
911 if (profile
!= null) {
912 return profile
.getDisplayName();
919 public Group
getGroup(GroupId groupId
) {
920 return toGroup(context
.getGroupHelper().getGroup(groupId
));
924 public List
<Identity
> getIdentities() {
925 return account
.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity
).toList();
928 private Identity
toIdentity(final IdentityInfo identityInfo
) {
929 if (identityInfo
== null) {
933 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
934 final var scannableFingerprint
= context
.getIdentityHelper()
935 .computeSafetyNumberForScanning(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey());
936 return new Identity(address
,
937 identityInfo
.getIdentityKey(),
938 context
.getIdentityHelper()
939 .computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
940 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
941 identityInfo
.getTrustLevel(),
942 identityInfo
.getDateAdded());
946 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
947 IdentityInfo identity
;
949 identity
= account
.getIdentityKeyStore()
950 .getIdentity(context
.getRecipientHelper().resolveRecipient(recipient
));
951 } catch (IOException
| UnregisteredRecipientException e
) {
954 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
958 public boolean trustIdentityVerified(
959 RecipientIdentifier
.Single recipient
, byte[] fingerprint
960 ) throws UnregisteredRecipientException
{
961 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
));
965 public boolean trustIdentityVerifiedSafetyNumber(
966 RecipientIdentifier
.Single recipient
, String safetyNumber
967 ) throws UnregisteredRecipientException
{
968 return trustIdentity(recipient
,
969 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
973 public boolean trustIdentityVerifiedSafetyNumber(
974 RecipientIdentifier
.Single recipient
, byte[] safetyNumber
975 ) throws UnregisteredRecipientException
{
976 return trustIdentity(recipient
,
977 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
));
981 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
982 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
985 private boolean trustIdentity(
986 RecipientIdentifier
.Single recipient
, Function
<RecipientId
, Boolean
> trustMethod
987 ) throws UnregisteredRecipientException
{
988 RecipientId recipientId
;
990 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
991 } catch (IOException e
) {
994 final var updated
= trustMethod
.apply(recipientId
);
995 if (updated
&& this.isReceiving()) {
996 context
.getReceiveHelper().setNeedsToRetryFailedMessages(true);
1002 public void addClosedListener(final Runnable listener
) {
1003 synchronized (closedListeners
) {
1004 closedListeners
.add(listener
);
1009 public void close() {
1011 synchronized (messageHandlers
) {
1012 weakHandlers
.clear();
1013 messageHandlers
.clear();
1014 thread
= receiveThread
;
1015 receiveThread
= null;
1017 if (thread
!= null) {
1018 stopReceiveThread(thread
);
1020 executor
.shutdown();
1022 dependencies
.getSignalWebSocket().disconnect();
1023 disposable
.dispose();
1025 synchronized (closedListeners
) {
1026 closedListeners
.forEach(Runnable
::run
);
1027 closedListeners
.clear();
1030 if (account
!= null) {