1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.DbusConfig
;
5 import org
.asamk
.signal
.manager
.AttachmentInvalidException
;
6 import org
.asamk
.signal
.manager
.Manager
;
7 import org
.asamk
.signal
.manager
.NotMasterDeviceException
;
8 import org
.asamk
.signal
.manager
.StickerPackInvalidException
;
9 import org
.asamk
.signal
.manager
.api
.Configuration
;
10 import org
.asamk
.signal
.manager
.api
.Device
;
11 import org
.asamk
.signal
.manager
.api
.Group
;
12 import org
.asamk
.signal
.manager
.api
.Identity
;
13 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
14 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
15 import org
.asamk
.signal
.manager
.api
.Message
;
16 import org
.asamk
.signal
.manager
.api
.MessageEnvelope
;
17 import org
.asamk
.signal
.manager
.api
.Pair
;
18 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
19 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
20 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
21 import org
.asamk
.signal
.manager
.api
.TypingAction
;
22 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
23 import org
.asamk
.signal
.manager
.groups
.GroupId
;
24 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
25 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
26 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
27 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
28 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
29 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
30 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
31 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
32 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
33 import org
.freedesktop
.dbus
.DBusMap
;
34 import org
.freedesktop
.dbus
.DBusPath
;
35 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
36 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
37 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
38 import org
.freedesktop
.dbus
.interfaces
.DBusSigHandler
;
39 import org
.freedesktop
.dbus
.types
.Variant
;
42 import java
.io
.IOException
;
44 import java
.net
.URISyntaxException
;
45 import java
.util
.ArrayList
;
46 import java
.util
.HashMap
;
47 import java
.util
.HashSet
;
48 import java
.util
.List
;
50 import java
.util
.Optional
;
52 import java
.util
.UUID
;
53 import java
.util
.concurrent
.TimeUnit
;
54 import java
.util
.function
.Function
;
55 import java
.util
.function
.Supplier
;
56 import java
.util
.stream
.Collectors
;
57 import java
.util
.stream
.Stream
;
60 * This class implements the Manager interface using the DBus Signal interface, where possible.
61 * It's used for the signal-cli dbus client mode (--dbus, --dbus-system)
63 public class DbusManagerImpl
implements Manager
{
65 private final Signal signal
;
66 private final DBusConnection connection
;
68 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
69 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
70 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
71 private DBusSigHandler
<Signal
.MessageReceivedV2
> dbusMsgHandler
;
72 private DBusSigHandler
<Signal
.ReceiptReceivedV2
> dbusRcptHandler
;
73 private DBusSigHandler
<Signal
.SyncMessageReceivedV2
> dbusSyncHandler
;
75 public DbusManagerImpl(final Signal signal
, DBusConnection connection
) {
77 this.connection
= connection
;
81 public String
getSelfNumber() {
82 return signal
.getSelfNumber();
86 public void checkAccountState() throws IOException
{
87 throw new UnsupportedOperationException();
91 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(final Set
<String
> numbers
) throws IOException
{
92 final var numbersList
= new ArrayList
<>(numbers
);
93 final var registered
= signal
.isRegistered(numbersList
);
95 final var result
= new HashMap
<String
, Pair
<String
, UUID
>>();
96 for (var i
= 0; i
< numbersList
.size(); i
++) {
97 result
.put(numbersList
.get(i
),
98 new Pair
<>(numbersList
.get(i
), registered
.get(i
) ? RecipientAddress
.UNKNOWN_UUID
: null));
104 public void updateAccountAttributes(final String deviceName
) throws IOException
{
105 if (deviceName
!= null) {
106 final var devicePath
= signal
.getThisDevice();
107 getRemoteObject(devicePath
, Signal
.Device
.class).Set("org.asamk.Signal.Device", "Name", deviceName
);
112 public Configuration
getConfiguration() {
113 throw new UnsupportedOperationException();
117 public void updateConfiguration(Configuration configuration
) throws IOException
{
118 throw new UnsupportedOperationException();
122 public void setProfile(
123 final String givenName
,
124 final String familyName
,
126 final String aboutEmoji
,
127 final Optional
<File
> avatar
128 ) throws IOException
{
129 signal
.updateProfile(emptyIfNull(givenName
),
130 emptyIfNull(familyName
),
132 emptyIfNull(aboutEmoji
),
133 avatar
== null ?
"" : avatar
.map(File
::getPath
).orElse(""),
134 avatar
!= null && avatar
.isEmpty());
138 public void unregister() throws IOException
{
139 throw new UnsupportedOperationException();
143 public void deleteAccount() throws IOException
{
144 throw new UnsupportedOperationException();
148 public void submitRateLimitRecaptchaChallenge(final String challenge
, final String captcha
) throws IOException
{
149 signal
.submitRateLimitChallenge(challenge
, captcha
);
153 public List
<Device
> getLinkedDevices() throws IOException
{
154 final var thisDevice
= signal
.getThisDevice();
155 return signal
.listDevices().stream().map(d
-> {
156 final var device
= getRemoteObject(d
.getObjectPath(),
157 Signal
.Device
.class).GetAll("org.asamk.Signal.Device");
158 return new Device((long) device
.get("Id").getValue(),
159 (String
) device
.get("Name").getValue(),
160 (long) device
.get("Created").getValue(),
161 (long) device
.get("LastSeen").getValue(),
162 thisDevice
.equals(d
.getObjectPath()));
167 public void removeLinkedDevices(final long deviceId
) throws IOException
{
168 final var devicePath
= signal
.getDevice(deviceId
);
169 getRemoteObject(devicePath
, Signal
.Device
.class).removeDevice();
173 public void addDeviceLink(final URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
174 signal
.addDevice(linkUri
.toString());
178 public void setRegistrationLockPin(final Optional
<String
> pin
) throws IOException
{
179 if (pin
.isPresent()) {
180 signal
.setPin(pin
.get());
187 public Profile
getRecipientProfile(final RecipientIdentifier
.Single recipient
) {
188 throw new UnsupportedOperationException();
192 public List
<Group
> getGroups() {
193 final var groups
= signal
.listGroups();
194 return groups
.stream().map(Signal
.StructGroup
::getObjectPath
).map(this::getGroup
).toList();
198 public SendGroupMessageResults
quitGroup(
199 final GroupId groupId
, final Set
<RecipientIdentifier
.Single
> groupAdmins
200 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
201 if (groupAdmins
.size() > 0) {
202 throw new UnsupportedOperationException();
204 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
206 return new SendGroupMessageResults(0, List
.of());
210 public void deleteGroup(final GroupId groupId
) throws IOException
{
211 throw new UnsupportedOperationException();
215 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
216 final String name
, final Set
<RecipientIdentifier
.Single
> members
, final File avatarFile
217 ) throws IOException
, AttachmentInvalidException
{
218 final var newGroupId
= signal
.createGroup(emptyIfNull(name
),
219 members
.stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList(),
220 avatarFile
== null ?
"" : avatarFile
.getPath());
221 return new Pair
<>(GroupId
.unknownVersion(newGroupId
), new SendGroupMessageResults(0, List
.of()));
225 public SendGroupMessageResults
updateGroup(
226 final GroupId groupId
, final UpdateGroup updateGroup
227 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
228 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
229 if (updateGroup
.getName() != null) {
230 group
.Set("org.asamk.Signal.Group", "Name", updateGroup
.getName());
232 if (updateGroup
.getDescription() != null) {
233 group
.Set("org.asamk.Signal.Group", "Description", updateGroup
.getDescription());
235 if (updateGroup
.getAvatarFile() != null) {
236 group
.Set("org.asamk.Signal.Group",
238 updateGroup
.getAvatarFile() == null ?
"" : updateGroup
.getAvatarFile().getPath());
240 if (updateGroup
.getExpirationTimer() != null) {
241 group
.Set("org.asamk.Signal.Group", "MessageExpirationTimer", updateGroup
.getExpirationTimer());
243 if (updateGroup
.getAddMemberPermission() != null) {
244 group
.Set("org.asamk.Signal.Group", "PermissionAddMember", updateGroup
.getAddMemberPermission().name());
246 if (updateGroup
.getEditDetailsPermission() != null) {
247 group
.Set("org.asamk.Signal.Group", "PermissionEditDetails", updateGroup
.getEditDetailsPermission().name());
249 if (updateGroup
.getIsAnnouncementGroup() != null) {
250 group
.Set("org.asamk.Signal.Group",
251 "PermissionSendMessage",
252 updateGroup
.getIsAnnouncementGroup()
253 ? GroupPermission
.ONLY_ADMINS
.name()
254 : GroupPermission
.EVERY_MEMBER
.name());
256 if (updateGroup
.getMembers() != null) {
257 group
.addMembers(updateGroup
.getMembers().stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList());
259 if (updateGroup
.getRemoveMembers() != null) {
260 group
.removeMembers(updateGroup
.getRemoveMembers()
262 .map(RecipientIdentifier
.Single
::getIdentifier
)
265 if (updateGroup
.getAdmins() != null) {
266 group
.addAdmins(updateGroup
.getAdmins().stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList());
268 if (updateGroup
.getRemoveAdmins() != null) {
269 group
.removeAdmins(updateGroup
.getRemoveAdmins()
271 .map(RecipientIdentifier
.Single
::getIdentifier
)
274 if (updateGroup
.isResetGroupLink()) {
277 if (updateGroup
.getGroupLinkState() != null) {
278 switch (updateGroup
.getGroupLinkState()) {
279 case DISABLED
-> group
.disableLink();
280 case ENABLED
-> group
.enableLink(false);
281 case ENABLED_WITH_APPROVAL
-> group
.enableLink(true);
284 return new SendGroupMessageResults(0, List
.of());
288 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(final GroupInviteLinkUrl inviteLinkUrl
) throws IOException
, InactiveGroupLinkException
{
289 final var newGroupId
= signal
.joinGroup(inviteLinkUrl
.getUrl());
290 return new Pair
<>(GroupId
.unknownVersion(newGroupId
), new SendGroupMessageResults(0, List
.of()));
294 public SendMessageResults
sendTypingMessage(
295 final TypingAction action
, final Set
<RecipientIdentifier
> recipients
296 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
297 return handleMessage(recipients
, numbers
-> {
298 numbers
.forEach(n
-> signal
.sendTyping(n
, action
== TypingAction
.STOP
));
301 signal
.sendTyping(signal
.getSelfNumber(), action
== TypingAction
.STOP
);
304 signal
.sendGroupTyping(groupId
, action
== TypingAction
.STOP
);
310 public SendMessageResults
sendReadReceipt(
311 final RecipientIdentifier
.Single sender
, final List
<Long
> messageIds
313 signal
.sendReadReceipt(sender
.getIdentifier(), messageIds
);
314 return new SendMessageResults(0, Map
.of());
318 public SendMessageResults
sendViewedReceipt(
319 final RecipientIdentifier
.Single sender
, final List
<Long
> messageIds
321 signal
.sendViewedReceipt(sender
.getIdentifier(), messageIds
);
322 return new SendMessageResults(0, Map
.of());
326 public SendMessageResults
sendMessage(
327 final Message message
, final Set
<RecipientIdentifier
> recipients
328 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
329 return handleMessage(recipients
,
330 numbers
-> signal
.sendMessage(message
.messageText(), message
.attachments(), numbers
),
331 () -> signal
.sendNoteToSelfMessage(message
.messageText(), message
.attachments()),
332 groupId
-> signal
.sendGroupMessage(message
.messageText(), message
.attachments(), groupId
));
336 public SendMessageResults
sendRemoteDeleteMessage(
337 final long targetSentTimestamp
, final Set
<RecipientIdentifier
> recipients
338 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
339 return handleMessage(recipients
,
340 numbers
-> signal
.sendRemoteDeleteMessage(targetSentTimestamp
, numbers
),
341 () -> signal
.sendRemoteDeleteMessage(targetSentTimestamp
, signal
.getSelfNumber()),
342 groupId
-> signal
.sendGroupRemoteDeleteMessage(targetSentTimestamp
, groupId
));
346 public SendMessageResults
sendMessageReaction(
348 final boolean remove
,
349 final RecipientIdentifier
.Single targetAuthor
,
350 final long targetSentTimestamp
,
351 final Set
<RecipientIdentifier
> recipients
352 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
353 return handleMessage(recipients
,
354 numbers
-> signal
.sendMessageReaction(emoji
,
356 targetAuthor
.getIdentifier(),
359 () -> signal
.sendMessageReaction(emoji
,
361 targetAuthor
.getIdentifier(),
363 signal
.getSelfNumber()),
364 groupId
-> signal
.sendGroupMessageReaction(emoji
,
366 targetAuthor
.getIdentifier(),
372 public SendMessageResults
sendEndSessionMessage(final Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
373 signal
.sendEndSessionMessage(recipients
.stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList());
374 return new SendMessageResults(0, Map
.of());
378 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) throws IOException
{
379 signal
.deleteRecipient(recipient
.getIdentifier());
383 public void deleteContact(final RecipientIdentifier
.Single recipient
) throws IOException
{
384 signal
.deleteContact(recipient
.getIdentifier());
388 public void setContactName(
389 final RecipientIdentifier
.Single recipient
, final String name
390 ) throws NotMasterDeviceException
{
391 signal
.setContactName(recipient
.getIdentifier(), name
);
395 public void setContactBlocked(
396 final RecipientIdentifier
.Single recipient
, final boolean blocked
397 ) throws NotMasterDeviceException
, IOException
{
398 signal
.setContactBlocked(recipient
.getIdentifier(), blocked
);
402 public void setGroupBlocked(
403 final GroupId groupId
, final boolean blocked
404 ) throws GroupNotFoundException
, IOException
{
405 setGroupProperty(groupId
, "IsBlocked", blocked
);
408 private void setGroupProperty(final GroupId groupId
, final String propertyName
, final boolean blocked
) {
409 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
410 group
.Set("org.asamk.Signal.Group", propertyName
, blocked
);
414 public void setExpirationTimer(
415 final RecipientIdentifier
.Single recipient
, final int messageExpirationTimer
416 ) throws IOException
{
417 signal
.setExpirationTimer(recipient
.getIdentifier(), messageExpirationTimer
);
421 public URI
uploadStickerPack(final File path
) throws IOException
, StickerPackInvalidException
{
423 return new URI(signal
.uploadStickerPack(path
.getPath()));
424 } catch (URISyntaxException e
) {
425 throw new AssertionError(e
);
430 public void requestAllSyncData() throws IOException
{
431 signal
.sendSyncRequest();
435 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
436 synchronized (messageHandlers
) {
437 if (isWeakListener
) {
438 weakHandlers
.add(handler
);
440 if (messageHandlers
.size() == 0) {
441 installMessageHandlers();
443 messageHandlers
.add(handler
);
449 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
450 synchronized (messageHandlers
) {
451 weakHandlers
.remove(handler
);
452 messageHandlers
.remove(handler
);
453 if (messageHandlers
.size() == 0) {
454 uninstallMessageHandlers();
460 public boolean isReceiving() {
461 synchronized (messageHandlers
) {
462 return messageHandlers
.size() > 0;
467 public void receiveMessages(final ReceiveMessageHandler handler
) throws IOException
{
468 addReceiveHandler(handler
);
470 synchronized (this) {
473 } catch (InterruptedException ignored
) {
475 removeReceiveHandler(handler
);
479 public void receiveMessages(
480 final long timeout
, final TimeUnit unit
, final ReceiveMessageHandler handler
481 ) throws IOException
{
482 addReceiveHandler(handler
);
484 Thread
.sleep(unit
.toMillis(timeout
));
485 } catch (InterruptedException ignored
) {
487 removeReceiveHandler(handler
);
491 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
495 public boolean hasCaughtUpWithOldMessages() {
500 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
501 return signal
.isContactBlocked(recipient
.getIdentifier());
505 public void sendContacts() throws IOException
{
506 signal
.sendContacts();
510 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
511 throw new UnsupportedOperationException();
515 public String
getContactOrProfileName(final RecipientIdentifier
.Single recipient
) {
516 return signal
.getContactName(recipient
.getIdentifier());
520 public Group
getGroup(final GroupId groupId
) {
521 final var groupPath
= signal
.getGroup(groupId
.serialize());
522 return getGroup(groupPath
);
525 @SuppressWarnings("unchecked")
526 private Group
getGroup(final DBusPath groupPath
) {
527 final var group
= getRemoteObject(groupPath
, Signal
.Group
.class).GetAll("org.asamk.Signal.Group");
528 final var id
= (byte[]) group
.get("Id").getValue();
530 return new Group(GroupId
.unknownVersion(id
),
531 (String
) group
.get("Name").getValue(),
532 (String
) group
.get("Description").getValue(),
533 GroupInviteLinkUrl
.fromUri((String
) group
.get("GroupInviteLink").getValue()),
534 ((List
<String
>) group
.get("Members").getValue()).stream()
535 .map(m
-> new RecipientAddress(null, m
))
536 .collect(Collectors
.toSet()),
537 ((List
<String
>) group
.get("PendingMembers").getValue()).stream()
538 .map(m
-> new RecipientAddress(null, m
))
539 .collect(Collectors
.toSet()),
540 ((List
<String
>) group
.get("RequestingMembers").getValue()).stream()
541 .map(m
-> new RecipientAddress(null, m
))
542 .collect(Collectors
.toSet()),
543 ((List
<String
>) group
.get("Admins").getValue()).stream()
544 .map(m
-> new RecipientAddress(null, m
))
545 .collect(Collectors
.toSet()),
546 (boolean) group
.get("IsBlocked").getValue(),
547 (int) group
.get("MessageExpirationTimer").getValue(),
548 GroupPermission
.valueOf((String
) group
.get("PermissionAddMember").getValue()),
549 GroupPermission
.valueOf((String
) group
.get("PermissionEditDetails").getValue()),
550 GroupPermission
.valueOf((String
) group
.get("PermissionSendMessage").getValue()),
551 (boolean) group
.get("IsMember").getValue(),
552 (boolean) group
.get("IsAdmin").getValue());
553 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
554 throw new AssertionError(e
);
559 public List
<Identity
> getIdentities() {
560 throw new UnsupportedOperationException();
564 public List
<Identity
> getIdentities(final RecipientIdentifier
.Single recipient
) {
565 throw new UnsupportedOperationException();
569 public boolean trustIdentityVerified(final RecipientIdentifier
.Single recipient
, final byte[] fingerprint
) {
570 throw new UnsupportedOperationException();
574 public boolean trustIdentityVerifiedSafetyNumber(
575 final RecipientIdentifier
.Single recipient
, final String safetyNumber
577 throw new UnsupportedOperationException();
581 public boolean trustIdentityVerifiedSafetyNumber(
582 final RecipientIdentifier
.Single recipient
, final byte[] safetyNumber
584 throw new UnsupportedOperationException();
588 public boolean trustIdentityAllKeys(final RecipientIdentifier
.Single recipient
) {
589 throw new UnsupportedOperationException();
593 public void addClosedListener(final Runnable listener
) {
594 synchronized (closedListeners
) {
595 closedListeners
.add(listener
);
600 public void close() throws IOException
{
601 synchronized (this) {
604 synchronized (messageHandlers
) {
605 if (messageHandlers
.size() > 0) {
606 uninstallMessageHandlers();
608 weakHandlers
.clear();
609 messageHandlers
.clear();
611 synchronized (closedListeners
) {
612 closedListeners
.forEach(Runnable
::run
);
613 closedListeners
.clear();
617 private SendMessageResults
handleMessage(
618 Set
<RecipientIdentifier
> recipients
,
619 Function
<List
<String
>, Long
> recipientsHandler
,
620 Supplier
<Long
> noteToSelfHandler
,
621 Function
<byte[], Long
> groupHandler
624 final var singleRecipients
= recipients
.stream()
625 .filter(r
-> r
instanceof RecipientIdentifier
.Single
)
626 .map(RecipientIdentifier
.Single
.class::cast
)
627 .map(RecipientIdentifier
.Single
::getIdentifier
)
629 if (singleRecipients
.size() > 0) {
630 timestamp
= recipientsHandler
.apply(singleRecipients
);
633 if (recipients
.contains(RecipientIdentifier
.NoteToSelf
.INSTANCE
)) {
634 timestamp
= noteToSelfHandler
.get();
636 final var groupRecipients
= recipients
.stream()
637 .filter(r
-> r
instanceof RecipientIdentifier
.Group
)
638 .map(RecipientIdentifier
.Group
.class::cast
)
639 .map(RecipientIdentifier
.Group
::groupId
)
641 for (final var groupId
: groupRecipients
) {
642 timestamp
= groupHandler
.apply(groupId
.serialize());
644 return new SendMessageResults(timestamp
, Map
.of());
647 private String
emptyIfNull(final String string
) {
648 return string
== null ?
"" : string
;
651 private <T
extends DBusInterface
> T
getRemoteObject(final DBusPath devicePath
, final Class
<T
> type
) {
653 return connection
.getRemoteObject(DbusConfig
.getBusname(), devicePath
.getPath(), type
);
654 } catch (DBusException e
) {
655 throw new AssertionError(e
);
659 private void installMessageHandlers() {
661 this.dbusMsgHandler
= messageReceived
-> {
662 final var extras
= messageReceived
.getExtras();
663 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
664 messageReceived
.getSender())),
666 messageReceived
.getTimestamp(),
672 Optional
.of(new MessageEnvelope
.Data(messageReceived
.getTimestamp(),
673 messageReceived
.getGroupId().length
> 0
674 ? Optional
.of(new MessageEnvelope
.Data
.GroupContext(GroupId
.unknownVersion(
675 messageReceived
.getGroupId()), false, 0))
678 Optional
.of(messageReceived
.getMessage()),
687 getAttachments(extras
),
695 notifyMessageHandlers(envelope
);
697 connection
.addSigHandler(Signal
.MessageReceivedV2
.class, signal
, this.dbusMsgHandler
);
699 this.dbusRcptHandler
= receiptReceived
-> {
700 final var type
= switch (receiptReceived
.getReceiptType()) {
701 case "read" -> MessageEnvelope
.Receipt
.Type
.READ
;
702 case "viewed" -> MessageEnvelope
.Receipt
.Type
.VIEWED
;
703 case "delivery" -> MessageEnvelope
.Receipt
.Type
.DELIVERY
;
704 default -> MessageEnvelope
.Receipt
.Type
.UNKNOWN
;
706 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
707 receiptReceived
.getSender())),
709 receiptReceived
.getTimestamp(),
713 Optional
.of(new MessageEnvelope
.Receipt(receiptReceived
.getTimestamp(),
715 List
.of(receiptReceived
.getTimestamp()))),
720 notifyMessageHandlers(envelope
);
722 connection
.addSigHandler(Signal
.ReceiptReceivedV2
.class, signal
, this.dbusRcptHandler
);
724 this.dbusSyncHandler
= syncReceived
-> {
725 final var extras
= syncReceived
.getExtras();
726 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
727 syncReceived
.getSource())),
729 syncReceived
.getTimestamp(),
736 Optional
.of(new MessageEnvelope
.Sync(Optional
.of(new MessageEnvelope
.Sync
.Sent(syncReceived
.getTimestamp(),
737 syncReceived
.getTimestamp(),
738 syncReceived
.getDestination().isEmpty()
740 : Optional
.of(new RecipientAddress(null, syncReceived
.getDestination())),
742 new MessageEnvelope
.Data(syncReceived
.getTimestamp(),
743 syncReceived
.getGroupId().length
> 0
744 ? Optional
.of(new MessageEnvelope
.Data
.GroupContext(GroupId
.unknownVersion(
745 syncReceived
.getGroupId()), false, 0))
748 Optional
.of(syncReceived
.getMessage()),
757 getAttachments(extras
),
771 notifyMessageHandlers(envelope
);
773 connection
.addSigHandler(Signal
.SyncMessageReceivedV2
.class, signal
, this.dbusSyncHandler
);
774 } catch (DBusException e
) {
777 signal
.subscribeReceive();
780 private void notifyMessageHandlers(final MessageEnvelope envelope
) {
781 synchronized (messageHandlers
) {
782 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream())
783 .forEach(h
-> h
.handleMessage(envelope
, null));
787 private void uninstallMessageHandlers() {
789 signal
.unsubscribeReceive();
790 connection
.removeSigHandler(Signal
.MessageReceivedV2
.class, signal
, this.dbusMsgHandler
);
791 connection
.removeSigHandler(Signal
.ReceiptReceivedV2
.class, signal
, this.dbusRcptHandler
);
792 connection
.removeSigHandler(Signal
.SyncMessageReceivedV2
.class, signal
, this.dbusSyncHandler
);
793 } catch (DBusException e
) {
798 private List
<MessageEnvelope
.Data
.Attachment
> getAttachments(final Map
<String
, Variant
<?
>> extras
) {
799 if (!extras
.containsKey("attachments")) {
803 final List
<DBusMap
<String
, Variant
<?
>>> attachments
= getValue(extras
, "attachments");
804 return attachments
.stream().map(a
-> {
805 final String file
= a
.containsKey("file") ?
getValue(a
, "file") : null;
806 return new MessageEnvelope
.Data
.Attachment(a
.containsKey("remoteId")
807 ? Optional
.of(getValue(a
, "remoteId"))
809 file
!= null ? Optional
.of(new File(file
)) : Optional
.empty(),
811 getValue(a
, "contentType"),
819 getValue(a
, "isVoiceNote"),
820 getValue(a
, "isGif"),
821 getValue(a
, "isBorderless"));
825 @SuppressWarnings("unchecked")
826 private <T
> T
getValue(
827 final Map
<String
, Variant
<?
>> stringVariantMap
, final String field
829 return (T
) stringVariantMap
.get(field
).getValue();