1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.manager
.Manager
;
5 import org
.asamk
.signal
.manager
.api
.AlreadyReceivingException
;
6 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
7 import org
.asamk
.signal
.manager
.api
.CaptchaRequiredException
;
8 import org
.asamk
.signal
.manager
.api
.Configuration
;
9 import org
.asamk
.signal
.manager
.api
.Contact
;
10 import org
.asamk
.signal
.manager
.api
.Device
;
11 import org
.asamk
.signal
.manager
.api
.DeviceLinkUrl
;
12 import org
.asamk
.signal
.manager
.api
.Group
;
13 import org
.asamk
.signal
.manager
.api
.GroupId
;
14 import org
.asamk
.signal
.manager
.api
.GroupInviteLinkUrl
;
15 import org
.asamk
.signal
.manager
.api
.GroupNotFoundException
;
16 import org
.asamk
.signal
.manager
.api
.GroupPermission
;
17 import org
.asamk
.signal
.manager
.api
.GroupSendingNotAllowedException
;
18 import org
.asamk
.signal
.manager
.api
.Identity
;
19 import org
.asamk
.signal
.manager
.api
.IdentityVerificationCode
;
20 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
21 import org
.asamk
.signal
.manager
.api
.IncorrectPinException
;
22 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
23 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
24 import org
.asamk
.signal
.manager
.api
.InvalidUsernameException
;
25 import org
.asamk
.signal
.manager
.api
.LastGroupAdminException
;
26 import org
.asamk
.signal
.manager
.api
.Message
;
27 import org
.asamk
.signal
.manager
.api
.MessageEnvelope
;
28 import org
.asamk
.signal
.manager
.api
.NonNormalizedPhoneNumberException
;
29 import org
.asamk
.signal
.manager
.api
.NotAGroupMemberException
;
30 import org
.asamk
.signal
.manager
.api
.NotPrimaryDeviceException
;
31 import org
.asamk
.signal
.manager
.api
.Pair
;
32 import org
.asamk
.signal
.manager
.api
.PinLockedException
;
33 import org
.asamk
.signal
.manager
.api
.RateLimitException
;
34 import org
.asamk
.signal
.manager
.api
.ReceiveConfig
;
35 import org
.asamk
.signal
.manager
.api
.Recipient
;
36 import org
.asamk
.signal
.manager
.api
.RecipientAddress
;
37 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
38 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
39 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
40 import org
.asamk
.signal
.manager
.api
.StickerPack
;
41 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
42 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
43 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
44 import org
.asamk
.signal
.manager
.api
.TypingAction
;
45 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
46 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
47 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
48 import org
.asamk
.signal
.manager
.api
.UserStatus
;
49 import org
.asamk
.signal
.manager
.api
.UsernameLinkUrl
;
50 import org
.freedesktop
.dbus
.DBusMap
;
51 import org
.freedesktop
.dbus
.DBusPath
;
52 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
53 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
54 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
55 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
56 import org
.freedesktop
.dbus
.interfaces
.DBusSigHandler
;
57 import org
.freedesktop
.dbus
.types
.Variant
;
60 import java
.io
.IOException
;
61 import java
.io
.InputStream
;
63 import java
.net
.URISyntaxException
;
64 import java
.time
.Duration
;
65 import java
.util
.ArrayList
;
66 import java
.util
.Collection
;
67 import java
.util
.HashMap
;
68 import java
.util
.HashSet
;
69 import java
.util
.List
;
71 import java
.util
.Objects
;
72 import java
.util
.Optional
;
74 import java
.util
.concurrent
.atomic
.AtomicInteger
;
75 import java
.util
.concurrent
.atomic
.AtomicLong
;
76 import java
.util
.function
.Function
;
77 import java
.util
.function
.Supplier
;
78 import java
.util
.stream
.Collectors
;
79 import java
.util
.stream
.Stream
;
82 * This class implements the Manager interface using the DBus Signal interface, where possible.
83 * It's used for the signal-cli dbus client mode (--dbus, --dbus-system)
85 public class DbusManagerImpl
implements Manager
{
87 private final Signal signal
;
88 private final DBusConnection connection
;
90 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
91 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
92 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
93 private final String busname
;
94 private DBusSigHandler
<Signal
.MessageReceivedV2
> dbusMsgHandler
;
95 private DBusSigHandler
<Signal
.EditMessageReceived
> dbusEditMsgHandler
;
96 private DBusSigHandler
<Signal
.ReceiptReceivedV2
> dbusRcptHandler
;
97 private DBusSigHandler
<Signal
.SyncMessageReceivedV2
> dbusSyncHandler
;
99 public DbusManagerImpl(final Signal signal
, DBusConnection connection
, final String busname
) {
100 this.signal
= signal
;
101 this.connection
= connection
;
102 this.busname
= busname
;
106 public String
getSelfNumber() {
107 return signal
.getSelfNumber();
111 public Map
<String
, UserStatus
> getUserStatus(final Set
<String
> numbers
) throws IOException
{
112 final var numbersList
= new ArrayList
<>(numbers
);
113 final var registered
= signal
.isRegistered(numbersList
);
115 final var result
= new HashMap
<String
, UserStatus
>();
116 for (var i
= 0; i
< numbersList
.size(); i
++) {
117 result
.put(numbersList
.get(i
),
118 new UserStatus(numbersList
.get(i
),
119 registered
.get(i
) ? RecipientAddress
.UNKNOWN_UUID
: null,
126 public void updateAccountAttributes(
127 final String deviceName
, final Boolean unrestrictedUnidentifiedSender
128 ) throws IOException
{
129 if (deviceName
!= null) {
130 final var devicePath
= signal
.getThisDevice();
131 getRemoteObject(devicePath
, Signal
.Device
.class).Set("org.asamk.Signal.Device", "Name", deviceName
);
136 public Configuration
getConfiguration() {
137 final var configuration
= getRemoteObject(new DBusPath(signal
.getObjectPath() + "/Configuration"),
138 Signal
.Configuration
.class).GetAll("org.asamk.Signal.Configuration");
139 return new Configuration(Optional
.of((Boolean
) configuration
.get("ReadReceipts").getValue()),
140 Optional
.of((Boolean
) configuration
.get("UnidentifiedDeliveryIndicators").getValue()),
141 Optional
.of((Boolean
) configuration
.get("TypingIndicators").getValue()),
142 Optional
.of((Boolean
) configuration
.get("LinkPreviews").getValue()));
146 public void updateConfiguration(Configuration newConfiguration
) {
147 final var configuration
= getRemoteObject(new DBusPath(signal
.getObjectPath() + "/Configuration"),
148 Signal
.Configuration
.class);
149 newConfiguration
.readReceipts()
150 .ifPresent(v
-> configuration
.Set("org.asamk.Signal.Configuration", "ReadReceipts", v
));
151 newConfiguration
.unidentifiedDeliveryIndicators()
152 .ifPresent(v
-> configuration
.Set("org.asamk.Signal.Configuration",
153 "UnidentifiedDeliveryIndicators",
155 newConfiguration
.typingIndicators()
156 .ifPresent(v
-> configuration
.Set("org.asamk.Signal.Configuration", "TypingIndicators", v
));
157 newConfiguration
.linkPreviews()
158 .ifPresent(v
-> configuration
.Set("org.asamk.Signal.Configuration", "LinkPreviews", v
));
162 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
163 signal
.updateProfile(emptyIfNull(updateProfile
.getGivenName()),
164 emptyIfNull(updateProfile
.getFamilyName()),
165 emptyIfNull(updateProfile
.getAbout()),
166 emptyIfNull(updateProfile
.getAboutEmoji()),
167 updateProfile
.getAvatar() == null ?
"" : updateProfile
.getAvatar(),
168 updateProfile
.isDeleteAvatar());
172 public String
getUsername() {
173 throw new UnsupportedOperationException();
177 public UsernameLinkUrl
getUsernameLink() {
178 throw new UnsupportedOperationException();
182 public void setUsername(final String username
) throws IOException
, InvalidUsernameException
{
183 throw new UnsupportedOperationException();
187 public void deleteUsername() throws IOException
{
188 throw new UnsupportedOperationException();
192 public void startChangeNumber(
193 final String newNumber
, final boolean voiceVerification
, final String captcha
194 ) throws RateLimitException
, IOException
, CaptchaRequiredException
, NonNormalizedPhoneNumberException
{
195 throw new UnsupportedOperationException();
199 public void finishChangeNumber(
200 final String newNumber
, final String verificationCode
, final String pin
201 ) throws IncorrectPinException
, PinLockedException
, IOException
{
202 throw new UnsupportedOperationException();
206 public void unregister() throws IOException
{
211 public void deleteAccount() throws IOException
{
212 signal
.deleteAccount();
216 public void submitRateLimitRecaptchaChallenge(final String challenge
, final String captcha
) throws IOException
{
217 signal
.submitRateLimitChallenge(challenge
, captcha
);
221 public List
<Device
> getLinkedDevices() throws IOException
{
222 final var thisDevice
= signal
.getThisDevice();
223 return signal
.listDevices().stream().map(d
-> {
224 final var device
= getRemoteObject(d
.getObjectPath(),
225 Signal
.Device
.class).GetAll("org.asamk.Signal.Device");
226 return new Device((Integer
) device
.get("Id").getValue(),
227 (String
) device
.get("Name").getValue(),
228 (long) device
.get("Created").getValue(),
229 (long) device
.get("LastSeen").getValue(),
230 thisDevice
.equals(d
.getObjectPath()));
235 public void removeLinkedDevices(final int deviceId
) throws IOException
{
236 final var devicePath
= signal
.getDevice(deviceId
);
237 getRemoteObject(devicePath
, Signal
.Device
.class).removeDevice();
241 public void addDeviceLink(final DeviceLinkUrl linkUri
) throws IOException
, InvalidDeviceLinkException
{
242 signal
.addDevice(linkUri
.createDeviceLinkUri().toString());
246 public void setRegistrationLockPin(final Optional
<String
> pin
) throws IOException
{
247 if (pin
.isPresent()) {
248 signal
.setPin(pin
.get());
255 public List
<Group
> getGroups() {
256 final var groups
= signal
.listGroups();
257 return groups
.stream().map(Signal
.StructGroup
::getObjectPath
).map(this::getGroup
).toList();
261 public SendGroupMessageResults
quitGroup(
262 final GroupId groupId
, final Set
<RecipientIdentifier
.Single
> groupAdmins
263 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
264 if (!groupAdmins
.isEmpty()) {
265 throw new UnsupportedOperationException();
267 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
270 } catch (Signal
.Error
.GroupNotFound e
) {
271 throw new GroupNotFoundException(groupId
);
272 } catch (Signal
.Error
.NotAGroupMember e
) {
273 throw new NotAGroupMemberException(groupId
, group
.Get("org.asamk.Signal.Group", "Name"));
274 } catch (Signal
.Error
.LastGroupAdmin e
) {
275 throw new LastGroupAdminException(groupId
, group
.Get("org.asamk.Signal.Group", "Name"));
277 return new SendGroupMessageResults(0, List
.of());
281 public void deleteGroup(final GroupId groupId
) throws IOException
{
282 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
287 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
288 final String name
, final Set
<RecipientIdentifier
.Single
> members
, final String avatarFile
289 ) throws IOException
, AttachmentInvalidException
{
290 final var newGroupId
= signal
.createGroup(emptyIfNull(name
),
291 members
.stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList(),
292 avatarFile
== null ?
"" : avatarFile
);
293 return new Pair
<>(GroupId
.unknownVersion(newGroupId
), new SendGroupMessageResults(0, List
.of()));
297 public SendGroupMessageResults
updateGroup(
298 final GroupId groupId
, final UpdateGroup updateGroup
299 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
300 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
301 if (updateGroup
.getName() != null) {
302 group
.Set("org.asamk.Signal.Group", "Name", updateGroup
.getName());
304 if (updateGroup
.getDescription() != null) {
305 group
.Set("org.asamk.Signal.Group", "Description", updateGroup
.getDescription());
307 if (updateGroup
.getAvatarFile() != null) {
308 group
.Set("org.asamk.Signal.Group",
310 updateGroup
.getAvatarFile() == null ?
"" : updateGroup
.getAvatarFile());
312 if (updateGroup
.getExpirationTimer() != null) {
313 group
.Set("org.asamk.Signal.Group", "MessageExpirationTimer", updateGroup
.getExpirationTimer());
315 if (updateGroup
.getAddMemberPermission() != null) {
316 group
.Set("org.asamk.Signal.Group", "PermissionAddMember", updateGroup
.getAddMemberPermission().name());
318 if (updateGroup
.getEditDetailsPermission() != null) {
319 group
.Set("org.asamk.Signal.Group", "PermissionEditDetails", updateGroup
.getEditDetailsPermission().name());
321 if (updateGroup
.getIsAnnouncementGroup() != null) {
322 group
.Set("org.asamk.Signal.Group",
323 "PermissionSendMessage",
324 updateGroup
.getIsAnnouncementGroup()
325 ? GroupPermission
.ONLY_ADMINS
.name()
326 : GroupPermission
.EVERY_MEMBER
.name());
328 if (updateGroup
.getMembers() != null) {
329 group
.addMembers(updateGroup
.getMembers().stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList());
331 if (updateGroup
.getRemoveMembers() != null) {
332 group
.removeMembers(updateGroup
.getRemoveMembers()
334 .map(RecipientIdentifier
.Single
::getIdentifier
)
337 if (updateGroup
.getAdmins() != null) {
338 group
.addAdmins(updateGroup
.getAdmins().stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList());
340 if (updateGroup
.getRemoveAdmins() != null) {
341 group
.removeAdmins(updateGroup
.getRemoveAdmins()
343 .map(RecipientIdentifier
.Single
::getIdentifier
)
346 if (updateGroup
.isResetGroupLink()) {
349 if (updateGroup
.getGroupLinkState() != null) {
350 switch (updateGroup
.getGroupLinkState()) {
351 case DISABLED
-> group
.disableLink();
352 case ENABLED
-> group
.enableLink(false);
353 case ENABLED_WITH_APPROVAL
-> group
.enableLink(true);
356 return new SendGroupMessageResults(0, List
.of());
360 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(final GroupInviteLinkUrl inviteLinkUrl
) throws IOException
, InactiveGroupLinkException
{
362 final var newGroupId
= signal
.joinGroup(inviteLinkUrl
.getUrl());
363 return new Pair
<>(GroupId
.unknownVersion(newGroupId
), new SendGroupMessageResults(0, List
.of()));
364 } catch (DBusExecutionException e
) {
365 throw new IOException("Failed to join group: " + e
.getMessage() + " (" + e
.getClass().getSimpleName() + ")",
371 public SendMessageResults
sendTypingMessage(
372 final TypingAction action
, final Set
<RecipientIdentifier
> recipients
373 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
374 return handleMessage(recipients
, numbers
-> {
375 numbers
.forEach(n
-> signal
.sendTyping(n
, action
== TypingAction
.STOP
));
378 signal
.sendTyping(signal
.getSelfNumber(), action
== TypingAction
.STOP
);
381 signal
.sendGroupTyping(groupId
, action
== TypingAction
.STOP
);
387 public SendMessageResults
sendReadReceipt(
388 final RecipientIdentifier
.Single sender
, final List
<Long
> messageIds
390 signal
.sendReadReceipt(sender
.getIdentifier(), messageIds
);
391 return new SendMessageResults(0, Map
.of());
395 public SendMessageResults
sendViewedReceipt(
396 final RecipientIdentifier
.Single sender
, final List
<Long
> messageIds
398 signal
.sendViewedReceipt(sender
.getIdentifier(), messageIds
);
399 return new SendMessageResults(0, Map
.of());
403 public SendMessageResults
sendMessage(
404 final Message message
, final Set
<RecipientIdentifier
> recipients
, final boolean notifySelf
405 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
406 return handleMessage(recipients
,
407 numbers
-> signal
.sendMessage(message
.messageText(), message
.attachments(), numbers
),
408 () -> signal
.sendNoteToSelfMessage(message
.messageText(), message
.attachments()),
409 groupId
-> signal
.sendGroupMessage(message
.messageText(), message
.attachments(), groupId
));
413 public SendMessageResults
sendEditMessage(
414 final Message message
, final Set
<RecipientIdentifier
> recipients
, final long editTargetTimestamp
415 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
416 throw new UnsupportedOperationException();
420 public SendMessageResults
sendRemoteDeleteMessage(
421 final long targetSentTimestamp
, final Set
<RecipientIdentifier
> recipients
422 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
423 return handleMessage(recipients
,
424 numbers
-> signal
.sendRemoteDeleteMessage(targetSentTimestamp
, numbers
),
425 () -> signal
.sendRemoteDeleteMessage(targetSentTimestamp
, signal
.getSelfNumber()),
426 groupId
-> signal
.sendGroupRemoteDeleteMessage(targetSentTimestamp
, groupId
));
430 public SendMessageResults
sendMessageReaction(
432 final boolean remove
,
433 final RecipientIdentifier
.Single targetAuthor
,
434 final long targetSentTimestamp
,
435 final Set
<RecipientIdentifier
> recipients
,
436 final boolean isStory
437 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
438 return handleMessage(recipients
,
439 numbers
-> signal
.sendMessageReaction(emoji
,
441 targetAuthor
.getIdentifier(),
444 () -> signal
.sendMessageReaction(emoji
,
446 targetAuthor
.getIdentifier(),
448 signal
.getSelfNumber()),
449 groupId
-> signal
.sendGroupMessageReaction(emoji
,
451 targetAuthor
.getIdentifier(),
457 public SendMessageResults
sendPaymentNotificationMessage(
458 final byte[] receipt
, final String note
, final RecipientIdentifier
.Single recipient
459 ) throws IOException
{
460 final var timestamp
= signal
.sendPaymentNotification(receipt
, note
, recipient
.getIdentifier());
461 return new SendMessageResults(timestamp
, Map
.of());
465 public SendMessageResults
sendEndSessionMessage(final Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
466 signal
.sendEndSessionMessage(recipients
.stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList());
467 return new SendMessageResults(0, Map
.of());
470 public void hideRecipient(final RecipientIdentifier
.Single recipient
) {
471 throw new UnsupportedOperationException();
475 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
476 signal
.deleteRecipient(recipient
.getIdentifier());
480 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
481 signal
.deleteContact(recipient
.getIdentifier());
485 public void setContactName(
486 final RecipientIdentifier
.Single recipient
, final String givenName
, final String familyName
487 ) throws NotPrimaryDeviceException
{
488 signal
.setContactName(recipient
.getIdentifier(), givenName
);
492 public void setContactsBlocked(
493 final Collection
<RecipientIdentifier
.Single
> recipients
, final boolean blocked
494 ) throws NotPrimaryDeviceException
, IOException
{
495 for (final var recipient
: recipients
) {
496 signal
.setContactBlocked(recipient
.getIdentifier(), blocked
);
501 public void setGroupsBlocked(
502 final Collection
<GroupId
> groupIds
, final boolean blocked
503 ) throws GroupNotFoundException
, IOException
{
504 for (final var groupId
: groupIds
) {
505 setGroupProperty(groupId
, "IsBlocked", blocked
);
509 private void setGroupProperty(final GroupId groupId
, final String propertyName
, final boolean blocked
) {
510 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
511 group
.Set("org.asamk.Signal.Group", propertyName
, blocked
);
515 public void setExpirationTimer(
516 final RecipientIdentifier
.Single recipient
, final int messageExpirationTimer
517 ) throws IOException
{
518 signal
.setExpirationTimer(recipient
.getIdentifier(), messageExpirationTimer
);
522 public StickerPackUrl
uploadStickerPack(final File path
) throws IOException
, StickerPackInvalidException
{
524 return StickerPackUrl
.fromUri(new URI(signal
.uploadStickerPack(path
.getPath())));
525 } catch (URISyntaxException
| StickerPackUrl
.InvalidStickerPackLinkException e
) {
526 throw new AssertionError(e
);
531 public void installStickerPack(final StickerPackUrl url
) throws IOException
{
532 throw new UnsupportedOperationException();
536 public List
<StickerPack
> getStickerPacks() {
537 throw new UnsupportedOperationException();
541 public void requestAllSyncData() throws IOException
{
542 signal
.sendSyncRequest();
546 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
547 synchronized (messageHandlers
) {
548 if (isWeakListener
) {
549 weakHandlers
.add(handler
);
551 if (messageHandlers
.isEmpty()) {
552 installMessageHandlers();
554 messageHandlers
.add(handler
);
560 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
561 synchronized (messageHandlers
) {
562 weakHandlers
.remove(handler
);
563 messageHandlers
.remove(handler
);
564 if (messageHandlers
.isEmpty()) {
565 uninstallMessageHandlers();
571 public boolean isReceiving() {
572 synchronized (messageHandlers
) {
573 return !messageHandlers
.isEmpty();
577 private Thread receiveThread
;
580 public void receiveMessages(
581 Optional
<Duration
> timeout
, Optional
<Integer
> maxMessages
, ReceiveMessageHandler handler
582 ) throws IOException
, AlreadyReceivingException
{
583 if (receiveThread
!= null) {
584 throw new AlreadyReceivingException("Already receiving message.");
586 receiveThread
= Thread
.currentThread();
588 final var remainingMessages
= new AtomicInteger(maxMessages
.orElse(-1));
589 final var lastMessage
= new AtomicLong(System
.currentTimeMillis());
590 final var thread
= Thread
.currentThread();
592 final ReceiveMessageHandler receiveHandler
= (envelope
, e
) -> {
593 lastMessage
.set(System
.currentTimeMillis());
594 handler
.handleMessage(envelope
, e
);
595 if (remainingMessages
.get() > 0) {
596 if (remainingMessages
.decrementAndGet() <= 0) {
597 remainingMessages
.set(0);
602 addReceiveHandler(receiveHandler
);
603 if (timeout
.isPresent()) {
604 while (remainingMessages
.get() != 0) {
606 final var passedTime
= System
.currentTimeMillis() - lastMessage
.get();
607 final var sleepTimeRemaining
= timeout
.get().toMillis() - passedTime
;
608 if (sleepTimeRemaining
< 0) {
611 Thread
.sleep(sleepTimeRemaining
);
612 } catch (InterruptedException ignored
) {
618 synchronized (this) {
621 } catch (InterruptedException ignored
) {
625 removeReceiveHandler(receiveHandler
);
626 receiveThread
= null;
630 public void stopReceiveMessages() {
631 if (receiveThread
!= null) {
632 receiveThread
.interrupt();
637 public void setReceiveConfig(final ReceiveConfig receiveConfig
) {
641 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
642 return signal
.isContactBlocked(recipient
.getIdentifier());
646 public void sendContacts() throws IOException
{
647 signal
.sendContacts();
651 public List
<Recipient
> getRecipients(
652 final boolean onlyContacts
,
653 final Optional
<Boolean
> blocked
,
654 final Collection
<RecipientIdentifier
.Single
> addresses
,
655 final Optional
<String
> name
657 final var numbers
= addresses
.stream()
658 .filter(s
-> s
instanceof RecipientIdentifier
.Number
)
659 .map(s
-> ((RecipientIdentifier
.Number
) s
).number())
660 .collect(Collectors
.toSet());
661 return signal
.listNumbers().stream().filter(n
-> addresses
.isEmpty() || numbers
.contains(n
)).map(n
-> {
662 final var contactBlocked
= signal
.isContactBlocked(n
);
663 if (blocked
.isPresent() && blocked
.get() != contactBlocked
) {
666 final var contactName
= signal
.getContactName(n
);
667 if (onlyContacts
&& contactName
.isEmpty()) {
670 if (name
.isPresent() && !name
.get().equals(contactName
)) {
673 return Recipient
.newBuilder()
674 .withAddress(new RecipientAddress(null, n
))
675 .withContact(new Contact(contactName
,
688 }).filter(Objects
::nonNull
).toList();
692 public String
getContactOrProfileName(final RecipientIdentifier
.Single recipient
) {
693 return signal
.getContactName(recipient
.getIdentifier());
697 public Group
getGroup(final GroupId groupId
) {
698 final var groupPath
= signal
.getGroup(groupId
.serialize());
699 return getGroup(groupPath
);
702 @SuppressWarnings("unchecked")
703 private Group
getGroup(final DBusPath groupPath
) {
704 final var group
= getRemoteObject(groupPath
, Signal
.Group
.class).GetAll("org.asamk.Signal.Group");
705 final var id
= (byte[]) group
.get("Id").getValue();
707 return new Group(GroupId
.unknownVersion(id
),
708 (String
) group
.get("Name").getValue(),
709 (String
) group
.get("Description").getValue(),
710 GroupInviteLinkUrl
.fromUri((String
) group
.get("GroupInviteLink").getValue()),
711 ((List
<String
>) group
.get("Members").getValue()).stream()
712 .map(m
-> new RecipientAddress(null, m
))
713 .collect(Collectors
.toSet()),
714 ((List
<String
>) group
.get("PendingMembers").getValue()).stream()
715 .map(m
-> new RecipientAddress(null, m
))
716 .collect(Collectors
.toSet()),
717 ((List
<String
>) group
.get("RequestingMembers").getValue()).stream()
718 .map(m
-> new RecipientAddress(null, m
))
719 .collect(Collectors
.toSet()),
720 ((List
<String
>) group
.get("Admins").getValue()).stream()
721 .map(m
-> new RecipientAddress(null, m
))
722 .collect(Collectors
.toSet()),
723 ((List
<String
>) group
.get("Banned").getValue()).stream()
724 .map(m
-> new RecipientAddress(null, m
))
725 .collect(Collectors
.toSet()),
726 (boolean) group
.get("IsBlocked").getValue(),
727 (int) group
.get("MessageExpirationTimer").getValue(),
728 GroupPermission
.valueOf((String
) group
.get("PermissionAddMember").getValue()),
729 GroupPermission
.valueOf((String
) group
.get("PermissionEditDetails").getValue()),
730 GroupPermission
.valueOf((String
) group
.get("PermissionSendMessage").getValue()),
731 (boolean) group
.get("IsMember").getValue(),
732 (boolean) group
.get("IsAdmin").getValue());
733 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
734 throw new AssertionError(e
);
739 public List
<Identity
> getIdentities() {
740 throw new UnsupportedOperationException();
744 public List
<Identity
> getIdentities(final RecipientIdentifier
.Single recipient
) {
745 throw new UnsupportedOperationException();
749 public boolean trustIdentityVerified(
750 final RecipientIdentifier
.Single recipient
, final IdentityVerificationCode verificationCode
752 throw new UnsupportedOperationException();
756 public boolean trustIdentityAllKeys(final RecipientIdentifier
.Single recipient
) {
757 throw new UnsupportedOperationException();
761 public void addAddressChangedListener(final Runnable listener
) {
765 public void addClosedListener(final Runnable listener
) {
766 synchronized (closedListeners
) {
767 closedListeners
.add(listener
);
772 public void close() {
773 synchronized (this) {
776 synchronized (messageHandlers
) {
777 if (!messageHandlers
.isEmpty()) {
778 uninstallMessageHandlers();
780 weakHandlers
.clear();
781 messageHandlers
.clear();
783 synchronized (closedListeners
) {
784 closedListeners
.forEach(Runnable
::run
);
785 closedListeners
.clear();
789 private SendMessageResults
handleMessage(
790 Set
<RecipientIdentifier
> recipients
,
791 Function
<List
<String
>, Long
> recipientsHandler
,
792 Supplier
<Long
> noteToSelfHandler
,
793 Function
<byte[], Long
> groupHandler
796 final var singleRecipients
= recipients
.stream()
797 .filter(r
-> r
instanceof RecipientIdentifier
.Single
)
798 .map(RecipientIdentifier
.Single
.class::cast
)
799 .map(RecipientIdentifier
.Single
::getIdentifier
)
801 if (!singleRecipients
.isEmpty()) {
802 timestamp
= recipientsHandler
.apply(singleRecipients
);
805 if (recipients
.contains(RecipientIdentifier
.NoteToSelf
.INSTANCE
)) {
806 timestamp
= noteToSelfHandler
.get();
808 final var groupRecipients
= recipients
.stream()
809 .filter(r
-> r
instanceof RecipientIdentifier
.Group
)
810 .map(RecipientIdentifier
.Group
.class::cast
)
811 .map(RecipientIdentifier
.Group
::groupId
)
813 for (final var groupId
: groupRecipients
) {
814 timestamp
= groupHandler
.apply(groupId
.serialize());
816 return new SendMessageResults(timestamp
, Map
.of());
819 private String
emptyIfNull(final String string
) {
820 return string
== null ?
"" : string
;
823 private <T
extends DBusInterface
> T
getRemoteObject(final DBusPath path
, final Class
<T
> type
) {
825 return connection
.getRemoteObject(busname
, path
.getPath(), type
);
826 } catch (DBusException e
) {
827 throw new AssertionError(e
);
831 private void installMessageHandlers() {
833 this.dbusMsgHandler
= messageReceived
-> {
834 final var extras
= messageReceived
.getExtras();
835 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
836 messageReceived
.getSender())),
838 messageReceived
.getTimestamp(),
844 Optional
.of(new MessageEnvelope
.Data(messageReceived
.getTimestamp(),
845 messageReceived
.getGroupId().length
> 0
846 ? Optional
.of(new MessageEnvelope
.Data
.GroupContext(GroupId
.unknownVersion(
847 messageReceived
.getGroupId()), false, 0))
851 Optional
.of(messageReceived
.getMessage()),
861 getAttachments(extras
),
872 notifyMessageHandlers(envelope
);
874 connection
.addSigHandler(Signal
.MessageReceivedV2
.class, signal
, this.dbusMsgHandler
);
875 this.dbusEditMsgHandler
= messageReceived
-> {
876 final var extras
= messageReceived
.getExtras();
877 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
878 messageReceived
.getSender())),
880 messageReceived
.getTimestamp(),
887 Optional
.of(new MessageEnvelope
.Edit(messageReceived
.getTargetSentTimestamp(),
888 new MessageEnvelope
.Data(messageReceived
.getTimestamp(),
889 messageReceived
.getGroupId().length
> 0
890 ? Optional
.of(new MessageEnvelope
.Data
.GroupContext(GroupId
.unknownVersion(
891 messageReceived
.getGroupId()), false, 0))
895 Optional
.of(messageReceived
.getMessage()),
905 getAttachments(extras
),
915 notifyMessageHandlers(envelope
);
917 connection
.addSigHandler(Signal
.EditMessageReceived
.class, signal
, this.dbusEditMsgHandler
);
919 this.dbusRcptHandler
= receiptReceived
-> {
920 final var type
= switch (receiptReceived
.getReceiptType()) {
921 case "read" -> MessageEnvelope
.Receipt
.Type
.READ
;
922 case "viewed" -> MessageEnvelope
.Receipt
.Type
.VIEWED
;
923 case "delivery" -> MessageEnvelope
.Receipt
.Type
.DELIVERY
;
924 default -> MessageEnvelope
.Receipt
.Type
.UNKNOWN
;
926 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
927 receiptReceived
.getSender())),
929 receiptReceived
.getTimestamp(),
933 Optional
.of(new MessageEnvelope
.Receipt(receiptReceived
.getTimestamp(),
935 List
.of(receiptReceived
.getTimestamp()))),
942 notifyMessageHandlers(envelope
);
944 connection
.addSigHandler(Signal
.ReceiptReceivedV2
.class, signal
, this.dbusRcptHandler
);
946 this.dbusSyncHandler
= syncReceived
-> {
947 final var extras
= syncReceived
.getExtras();
948 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
949 syncReceived
.getSource())),
951 syncReceived
.getTimestamp(),
959 Optional
.of(new MessageEnvelope
.Sync(Optional
.of(new MessageEnvelope
.Sync
.Sent(syncReceived
.getTimestamp(),
960 syncReceived
.getTimestamp(),
961 syncReceived
.getDestination().isEmpty()
963 : Optional
.of(new RecipientAddress(null, syncReceived
.getDestination())),
965 Optional
.of(new MessageEnvelope
.Data(syncReceived
.getTimestamp(),
966 syncReceived
.getGroupId().length
> 0
967 ? Optional
.of(new MessageEnvelope
.Data
.GroupContext(GroupId
.unknownVersion(
968 syncReceived
.getGroupId()), false, 0))
972 Optional
.of(syncReceived
.getMessage()),
982 getAttachments(extras
),
1000 notifyMessageHandlers(envelope
);
1002 connection
.addSigHandler(Signal
.SyncMessageReceivedV2
.class, signal
, this.dbusSyncHandler
);
1003 } catch (DBusException e
) {
1004 throw new RuntimeException(e
);
1006 signal
.subscribeReceive();
1009 private void notifyMessageHandlers(final MessageEnvelope envelope
) {
1010 synchronized (messageHandlers
) {
1011 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream())
1012 .forEach(h
-> h
.handleMessage(envelope
, null));
1016 private void uninstallMessageHandlers() {
1018 signal
.unsubscribeReceive();
1019 connection
.removeSigHandler(Signal
.MessageReceivedV2
.class, signal
, this.dbusMsgHandler
);
1020 connection
.removeSigHandler(Signal
.EditMessageReceived
.class, signal
, this.dbusEditMsgHandler
);
1021 connection
.removeSigHandler(Signal
.ReceiptReceivedV2
.class, signal
, this.dbusRcptHandler
);
1022 connection
.removeSigHandler(Signal
.SyncMessageReceivedV2
.class, signal
, this.dbusSyncHandler
);
1023 } catch (DBusException e
) {
1024 throw new RuntimeException(e
);
1028 private List
<MessageEnvelope
.Data
.Attachment
> getAttachments(final Map
<String
, Variant
<?
>> extras
) {
1029 if (!extras
.containsKey("attachments")) {
1033 final List
<DBusMap
<String
, Variant
<?
>>> attachments
= getValue(extras
, "attachments");
1034 return attachments
.stream().map(a
-> {
1035 final String file
= a
.containsKey("file") ?
getValue(a
, "file") : null;
1036 return new MessageEnvelope
.Data
.Attachment(a
.containsKey("remoteId")
1037 ? Optional
.of(getValue(a
, "remoteId"))
1039 file
!= null ? Optional
.of(new File(file
)) : Optional
.empty(),
1041 getValue(a
, "contentType"),
1049 getValue(a
, "isVoiceNote"),
1050 getValue(a
, "isGif"),
1051 getValue(a
, "isBorderless"));
1055 private List
<MessageEnvelope
.Data
.Mention
> getMentions(final Map
<String
, Variant
<?
>> extras
) {
1056 if (!extras
.containsKey("mentions")) {
1060 final List
<DBusMap
<String
, Variant
<?
>>> mentions
= getValue(extras
, "mentions");
1061 return mentions
.stream()
1062 .map(a
-> new MessageEnvelope
.Data
.Mention(new RecipientAddress(null, getValue(a
, "recipient")),
1063 getValue(a
, "start"),
1064 getValue(a
, "length")))
1069 public InputStream
retrieveAttachment(final String id
) throws IOException
{
1070 throw new UnsupportedOperationException();
1074 public InputStream
retrieveContactAvatar(final RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
1075 throw new UnsupportedOperationException();
1079 public InputStream
retrieveProfileAvatar(final RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
1080 throw new UnsupportedOperationException();
1084 public InputStream
retrieveGroupAvatar(final GroupId groupId
) throws IOException
{
1085 throw new UnsupportedOperationException();
1089 public InputStream
retrieveSticker(final StickerPackId stickerPackId
, final int stickerId
) throws IOException
{
1090 throw new UnsupportedOperationException();
1093 @SuppressWarnings("unchecked")
1094 private <T
> T
getValue(
1095 final Map
<String
, Variant
<?
>> stringVariantMap
, final String field
1097 return (T
) stringVariantMap
.get(field
).getValue();