1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.BaseConfig
;
5 import org
.asamk
.signal
.manager
.Manager
;
6 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
7 import org
.asamk
.signal
.manager
.api
.GroupId
;
8 import org
.asamk
.signal
.manager
.api
.GroupInviteLinkUrl
;
9 import org
.asamk
.signal
.manager
.api
.GroupLinkState
;
10 import org
.asamk
.signal
.manager
.api
.GroupNotFoundException
;
11 import org
.asamk
.signal
.manager
.api
.GroupPermission
;
12 import org
.asamk
.signal
.manager
.api
.GroupSendingNotAllowedException
;
13 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
14 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
15 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
16 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
17 import org
.asamk
.signal
.manager
.api
.LastGroupAdminException
;
18 import org
.asamk
.signal
.manager
.api
.Message
;
19 import org
.asamk
.signal
.manager
.api
.NotAGroupMemberException
;
20 import org
.asamk
.signal
.manager
.api
.NotPrimaryDeviceException
;
21 import org
.asamk
.signal
.manager
.api
.PendingAdminApprovalException
;
22 import org
.asamk
.signal
.manager
.api
.RecipientAddress
;
23 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
24 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
25 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
26 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
27 import org
.asamk
.signal
.manager
.api
.TypingAction
;
28 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
29 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
30 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
31 import org
.asamk
.signal
.manager
.api
.UserStatus
;
32 import org
.asamk
.signal
.util
.SendMessageResultUtils
;
33 import org
.freedesktop
.dbus
.DBusPath
;
34 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
35 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
36 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
37 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
38 import org
.freedesktop
.dbus
.types
.Variant
;
39 import org
.slf4j
.Logger
;
40 import org
.slf4j
.LoggerFactory
;
43 import java
.io
.IOException
;
45 import java
.net
.URISyntaxException
;
46 import java
.util
.ArrayList
;
47 import java
.util
.Arrays
;
48 import java
.util
.Base64
;
49 import java
.util
.Collection
;
50 import java
.util
.HashSet
;
51 import java
.util
.List
;
53 import java
.util
.Objects
;
54 import java
.util
.Optional
;
56 import java
.util
.stream
.Collectors
;
58 public class DbusSignalImpl
implements Signal
{
60 private final Manager m
;
61 private final DBusConnection connection
;
62 private final String objectPath
;
63 private final boolean noReceiveOnStart
;
65 private DBusPath thisDevice
;
66 private final List
<StructDevice
> devices
= new ArrayList
<>();
67 private final List
<StructGroup
> groups
= new ArrayList
<>();
68 private DbusReceiveMessageHandler dbusMessageHandler
;
69 private int subscriberCount
;
71 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
73 public DbusSignalImpl(
74 final Manager m
, DBusConnection connection
, final String objectPath
, final boolean noReceiveOnStart
77 this.connection
= connection
;
78 this.objectPath
= objectPath
;
79 this.noReceiveOnStart
= noReceiveOnStart
;
81 m
.addAddressChangedListener(() -> {
87 public void initObjects() {
89 if (!noReceiveOnStart
) {
94 private void exportObjects() {
99 updateConfiguration();
102 public void close() {
103 if (dbusMessageHandler
!= null) {
104 m
.removeReceiveHandler(dbusMessageHandler
);
105 dbusMessageHandler
= null;
110 private void unExportObjects() {
113 unExportConfiguration();
114 connection
.unExportObject(this.objectPath
);
118 public String
getObjectPath() {
123 public String
getSelfNumber() {
124 return m
.getSelfNumber();
128 public void subscribeReceive() {
129 if (dbusMessageHandler
== null) {
130 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
131 m
.addReceiveHandler(dbusMessageHandler
);
137 public void unsubscribeReceive() {
138 subscriberCount
= Math
.max(0, subscriberCount
- 1);
139 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
140 m
.removeReceiveHandler(dbusMessageHandler
);
141 dbusMessageHandler
= null;
146 public void submitRateLimitChallenge(String challenge
, String captcha
) {
148 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
149 } catch (IOException e
) {
150 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
156 public void unregister() throws Error
.Failure
{
159 } catch (IOException e
) {
160 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
165 public void deleteAccount() throws Error
.Failure
{
168 } catch (IOException e
) {
169 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
174 public void addDevice(String uri
) {
176 m
.addDeviceLink(new URI(uri
));
177 } catch (IOException
| InvalidDeviceLinkException e
) {
178 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
179 } catch (URISyntaxException e
) {
180 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
181 + " Device link uri has invalid format: "
187 public DBusPath
getDevice(long deviceId
) {
189 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
190 if (deviceOptional
.isEmpty()) {
191 throw new Error
.DeviceNotFound("Device not found");
193 return deviceOptional
.get().getObjectPath();
197 public List
<StructDevice
> listDevices() {
203 public DBusPath
getThisDevice() {
209 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
210 return sendMessage(message
, attachments
, List
.of(recipient
));
214 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
216 final var results
= m
.sendMessage(new Message(message
,
224 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
225 .map(RecipientIdentifier
.class::cast
)
226 .collect(Collectors
.toSet()));
228 checkSendMessageResults(results
);
229 return results
.timestamp();
230 } catch (AttachmentInvalidException e
) {
231 throw new Error
.AttachmentInvalid(e
.getMessage());
232 } catch (IOException
| InvalidStickerException e
) {
233 throw new Error
.Failure(e
);
234 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
235 throw new Error
.GroupNotFound(e
.getMessage());
236 } catch (UnregisteredRecipientException e
) {
237 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
242 public long sendRemoteDeleteMessage(
243 final long targetSentTimestamp
, final String recipient
245 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
249 public long sendRemoteDeleteMessage(
250 final long targetSentTimestamp
, final List
<String
> recipients
253 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
254 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
255 .map(RecipientIdentifier
.class::cast
)
256 .collect(Collectors
.toSet()));
257 checkSendMessageResults(results
);
258 return results
.timestamp();
259 } catch (IOException e
) {
260 throw new Error
.Failure(e
.getMessage());
261 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
262 throw new Error
.GroupNotFound(e
.getMessage());
267 public long sendMessageReaction(
269 final boolean remove
,
270 final String targetAuthor
,
271 final long targetSentTimestamp
,
272 final String recipient
274 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
278 public long sendMessageReaction(
280 final boolean remove
,
281 final String targetAuthor
,
282 final long targetSentTimestamp
,
283 final List
<String
> recipients
286 final var results
= m
.sendMessageReaction(emoji
,
288 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
290 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
291 .map(RecipientIdentifier
.class::cast
)
292 .collect(Collectors
.toSet()),
294 checkSendMessageResults(results
);
295 return results
.timestamp();
296 } catch (IOException e
) {
297 throw new Error
.Failure(e
.getMessage());
298 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
299 throw new Error
.GroupNotFound(e
.getMessage());
300 } catch (UnregisteredRecipientException e
) {
301 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
306 public long sendPaymentNotification(
307 final byte[] receipt
, final String note
, final String recipient
308 ) throws Error
.Failure
{
310 final var results
= m
.sendPaymentNotificationMessage(receipt
,
312 getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
313 checkSendMessageResults(results
);
314 return results
.timestamp();
315 } catch (IOException e
) {
316 throw new Error
.Failure(e
.getMessage());
321 public void sendTyping(
322 final String recipient
, final boolean stop
323 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
325 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
326 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
327 .map(RecipientIdentifier
.class::cast
)
328 .collect(Collectors
.toSet()));
329 checkSendMessageResults(results
);
330 } catch (IOException e
) {
331 throw new Error
.Failure(e
.getMessage());
332 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
333 throw new Error
.GroupNotFound(e
.getMessage());
338 public void sendReadReceipt(
339 final String recipient
, final List
<Long
> messageIds
340 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
342 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
344 checkSendMessageResults(results
);
345 } catch (IOException e
) {
346 throw new Error
.Failure(e
.getMessage());
351 public void sendViewedReceipt(
352 final String recipient
, final List
<Long
> messageIds
353 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
355 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
357 checkSendMessageResults(results
);
358 } catch (IOException e
) {
359 throw new Error
.Failure(e
.getMessage());
364 public void sendContacts() {
367 } catch (IOException e
) {
368 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
373 public void sendSyncRequest() {
375 m
.requestAllSyncData();
376 } catch (IOException e
) {
377 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
382 public long sendNoteToSelfMessage(
383 final String message
, final List
<String
> attachments
384 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
386 final var results
= m
.sendMessage(new Message(message
,
393 List
.of()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
394 checkSendMessageResults(results
);
395 return results
.timestamp();
396 } catch (AttachmentInvalidException e
) {
397 throw new Error
.AttachmentInvalid(e
.getMessage());
398 } catch (IOException
| InvalidStickerException e
) {
399 throw new Error
.Failure(e
.getMessage());
400 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
401 throw new Error
.GroupNotFound(e
.getMessage());
402 } catch (UnregisteredRecipientException e
) {
403 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
408 public void sendEndSessionMessage(final List
<String
> recipients
) {
410 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
411 checkSendMessageResults(results
);
412 } catch (IOException e
) {
413 throw new Error
.Failure(e
.getMessage());
418 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
419 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
423 public void deleteContact(final String recipient
) throws Error
.Failure
{
424 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
428 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
430 var results
= m
.sendMessage(new Message(message
,
437 List
.of()), Set
.of(getGroupRecipientIdentifier(groupId
)));
438 checkSendMessageResults(results
);
439 return results
.timestamp();
440 } catch (IOException
| InvalidStickerException e
) {
441 throw new Error
.Failure(e
.getMessage());
442 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
443 throw new Error
.GroupNotFound(e
.getMessage());
444 } catch (AttachmentInvalidException e
) {
445 throw new Error
.AttachmentInvalid(e
.getMessage());
446 } catch (UnregisteredRecipientException e
) {
447 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
452 public void sendGroupTyping(
453 final byte[] groupId
, final boolean stop
454 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
456 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
457 Set
.of(getGroupRecipientIdentifier(groupId
)));
458 checkSendMessageResults(results
);
459 } catch (IOException e
) {
460 throw new Error
.Failure(e
.getMessage());
461 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
462 throw new Error
.GroupNotFound(e
.getMessage());
467 public long sendGroupRemoteDeleteMessage(
468 final long targetSentTimestamp
, final byte[] groupId
471 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
472 Set
.of(getGroupRecipientIdentifier(groupId
)));
473 checkSendMessageResults(results
);
474 return results
.timestamp();
475 } catch (IOException e
) {
476 throw new Error
.Failure(e
.getMessage());
477 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
478 throw new Error
.GroupNotFound(e
.getMessage());
483 public long sendGroupMessageReaction(
485 final boolean remove
,
486 final String targetAuthor
,
487 final long targetSentTimestamp
,
491 final var results
= m
.sendMessageReaction(emoji
,
493 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
495 Set
.of(getGroupRecipientIdentifier(groupId
)),
497 checkSendMessageResults(results
);
498 return results
.timestamp();
499 } catch (IOException e
) {
500 throw new Error
.Failure(e
.getMessage());
501 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
502 throw new Error
.GroupNotFound(e
.getMessage());
503 } catch (UnregisteredRecipientException e
) {
504 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
508 // Since contact names might be empty if not defined, also potentially return
511 public String
getContactName(final String number
) {
512 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
513 return name
== null ?
"" : name
;
517 public void setContactName(final String number
, final String name
) {
519 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
, "");
520 } catch (NotPrimaryDeviceException e
) {
521 throw new Error
.Failure("This command doesn't work on linked devices.");
522 } catch (IOException e
) {
523 throw new Error
.Failure("Contact is not registered.");
524 } catch (UnregisteredRecipientException e
) {
525 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
530 public void setExpirationTimer(final String number
, final int expiration
) {
532 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
533 } catch (IOException e
) {
534 throw new Error
.Failure(e
.getMessage());
535 } catch (UnregisteredRecipientException e
) {
536 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
541 public void setContactBlocked(final String number
, final boolean blocked
) {
543 m
.setContactsBlocked(List
.of(getSingleRecipientIdentifier(number
, m
.getSelfNumber())), blocked
);
544 } catch (NotPrimaryDeviceException e
) {
545 throw new Error
.Failure("This command doesn't work on linked devices.");
546 } catch (IOException e
) {
547 throw new Error
.Failure(e
.getMessage());
548 } catch (UnregisteredRecipientException e
) {
549 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
554 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
556 m
.setGroupsBlocked(List
.of(getGroupId(groupId
)), blocked
);
557 } catch (NotPrimaryDeviceException e
) {
558 throw new Error
.Failure("This command doesn't work on linked devices.");
559 } catch (GroupNotFoundException e
) {
560 throw new Error
.GroupNotFound(e
.getMessage());
561 } catch (IOException e
) {
562 throw new Error
.Failure(e
.getMessage());
567 public List
<byte[]> getGroupIds() {
568 var groups
= m
.getGroups();
569 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
573 public DBusPath
getGroup(final byte[] groupId
) {
575 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
576 if (groupOptional
.isEmpty()) {
577 throw new Error
.GroupNotFound("Group not found");
579 return groupOptional
.get().getObjectPath();
583 public List
<StructGroup
> listGroups() {
589 public String
getGroupName(final byte[] groupId
) {
590 var group
= m
.getGroup(getGroupId(groupId
));
591 if (group
== null || group
.title() == null) {
594 return group
.title();
599 public List
<String
> getGroupMembers(final byte[] groupId
) {
600 var group
= m
.getGroup(getGroupId(groupId
));
604 final var members
= group
.members();
605 return getRecipientStrings(members
);
610 public byte[] createGroup(
611 final String name
, final List
<String
> members
, final String avatar
612 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
613 return updateGroup(new byte[0], name
, members
, avatar
);
617 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
619 groupId
= nullIfEmpty(groupId
);
620 name
= nullIfEmpty(name
);
621 avatar
= nullIfEmpty(avatar
);
622 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
623 if (groupId
== null) {
624 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
);
626 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
627 return results
.first().serialize();
629 final var results
= m
.updateGroup(getGroupId(groupId
),
630 UpdateGroup
.newBuilder()
632 .withMembers(memberIdentifiers
)
633 .withAvatarFile(avatar
)
635 if (results
!= null) {
636 checkGroupSendMessageResults(results
.timestamp(), results
.results());
640 } catch (IOException e
) {
641 throw new Error
.Failure(e
.getMessage());
642 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
643 throw new Error
.GroupNotFound(e
.getMessage());
644 } catch (AttachmentInvalidException e
) {
645 throw new Error
.AttachmentInvalid(e
.getMessage());
646 } catch (UnregisteredRecipientException e
) {
647 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
652 public boolean isRegistered() {
657 public boolean isRegistered(String number
) {
658 var result
= isRegistered(List
.of(number
));
659 return result
.get(0);
663 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
664 if (numbers
.isEmpty()) {
668 Map
<String
, UserStatus
> registered
;
670 registered
= m
.getUserStatus(new HashSet
<>(numbers
));
671 } catch (IOException e
) {
672 throw new Error
.Failure(e
.getMessage());
675 return numbers
.stream().map(number
-> registered
.get(number
).uuid() != null).toList();
679 public void updateProfile(
685 final boolean removeAvatar
688 givenName
= nullIfEmpty(givenName
);
689 familyName
= nullIfEmpty(familyName
);
690 about
= nullIfEmpty(about
);
691 aboutEmoji
= nullIfEmpty(aboutEmoji
);
692 avatarPath
= nullIfEmpty(avatarPath
);
693 final var avatarFile
= removeAvatar
|| avatarPath
== null ?
null : avatarPath
;
694 m
.updateProfile(UpdateProfile
.newBuilder()
695 .withGivenName(givenName
)
696 .withFamilyName(familyName
)
698 .withAboutEmoji(aboutEmoji
)
699 .withAvatar(avatarFile
)
700 .withDeleteAvatar(removeAvatar
)
702 } catch (IOException e
) {
703 throw new Error
.Failure(e
.getMessage());
708 public void updateProfile(
711 final String aboutEmoji
,
713 final boolean removeAvatar
715 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
719 public void removePin() {
721 m
.setRegistrationLockPin(Optional
.empty());
722 } catch (IOException e
) {
723 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
724 } catch (NotPrimaryDeviceException e
) {
725 throw new Error
.Failure("This command doesn't work on linked devices.");
730 public void setPin(String registrationLockPin
) {
732 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
733 } catch (IOException e
) {
734 throw new Error
.Failure("Set pin error: " + e
.getMessage());
735 } catch (NotPrimaryDeviceException e
) {
736 throw new Error
.Failure("This command doesn't work on linked devices.");
740 // Provide option to query a version string in order to react on potential
741 // future interface changes
743 public String
version() {
744 return BaseConfig
.PROJECT_VERSION
;
747 // Create a unique list of Numbers from Identities and Contacts to really get
748 // all numbers the system knows
750 public List
<String
> listNumbers() {
751 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.empty())
753 .map(r
-> r
.getAddress().number().orElse(null))
754 .filter(Objects
::nonNull
)
760 public List
<String
> getContactNumber(final String name
) {
761 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.of(name
))
763 .map(r
-> r
.getAddress().getLegacyIdentifier())
768 public void quitGroup(final byte[] groupId
) {
769 var group
= getGroupId(groupId
);
771 m
.quitGroup(group
, Set
.of());
772 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
773 throw new Error
.GroupNotFound(e
.getMessage());
774 } catch (IOException
| LastGroupAdminException e
) {
775 throw new Error
.Failure(e
.getMessage());
776 } catch (UnregisteredRecipientException e
) {
777 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
782 public byte[] joinGroup(final String groupLink
) {
784 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
785 if (linkUrl
== null) {
786 throw new Error
.Failure("Group link is invalid:");
788 final var result
= m
.joinGroup(linkUrl
);
789 return result
.first().serialize();
790 } catch (PendingAdminApprovalException e
) {
791 throw new Error
.Failure("Pending admin approval: " + e
.getMessage());
792 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
793 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
794 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
795 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
796 } catch (IOException e
) {
797 throw new Error
.Failure(e
.getMessage());
802 public boolean isContactBlocked(final String number
) {
803 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
807 public boolean isGroupBlocked(final byte[] groupId
) {
808 var group
= m
.getGroup(getGroupId(groupId
));
812 return group
.isBlocked();
817 public boolean isMember(final byte[] groupId
) {
818 var group
= m
.getGroup(getGroupId(groupId
));
822 return group
.isMember();
827 public String
uploadStickerPack(String stickerPackPath
) {
828 File path
= new File(stickerPackPath
);
830 return m
.uploadStickerPack(path
).toString();
831 } catch (IOException e
) {
832 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
833 } catch (StickerPackInvalidException e
) {
834 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
838 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
839 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
845 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
847 if (result
.isIdentityFailure()) {
848 throw new Error
.UntrustedIdentity(message
);
850 throw new Error
.Failure(message
);
854 private void checkSendMessageResults(final SendMessageResults results
) {
855 final var sendMessageResults
= results
.results().values().stream().findFirst();
856 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
857 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
861 if (results
.hasSuccess()) {
865 var message
= new StringBuilder();
866 message
.append("Failed to send messages:\n");
867 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
868 for (var error
: errors
) {
869 message
.append(error
).append('\n');
871 message
.append(results
.timestamp());
873 throw new Error
.Failure(message
.toString());
876 private static void checkGroupSendMessageResults(
877 long timestamp
, Collection
<SendMessageResult
> results
878 ) throws DBusExecutionException
{
879 if (results
.size() == 1) {
880 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
884 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
885 if (errors
.size() == 0 || errors
.size() < results
.size()) {
889 var message
= new StringBuilder();
890 message
.append("Failed to send message:\n");
891 for (var error
: errors
) {
892 message
.append(error
).append('\n');
894 message
.append(timestamp
);
896 throw new Error
.Failure(message
.toString());
899 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
900 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
903 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
904 final Collection
<String
> recipientStrings
, final String localNumber
905 ) throws DBusExecutionException
{
906 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
907 for (var recipientString
: recipientStrings
) {
908 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
913 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
914 final String recipientString
, final String localNumber
915 ) throws DBusExecutionException
{
917 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
918 } catch (InvalidNumberException e
) {
919 throw new Error
.InvalidNumber(e
.getMessage());
923 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
924 return new RecipientIdentifier
.Group(getGroupId(groupId
));
927 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
929 return GroupId
.unknownVersion(groupId
);
930 } catch (Throwable e
) {
931 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
935 private byte[] nullIfEmpty(final byte[] array
) {
936 return array
.length
== 0 ?
null : array
;
939 private String
nullIfEmpty(final String name
) {
940 return name
.isEmpty() ?
null : name
;
943 private String
emptyIfNull(final String string
) {
944 return string
== null ?
"" : string
;
947 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
948 return basePath
+ "/Devices/" + deviceId
;
951 private void updateDevices() {
952 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
954 linkedDevices
= m
.getLinkedDevices();
955 } catch (IOException e
) {
956 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
961 linkedDevices
.forEach(d
-> {
962 final var object
= new DbusSignalDeviceImpl(d
);
963 final var deviceObjectPath
= object
.getObjectPath();
964 exportObject(object
);
965 if (d
.isThisDevice()) {
966 thisDevice
= new DBusPath(deviceObjectPath
);
968 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
972 private void unExportDevices() {
973 this.devices
.stream()
974 .map(StructDevice
::getObjectPath
)
975 .map(DBusPath
::getPath
)
976 .forEach(connection
::unExportObject
);
977 this.devices
.clear();
980 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
981 return basePath
+ "/Groups/" + Base64
.getEncoder()
982 .encodeToString(groupId
)
988 private void updateGroups() {
989 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
990 groups
= m
.getGroups();
994 groups
.forEach(g
-> {
995 final var object
= new DbusSignalGroupImpl(g
.groupId());
996 exportObject(object
);
997 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
998 g
.groupId().serialize(),
999 emptyIfNull(g
.title())));
1003 private void unExportGroups() {
1004 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
1005 this.groups
.clear();
1008 private static String
getConfigurationObjectPath(String basePath
) {
1009 return basePath
+ "/Configuration";
1012 private void updateConfiguration() {
1013 unExportConfiguration();
1014 final var object
= new DbusSignalConfigurationImpl();
1015 exportObject(object
);
1018 private void unExportConfiguration() {
1019 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
1020 connection
.unExportObject(objectPath
);
1023 private void exportObject(final DBusInterface object
) {
1025 connection
.exportObject(object
);
1026 logger
.debug("Exported dbus object: " + object
.getObjectPath());
1027 } catch (DBusException e
) {
1028 e
.printStackTrace();
1032 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
1034 private final org
.asamk
.signal
.manager
.api
.Device device
;
1036 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1037 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1038 List
.of(new DbusProperty
<>("Id", device
::id
),
1039 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1040 new DbusProperty
<>("Created", device
::created
),
1041 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1042 this.device
= device
;
1046 public String
getObjectPath() {
1047 return getDeviceObjectPath(objectPath
, device
.id());
1051 public void removeDevice() throws Error
.Failure
{
1053 m
.removeLinkedDevices(device
.id());
1055 } catch (IOException e
) {
1056 throw new Error
.Failure(e
.getMessage());
1060 private void setDeviceName(String name
) {
1061 if (!device
.isThisDevice()) {
1062 throw new Error
.Failure("Only the name of this device can be changed");
1065 m
.updateAccountAttributes(name
);
1066 // update device list
1068 } catch (IOException e
) {
1069 throw new Error
.Failure(e
.getMessage());
1074 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1076 public DbusSignalConfigurationImpl(
1078 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1079 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1080 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1081 this::getUnidentifiedDeliveryIndicators
,
1082 this::setUnidentifiedDeliveryIndicators
),
1083 new DbusProperty
<>("TypingIndicators",
1084 this::getTypingIndicators
,
1085 this::setTypingIndicators
),
1086 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1091 public String
getObjectPath() {
1092 return getConfigurationObjectPath(objectPath
);
1095 public void setReadReceipts(Boolean readReceipts
) {
1096 setConfiguration(readReceipts
, null, null, null);
1099 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1100 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1103 public void setTypingIndicators(Boolean typingIndicators
) {
1104 setConfiguration(null, null, typingIndicators
, null);
1107 public void setLinkPreviews(Boolean linkPreviews
) {
1108 setConfiguration(null, null, null, linkPreviews
);
1111 private void setConfiguration(
1112 Boolean readReceipts
,
1113 Boolean unidentifiedDeliveryIndicators
,
1114 Boolean typingIndicators
,
1115 Boolean linkPreviews
1118 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1119 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1120 Optional
.ofNullable(typingIndicators
),
1121 Optional
.ofNullable(linkPreviews
)));
1122 } catch (IOException e
) {
1123 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1124 } catch (NotPrimaryDeviceException e
) {
1125 throw new Error
.Failure("This command doesn't work on linked devices.");
1129 private boolean getReadReceipts() {
1130 return m
.getConfiguration().readReceipts().orElse(false);
1133 private boolean getUnidentifiedDeliveryIndicators() {
1134 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1137 private boolean getTypingIndicators() {
1138 return m
.getConfiguration().typingIndicators().orElse(false);
1141 private boolean getLinkPreviews() {
1142 return m
.getConfiguration().linkPreviews().orElse(false);
1146 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1148 private final GroupId groupId
;
1150 public DbusSignalGroupImpl(final GroupId groupId
) {
1151 this.groupId
= groupId
;
1152 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1153 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1154 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1155 new DbusProperty
<>("Description",
1156 () -> emptyIfNull(getGroup().description()),
1157 this::setGroupDescription
),
1158 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1159 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1160 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1161 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1162 new DbusProperty
<>("MessageExpirationTimer",
1163 () -> getGroup().messageExpirationTimer(),
1164 this::setMessageExpirationTime
),
1165 new DbusProperty
<>("Members",
1166 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1167 new DbusProperty
<>("PendingMembers",
1168 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1169 new DbusProperty
<>("RequestingMembers",
1170 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1171 new DbusProperty
<>("Admins",
1172 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1173 new DbusProperty
<>("Banned",
1174 () -> new Variant
<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
1175 new DbusProperty
<>("PermissionAddMember",
1176 () -> getGroup().permissionAddMember().name(),
1177 this::setGroupPermissionAddMember
),
1178 new DbusProperty
<>("PermissionEditDetails",
1179 () -> getGroup().permissionEditDetails().name(),
1180 this::setGroupPermissionEditDetails
),
1181 new DbusProperty
<>("PermissionSendMessage",
1182 () -> getGroup().permissionSendMessage().name(),
1183 this::setGroupPermissionSendMessage
),
1184 new DbusProperty
<>("GroupInviteLink", () -> {
1185 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1186 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1191 public String
getObjectPath() {
1192 return getGroupObjectPath(objectPath
, groupId
.serialize());
1196 public void quitGroup() throws Error
.Failure
{
1198 m
.quitGroup(groupId
, Set
.of());
1199 } catch (GroupNotFoundException e
) {
1200 throw new Error
.GroupNotFound(e
.getMessage());
1201 } catch (NotAGroupMemberException e
) {
1202 throw new Error
.NotAGroupMember(e
.getMessage());
1203 } catch (IOException e
) {
1204 throw new Error
.Failure(e
.getMessage());
1205 } catch (LastGroupAdminException e
) {
1206 throw new Error
.LastGroupAdmin(e
.getMessage());
1207 } catch (UnregisteredRecipientException e
) {
1208 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1213 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1215 m
.deleteGroup(groupId
);
1216 } catch (IOException e
) {
1217 throw new Error
.Failure(e
.getMessage());
1223 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1224 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1225 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1229 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1230 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1231 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1235 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1236 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1237 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1241 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1242 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1243 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1247 public void resetLink() throws Error
.Failure
{
1248 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1252 public void disableLink() throws Error
.Failure
{
1253 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1257 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1258 updateGroup(UpdateGroup
.newBuilder()
1259 .withGroupLinkState(requiresApproval
1260 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1261 : GroupLinkState
.ENABLED
)
1265 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1266 return m
.getGroup(groupId
);
1269 private void setGroupName(final String name
) {
1270 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1273 private void setGroupDescription(final String description
) {
1274 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1277 private void setGroupAvatar(final String avatar
) {
1278 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(avatar
).build());
1281 private void setMessageExpirationTime(final int expirationTime
) {
1282 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1285 private void setGroupPermissionAddMember(final String permission
) {
1286 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1289 private void setGroupPermissionEditDetails(final String permission
) {
1290 updateGroup(UpdateGroup
.newBuilder()
1291 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1295 private void setGroupPermissionSendMessage(final String permission
) {
1296 updateGroup(UpdateGroup
.newBuilder()
1297 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1301 private void setIsBlocked(final boolean isBlocked
) {
1303 m
.setGroupsBlocked(List
.of(groupId
), isBlocked
);
1304 } catch (NotPrimaryDeviceException e
) {
1305 throw new Error
.Failure("This command doesn't work on linked devices.");
1306 } catch (GroupNotFoundException e
) {
1307 throw new Error
.GroupNotFound(e
.getMessage());
1308 } catch (IOException e
) {
1309 throw new Error
.Failure(e
.getMessage());
1313 private void updateGroup(final UpdateGroup updateGroup
) {
1315 m
.updateGroup(groupId
, updateGroup
);
1316 } catch (IOException e
) {
1317 throw new Error
.Failure(e
.getMessage());
1318 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1319 throw new Error
.GroupNotFound(e
.getMessage());
1320 } catch (AttachmentInvalidException e
) {
1321 throw new Error
.AttachmentInvalid(e
.getMessage());
1322 } catch (UnregisteredRecipientException e
) {
1323 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");