1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.DbusConfig
;
5 import org
.asamk
.signal
.manager
.Manager
;
6 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
7 import org
.asamk
.signal
.manager
.api
.Configuration
;
8 import org
.asamk
.signal
.manager
.api
.Device
;
9 import org
.asamk
.signal
.manager
.api
.Group
;
10 import org
.asamk
.signal
.manager
.api
.Identity
;
11 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
12 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
13 import org
.asamk
.signal
.manager
.api
.Message
;
14 import org
.asamk
.signal
.manager
.api
.MessageEnvelope
;
15 import org
.asamk
.signal
.manager
.api
.NotMasterDeviceException
;
16 import org
.asamk
.signal
.manager
.api
.Pair
;
17 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
18 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
19 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
20 import org
.asamk
.signal
.manager
.api
.StickerPack
;
21 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
22 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
23 import org
.asamk
.signal
.manager
.api
.TypingAction
;
24 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
25 import org
.asamk
.signal
.manager
.api
.UserStatus
;
26 import org
.asamk
.signal
.manager
.groups
.GroupId
;
27 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
28 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
29 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
30 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
31 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
32 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
33 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
34 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
35 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
36 import org
.freedesktop
.dbus
.DBusMap
;
37 import org
.freedesktop
.dbus
.DBusPath
;
38 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
39 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
40 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
41 import org
.freedesktop
.dbus
.interfaces
.DBusSigHandler
;
42 import org
.freedesktop
.dbus
.types
.Variant
;
45 import java
.io
.IOException
;
47 import java
.net
.URISyntaxException
;
48 import java
.time
.Duration
;
49 import java
.util
.ArrayList
;
50 import java
.util
.Collection
;
51 import java
.util
.HashMap
;
52 import java
.util
.HashSet
;
53 import java
.util
.List
;
55 import java
.util
.Objects
;
56 import java
.util
.Optional
;
58 import java
.util
.concurrent
.atomic
.AtomicLong
;
59 import java
.util
.function
.Function
;
60 import java
.util
.function
.Supplier
;
61 import java
.util
.stream
.Collectors
;
62 import java
.util
.stream
.Stream
;
65 * This class implements the Manager interface using the DBus Signal interface, where possible.
66 * It's used for the signal-cli dbus client mode (--dbus, --dbus-system)
68 public class DbusManagerImpl
implements Manager
{
70 private final Signal signal
;
71 private final DBusConnection connection
;
73 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
74 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
75 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
76 private DBusSigHandler
<Signal
.MessageReceivedV2
> dbusMsgHandler
;
77 private DBusSigHandler
<Signal
.ReceiptReceivedV2
> dbusRcptHandler
;
78 private DBusSigHandler
<Signal
.SyncMessageReceivedV2
> dbusSyncHandler
;
80 public DbusManagerImpl(final Signal signal
, DBusConnection connection
) {
82 this.connection
= connection
;
86 public String
getSelfNumber() {
87 return signal
.getSelfNumber();
91 public Map
<String
, UserStatus
> getUserStatus(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
, UserStatus
>();
96 for (var i
= 0; i
< numbersList
.size(); i
++) {
97 result
.put(numbersList
.get(i
),
98 new UserStatus(numbersList
.get(i
),
99 registered
.get(i
) ? RecipientAddress
.UNKNOWN_UUID
: null,
106 public void updateAccountAttributes(final String deviceName
) throws IOException
{
107 if (deviceName
!= null) {
108 final var devicePath
= signal
.getThisDevice();
109 getRemoteObject(devicePath
, Signal
.Device
.class).Set("org.asamk.Signal.Device", "Name", deviceName
);
114 public Configuration
getConfiguration() {
115 final var configuration
= getRemoteObject(new DBusPath(signal
.getObjectPath() + "/Configuration"),
116 Signal
.Configuration
.class).GetAll("org.asamk.Signal.Configuration");
117 return new Configuration(Optional
.of((Boolean
) configuration
.get("ReadReceipts").getValue()),
118 Optional
.of((Boolean
) configuration
.get("UnidentifiedDeliveryIndicators").getValue()),
119 Optional
.of((Boolean
) configuration
.get("TypingIndicators").getValue()),
120 Optional
.of((Boolean
) configuration
.get("LinkPreviews").getValue()));
124 public void updateConfiguration(Configuration newConfiguration
) throws IOException
{
125 final var configuration
= getRemoteObject(new DBusPath(signal
.getObjectPath() + "/Configuration"),
126 Signal
.Configuration
.class);
127 newConfiguration
.readReceipts()
128 .ifPresent(v
-> configuration
.Set("org.asamk.Signal.Configuration", "ReadReceipts", v
));
129 newConfiguration
.unidentifiedDeliveryIndicators()
130 .ifPresent(v
-> configuration
.Set("org.asamk.Signal.Configuration",
131 "UnidentifiedDeliveryIndicators",
133 newConfiguration
.typingIndicators()
134 .ifPresent(v
-> configuration
.Set("org.asamk.Signal.Configuration", "TypingIndicators", v
));
135 newConfiguration
.linkPreviews()
136 .ifPresent(v
-> configuration
.Set("org.asamk.Signal.Configuration", "LinkPreviews", v
));
140 public void setProfile(
141 final String givenName
,
142 final String familyName
,
144 final String aboutEmoji
,
145 final Optional
<File
> avatar
146 ) throws IOException
{
147 signal
.updateProfile(emptyIfNull(givenName
),
148 emptyIfNull(familyName
),
150 emptyIfNull(aboutEmoji
),
151 avatar
== null ?
"" : avatar
.map(File
::getPath
).orElse(""),
152 avatar
!= null && avatar
.isEmpty());
156 public void unregister() throws IOException
{
161 public void deleteAccount() throws IOException
{
162 signal
.deleteAccount();
166 public void submitRateLimitRecaptchaChallenge(final String challenge
, final String captcha
) throws IOException
{
167 signal
.submitRateLimitChallenge(challenge
, captcha
);
171 public List
<Device
> getLinkedDevices() throws IOException
{
172 final var thisDevice
= signal
.getThisDevice();
173 return signal
.listDevices().stream().map(d
-> {
174 final var device
= getRemoteObject(d
.getObjectPath(),
175 Signal
.Device
.class).GetAll("org.asamk.Signal.Device");
176 return new Device((Integer
) device
.get("Id").getValue(),
177 (String
) device
.get("Name").getValue(),
178 (long) device
.get("Created").getValue(),
179 (long) device
.get("LastSeen").getValue(),
180 thisDevice
.equals(d
.getObjectPath()));
185 public void removeLinkedDevices(final int deviceId
) throws IOException
{
186 final var devicePath
= signal
.getDevice(deviceId
);
187 getRemoteObject(devicePath
, Signal
.Device
.class).removeDevice();
191 public void addDeviceLink(final URI linkUri
) throws IOException
, InvalidDeviceLinkException
{
192 signal
.addDevice(linkUri
.toString());
196 public void setRegistrationLockPin(final Optional
<String
> pin
) throws IOException
{
197 if (pin
.isPresent()) {
198 signal
.setPin(pin
.get());
205 public Profile
getRecipientProfile(final RecipientIdentifier
.Single recipient
) {
206 throw new UnsupportedOperationException();
210 public List
<Group
> getGroups() {
211 final var groups
= signal
.listGroups();
212 return groups
.stream().map(Signal
.StructGroup
::getObjectPath
).map(this::getGroup
).toList();
216 public SendGroupMessageResults
quitGroup(
217 final GroupId groupId
, final Set
<RecipientIdentifier
.Single
> groupAdmins
218 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
219 if (groupAdmins
.size() > 0) {
220 throw new UnsupportedOperationException();
222 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
224 return new SendGroupMessageResults(0, List
.of());
228 public void deleteGroup(final GroupId groupId
) throws IOException
{
229 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
234 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
235 final String name
, final Set
<RecipientIdentifier
.Single
> members
, final File avatarFile
236 ) throws IOException
, AttachmentInvalidException
{
237 final var newGroupId
= signal
.createGroup(emptyIfNull(name
),
238 members
.stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList(),
239 avatarFile
== null ?
"" : avatarFile
.getPath());
240 return new Pair
<>(GroupId
.unknownVersion(newGroupId
), new SendGroupMessageResults(0, List
.of()));
244 public SendGroupMessageResults
updateGroup(
245 final GroupId groupId
, final UpdateGroup updateGroup
246 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
247 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
248 if (updateGroup
.getName() != null) {
249 group
.Set("org.asamk.Signal.Group", "Name", updateGroup
.getName());
251 if (updateGroup
.getDescription() != null) {
252 group
.Set("org.asamk.Signal.Group", "Description", updateGroup
.getDescription());
254 if (updateGroup
.getAvatarFile() != null) {
255 group
.Set("org.asamk.Signal.Group",
257 updateGroup
.getAvatarFile() == null ?
"" : updateGroup
.getAvatarFile().getPath());
259 if (updateGroup
.getExpirationTimer() != null) {
260 group
.Set("org.asamk.Signal.Group", "MessageExpirationTimer", updateGroup
.getExpirationTimer());
262 if (updateGroup
.getAddMemberPermission() != null) {
263 group
.Set("org.asamk.Signal.Group", "PermissionAddMember", updateGroup
.getAddMemberPermission().name());
265 if (updateGroup
.getEditDetailsPermission() != null) {
266 group
.Set("org.asamk.Signal.Group", "PermissionEditDetails", updateGroup
.getEditDetailsPermission().name());
268 if (updateGroup
.getIsAnnouncementGroup() != null) {
269 group
.Set("org.asamk.Signal.Group",
270 "PermissionSendMessage",
271 updateGroup
.getIsAnnouncementGroup()
272 ? GroupPermission
.ONLY_ADMINS
.name()
273 : GroupPermission
.EVERY_MEMBER
.name());
275 if (updateGroup
.getMembers() != null) {
276 group
.addMembers(updateGroup
.getMembers().stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList());
278 if (updateGroup
.getRemoveMembers() != null) {
279 group
.removeMembers(updateGroup
.getRemoveMembers()
281 .map(RecipientIdentifier
.Single
::getIdentifier
)
284 if (updateGroup
.getAdmins() != null) {
285 group
.addAdmins(updateGroup
.getAdmins().stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList());
287 if (updateGroup
.getRemoveAdmins() != null) {
288 group
.removeAdmins(updateGroup
.getRemoveAdmins()
290 .map(RecipientIdentifier
.Single
::getIdentifier
)
293 if (updateGroup
.isResetGroupLink()) {
296 if (updateGroup
.getGroupLinkState() != null) {
297 switch (updateGroup
.getGroupLinkState()) {
298 case DISABLED
-> group
.disableLink();
299 case ENABLED
-> group
.enableLink(false);
300 case ENABLED_WITH_APPROVAL
-> group
.enableLink(true);
303 return new SendGroupMessageResults(0, List
.of());
307 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(final GroupInviteLinkUrl inviteLinkUrl
) throws IOException
, InactiveGroupLinkException
{
308 final var newGroupId
= signal
.joinGroup(inviteLinkUrl
.getUrl());
309 return new Pair
<>(GroupId
.unknownVersion(newGroupId
), new SendGroupMessageResults(0, List
.of()));
313 public SendMessageResults
sendTypingMessage(
314 final TypingAction action
, final Set
<RecipientIdentifier
> recipients
315 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
316 return handleMessage(recipients
, numbers
-> {
317 numbers
.forEach(n
-> signal
.sendTyping(n
, action
== TypingAction
.STOP
));
320 signal
.sendTyping(signal
.getSelfNumber(), action
== TypingAction
.STOP
);
323 signal
.sendGroupTyping(groupId
, action
== TypingAction
.STOP
);
329 public SendMessageResults
sendReadReceipt(
330 final RecipientIdentifier
.Single sender
, final List
<Long
> messageIds
332 signal
.sendReadReceipt(sender
.getIdentifier(), messageIds
);
333 return new SendMessageResults(0, Map
.of());
337 public SendMessageResults
sendViewedReceipt(
338 final RecipientIdentifier
.Single sender
, final List
<Long
> messageIds
340 signal
.sendViewedReceipt(sender
.getIdentifier(), messageIds
);
341 return new SendMessageResults(0, Map
.of());
345 public SendMessageResults
sendMessage(
346 final Message message
, final Set
<RecipientIdentifier
> recipients
347 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
348 return handleMessage(recipients
,
349 numbers
-> signal
.sendMessage(message
.messageText(), message
.attachments(), numbers
),
350 () -> signal
.sendNoteToSelfMessage(message
.messageText(), message
.attachments()),
351 groupId
-> signal
.sendGroupMessage(message
.messageText(), message
.attachments(), groupId
));
355 public SendMessageResults
sendRemoteDeleteMessage(
356 final long targetSentTimestamp
, final Set
<RecipientIdentifier
> recipients
357 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
358 return handleMessage(recipients
,
359 numbers
-> signal
.sendRemoteDeleteMessage(targetSentTimestamp
, numbers
),
360 () -> signal
.sendRemoteDeleteMessage(targetSentTimestamp
, signal
.getSelfNumber()),
361 groupId
-> signal
.sendGroupRemoteDeleteMessage(targetSentTimestamp
, groupId
));
365 public SendMessageResults
sendMessageReaction(
367 final boolean remove
,
368 final RecipientIdentifier
.Single targetAuthor
,
369 final long targetSentTimestamp
,
370 final Set
<RecipientIdentifier
> recipients
371 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
372 return handleMessage(recipients
,
373 numbers
-> signal
.sendMessageReaction(emoji
,
375 targetAuthor
.getIdentifier(),
378 () -> signal
.sendMessageReaction(emoji
,
380 targetAuthor
.getIdentifier(),
382 signal
.getSelfNumber()),
383 groupId
-> signal
.sendGroupMessageReaction(emoji
,
385 targetAuthor
.getIdentifier(),
391 public SendMessageResults
sendEndSessionMessage(final Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
392 signal
.sendEndSessionMessage(recipients
.stream().map(RecipientIdentifier
.Single
::getIdentifier
).toList());
393 return new SendMessageResults(0, Map
.of());
397 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
398 signal
.deleteRecipient(recipient
.getIdentifier());
402 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
403 signal
.deleteContact(recipient
.getIdentifier());
407 public void setContactName(
408 final RecipientIdentifier
.Single recipient
, final String name
409 ) throws NotMasterDeviceException
{
410 signal
.setContactName(recipient
.getIdentifier(), name
);
414 public void setContactsBlocked(
415 final Collection
<RecipientIdentifier
.Single
> recipients
, final boolean blocked
416 ) throws NotMasterDeviceException
, IOException
{
417 for (final var recipient
: recipients
) {
418 signal
.setContactBlocked(recipient
.getIdentifier(), blocked
);
423 public void setGroupsBlocked(
424 final Collection
<GroupId
> groupIds
, final boolean blocked
425 ) throws GroupNotFoundException
, IOException
{
426 for (final var groupId
: groupIds
) {
427 setGroupProperty(groupId
, "IsBlocked", blocked
);
431 private void setGroupProperty(final GroupId groupId
, final String propertyName
, final boolean blocked
) {
432 final var group
= getRemoteObject(signal
.getGroup(groupId
.serialize()), Signal
.Group
.class);
433 group
.Set("org.asamk.Signal.Group", propertyName
, blocked
);
437 public void setExpirationTimer(
438 final RecipientIdentifier
.Single recipient
, final int messageExpirationTimer
439 ) throws IOException
{
440 signal
.setExpirationTimer(recipient
.getIdentifier(), messageExpirationTimer
);
444 public StickerPackUrl
uploadStickerPack(final File path
) throws IOException
, StickerPackInvalidException
{
446 return StickerPackUrl
.fromUri(new URI(signal
.uploadStickerPack(path
.getPath())));
447 } catch (URISyntaxException
| StickerPackUrl
.InvalidStickerPackLinkException e
) {
448 throw new AssertionError(e
);
453 public List
<StickerPack
> getStickerPacks() {
454 throw new UnsupportedOperationException();
458 public void requestAllSyncData() throws IOException
{
459 signal
.sendSyncRequest();
463 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
464 synchronized (messageHandlers
) {
465 if (isWeakListener
) {
466 weakHandlers
.add(handler
);
468 if (messageHandlers
.size() == 0) {
469 installMessageHandlers();
471 messageHandlers
.add(handler
);
477 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
478 synchronized (messageHandlers
) {
479 weakHandlers
.remove(handler
);
480 messageHandlers
.remove(handler
);
481 if (messageHandlers
.size() == 0) {
482 uninstallMessageHandlers();
488 public boolean isReceiving() {
489 synchronized (messageHandlers
) {
490 return messageHandlers
.size() > 0;
495 public void receiveMessages(final ReceiveMessageHandler handler
) throws IOException
{
496 addReceiveHandler(handler
);
498 synchronized (this) {
501 } catch (InterruptedException ignored
) {
503 removeReceiveHandler(handler
);
507 public void receiveMessages(
508 final Duration timeout
, final ReceiveMessageHandler handler
509 ) throws IOException
{
510 final var lastMessage
= new AtomicLong(System
.currentTimeMillis());
512 final ReceiveMessageHandler receiveHandler
= (envelope
, e
) -> {
513 lastMessage
.set(System
.currentTimeMillis());
514 handler
.handleMessage(envelope
, e
);
516 addReceiveHandler(receiveHandler
);
519 final var sleepTimeRemaining
= timeout
.toMillis() - (System
.currentTimeMillis() - lastMessage
.get());
520 if (sleepTimeRemaining
< 0) {
523 Thread
.sleep(sleepTimeRemaining
);
524 } catch (InterruptedException ignored
) {
527 removeReceiveHandler(receiveHandler
);
531 public void setIgnoreAttachments(final boolean ignoreAttachments
) {
535 public boolean hasCaughtUpWithOldMessages() {
540 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
541 return signal
.isContactBlocked(recipient
.getIdentifier());
545 public void sendContacts() throws IOException
{
546 signal
.sendContacts();
550 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
551 return signal
.listNumbers().stream().map(n
-> {
552 final var contactName
= signal
.getContactName(n
);
553 if (contactName
.length() == 0) {
556 return new Pair
<>(new RecipientAddress(null, n
),
557 new Contact(contactName
, null, 0, signal
.isContactBlocked(n
), false, false));
558 }).filter(Objects
::nonNull
).toList();
562 public String
getContactOrProfileName(final RecipientIdentifier
.Single recipient
) {
563 return signal
.getContactName(recipient
.getIdentifier());
567 public Group
getGroup(final GroupId groupId
) {
568 final var groupPath
= signal
.getGroup(groupId
.serialize());
569 return getGroup(groupPath
);
572 @SuppressWarnings("unchecked")
573 private Group
getGroup(final DBusPath groupPath
) {
574 final var group
= getRemoteObject(groupPath
, Signal
.Group
.class).GetAll("org.asamk.Signal.Group");
575 final var id
= (byte[]) group
.get("Id").getValue();
577 return new Group(GroupId
.unknownVersion(id
),
578 (String
) group
.get("Name").getValue(),
579 (String
) group
.get("Description").getValue(),
580 GroupInviteLinkUrl
.fromUri((String
) group
.get("GroupInviteLink").getValue()),
581 ((List
<String
>) group
.get("Members").getValue()).stream()
582 .map(m
-> new RecipientAddress(null, m
))
583 .collect(Collectors
.toSet()),
584 ((List
<String
>) group
.get("PendingMembers").getValue()).stream()
585 .map(m
-> new RecipientAddress(null, m
))
586 .collect(Collectors
.toSet()),
587 ((List
<String
>) group
.get("RequestingMembers").getValue()).stream()
588 .map(m
-> new RecipientAddress(null, m
))
589 .collect(Collectors
.toSet()),
590 ((List
<String
>) group
.get("Admins").getValue()).stream()
591 .map(m
-> new RecipientAddress(null, m
))
592 .collect(Collectors
.toSet()),
593 ((List
<String
>) group
.get("Banned").getValue()).stream()
594 .map(m
-> new RecipientAddress(null, m
))
595 .collect(Collectors
.toSet()),
596 (boolean) group
.get("IsBlocked").getValue(),
597 (int) group
.get("MessageExpirationTimer").getValue(),
598 GroupPermission
.valueOf((String
) group
.get("PermissionAddMember").getValue()),
599 GroupPermission
.valueOf((String
) group
.get("PermissionEditDetails").getValue()),
600 GroupPermission
.valueOf((String
) group
.get("PermissionSendMessage").getValue()),
601 (boolean) group
.get("IsMember").getValue(),
602 (boolean) group
.get("IsAdmin").getValue());
603 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
604 throw new AssertionError(e
);
609 public List
<Identity
> getIdentities() {
610 throw new UnsupportedOperationException();
614 public List
<Identity
> getIdentities(final RecipientIdentifier
.Single recipient
) {
615 throw new UnsupportedOperationException();
619 public boolean trustIdentityVerified(final RecipientIdentifier
.Single recipient
, final byte[] fingerprint
) {
620 throw new UnsupportedOperationException();
624 public boolean trustIdentityVerifiedSafetyNumber(
625 final RecipientIdentifier
.Single recipient
, final String safetyNumber
627 throw new UnsupportedOperationException();
631 public boolean trustIdentityVerifiedSafetyNumber(
632 final RecipientIdentifier
.Single recipient
, final byte[] safetyNumber
634 throw new UnsupportedOperationException();
638 public boolean trustIdentityAllKeys(final RecipientIdentifier
.Single recipient
) {
639 throw new UnsupportedOperationException();
643 public void addAddressChangedListener(final Runnable listener
) {
647 public void addClosedListener(final Runnable listener
) {
648 synchronized (closedListeners
) {
649 closedListeners
.add(listener
);
654 public void close() {
655 synchronized (this) {
658 synchronized (messageHandlers
) {
659 if (messageHandlers
.size() > 0) {
660 uninstallMessageHandlers();
662 weakHandlers
.clear();
663 messageHandlers
.clear();
665 synchronized (closedListeners
) {
666 closedListeners
.forEach(Runnable
::run
);
667 closedListeners
.clear();
671 private SendMessageResults
handleMessage(
672 Set
<RecipientIdentifier
> recipients
,
673 Function
<List
<String
>, Long
> recipientsHandler
,
674 Supplier
<Long
> noteToSelfHandler
,
675 Function
<byte[], Long
> groupHandler
678 final var singleRecipients
= recipients
.stream()
679 .filter(r
-> r
instanceof RecipientIdentifier
.Single
)
680 .map(RecipientIdentifier
.Single
.class::cast
)
681 .map(RecipientIdentifier
.Single
::getIdentifier
)
683 if (singleRecipients
.size() > 0) {
684 timestamp
= recipientsHandler
.apply(singleRecipients
);
687 if (recipients
.contains(RecipientIdentifier
.NoteToSelf
.INSTANCE
)) {
688 timestamp
= noteToSelfHandler
.get();
690 final var groupRecipients
= recipients
.stream()
691 .filter(r
-> r
instanceof RecipientIdentifier
.Group
)
692 .map(RecipientIdentifier
.Group
.class::cast
)
693 .map(RecipientIdentifier
.Group
::groupId
)
695 for (final var groupId
: groupRecipients
) {
696 timestamp
= groupHandler
.apply(groupId
.serialize());
698 return new SendMessageResults(timestamp
, Map
.of());
701 private String
emptyIfNull(final String string
) {
702 return string
== null ?
"" : string
;
705 private <T
extends DBusInterface
> T
getRemoteObject(final DBusPath path
, final Class
<T
> type
) {
707 return connection
.getRemoteObject(DbusConfig
.getBusname(), path
.getPath(), type
);
708 } catch (DBusException e
) {
709 throw new AssertionError(e
);
713 private void installMessageHandlers() {
715 this.dbusMsgHandler
= messageReceived
-> {
716 final var extras
= messageReceived
.getExtras();
717 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
718 messageReceived
.getSender())),
720 messageReceived
.getTimestamp(),
726 Optional
.of(new MessageEnvelope
.Data(messageReceived
.getTimestamp(),
727 messageReceived
.getGroupId().length
> 0
728 ? Optional
.of(new MessageEnvelope
.Data
.GroupContext(GroupId
.unknownVersion(
729 messageReceived
.getGroupId()), false, 0))
732 Optional
.of(messageReceived
.getMessage()),
741 getAttachments(extras
),
749 notifyMessageHandlers(envelope
);
751 connection
.addSigHandler(Signal
.MessageReceivedV2
.class, signal
, this.dbusMsgHandler
);
753 this.dbusRcptHandler
= receiptReceived
-> {
754 final var type
= switch (receiptReceived
.getReceiptType()) {
755 case "read" -> MessageEnvelope
.Receipt
.Type
.READ
;
756 case "viewed" -> MessageEnvelope
.Receipt
.Type
.VIEWED
;
757 case "delivery" -> MessageEnvelope
.Receipt
.Type
.DELIVERY
;
758 default -> MessageEnvelope
.Receipt
.Type
.UNKNOWN
;
760 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
761 receiptReceived
.getSender())),
763 receiptReceived
.getTimestamp(),
767 Optional
.of(new MessageEnvelope
.Receipt(receiptReceived
.getTimestamp(),
769 List
.of(receiptReceived
.getTimestamp()))),
774 notifyMessageHandlers(envelope
);
776 connection
.addSigHandler(Signal
.ReceiptReceivedV2
.class, signal
, this.dbusRcptHandler
);
778 this.dbusSyncHandler
= syncReceived
-> {
779 final var extras
= syncReceived
.getExtras();
780 final var envelope
= new MessageEnvelope(Optional
.of(new RecipientAddress(null,
781 syncReceived
.getSource())),
783 syncReceived
.getTimestamp(),
790 Optional
.of(new MessageEnvelope
.Sync(Optional
.of(new MessageEnvelope
.Sync
.Sent(syncReceived
.getTimestamp(),
791 syncReceived
.getTimestamp(),
792 syncReceived
.getDestination().isEmpty()
794 : Optional
.of(new RecipientAddress(null, syncReceived
.getDestination())),
796 Optional
.of(new MessageEnvelope
.Data(syncReceived
.getTimestamp(),
797 syncReceived
.getGroupId().length
> 0
798 ? Optional
.of(new MessageEnvelope
.Data
.GroupContext(GroupId
.unknownVersion(
799 syncReceived
.getGroupId()), false, 0))
802 Optional
.of(syncReceived
.getMessage()),
811 getAttachments(extras
),
825 notifyMessageHandlers(envelope
);
827 connection
.addSigHandler(Signal
.SyncMessageReceivedV2
.class, signal
, this.dbusSyncHandler
);
828 } catch (DBusException e
) {
831 signal
.subscribeReceive();
834 private void notifyMessageHandlers(final MessageEnvelope envelope
) {
835 synchronized (messageHandlers
) {
836 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream())
837 .forEach(h
-> h
.handleMessage(envelope
, null));
841 private void uninstallMessageHandlers() {
843 signal
.unsubscribeReceive();
844 connection
.removeSigHandler(Signal
.MessageReceivedV2
.class, signal
, this.dbusMsgHandler
);
845 connection
.removeSigHandler(Signal
.ReceiptReceivedV2
.class, signal
, this.dbusRcptHandler
);
846 connection
.removeSigHandler(Signal
.SyncMessageReceivedV2
.class, signal
, this.dbusSyncHandler
);
847 } catch (DBusException e
) {
852 private List
<MessageEnvelope
.Data
.Attachment
> getAttachments(final Map
<String
, Variant
<?
>> extras
) {
853 if (!extras
.containsKey("attachments")) {
857 final List
<DBusMap
<String
, Variant
<?
>>> attachments
= getValue(extras
, "attachments");
858 return attachments
.stream().map(a
-> {
859 final String file
= a
.containsKey("file") ?
getValue(a
, "file") : null;
860 return new MessageEnvelope
.Data
.Attachment(a
.containsKey("remoteId")
861 ? Optional
.of(getValue(a
, "remoteId"))
863 file
!= null ? Optional
.of(new File(file
)) : Optional
.empty(),
865 getValue(a
, "contentType"),
873 getValue(a
, "isVoiceNote"),
874 getValue(a
, "isGif"),
875 getValue(a
, "isBorderless"));
879 @SuppressWarnings("unchecked")
880 private <T
> T
getValue(
881 final Map
<String
, Variant
<?
>> stringVariantMap
, final String field
883 return (T
) stringVariantMap
.get(field
).getValue();