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
.InactiveGroupLinkException
;
8 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
9 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
10 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
11 import org
.asamk
.signal
.manager
.api
.Message
;
12 import org
.asamk
.signal
.manager
.api
.NotPrimaryDeviceException
;
13 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
14 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
15 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
16 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
17 import org
.asamk
.signal
.manager
.api
.TypingAction
;
18 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
19 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
20 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
21 import org
.asamk
.signal
.manager
.api
.UserStatus
;
22 import org
.asamk
.signal
.manager
.groups
.GroupId
;
23 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
24 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
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
.RecipientAddress
;
31 import org
.asamk
.signal
.util
.SendMessageResultUtils
;
32 import org
.freedesktop
.dbus
.DBusPath
;
33 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
35 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
36 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
37 import org
.freedesktop
.dbus
.types
.Variant
;
38 import org
.slf4j
.Logger
;
39 import org
.slf4j
.LoggerFactory
;
42 import java
.io
.IOException
;
44 import java
.net
.URISyntaxException
;
45 import java
.util
.ArrayList
;
46 import java
.util
.Arrays
;
47 import java
.util
.Base64
;
48 import java
.util
.Collection
;
49 import java
.util
.HashSet
;
50 import java
.util
.List
;
52 import java
.util
.Objects
;
53 import java
.util
.Optional
;
55 import java
.util
.stream
.Collectors
;
57 public class DbusSignalImpl
implements Signal
{
59 private final Manager m
;
60 private final DBusConnection connection
;
61 private final String objectPath
;
62 private final boolean noReceiveOnStart
;
64 private DBusPath thisDevice
;
65 private final List
<StructDevice
> devices
= new ArrayList
<>();
66 private final List
<StructGroup
> groups
= new ArrayList
<>();
67 private DbusReceiveMessageHandler dbusMessageHandler
;
68 private int subscriberCount
;
70 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
72 public DbusSignalImpl(
73 final Manager m
, DBusConnection connection
, final String objectPath
, final boolean noReceiveOnStart
76 this.connection
= connection
;
77 this.objectPath
= objectPath
;
78 this.noReceiveOnStart
= noReceiveOnStart
;
80 m
.addAddressChangedListener(() -> {
86 public void initObjects() {
88 if (!noReceiveOnStart
) {
93 private void exportObjects() {
98 updateConfiguration();
101 public void close() {
102 if (dbusMessageHandler
!= null) {
103 m
.removeReceiveHandler(dbusMessageHandler
);
104 dbusMessageHandler
= null;
109 private void unExportObjects() {
112 unExportConfiguration();
113 connection
.unExportObject(this.objectPath
);
117 public String
getObjectPath() {
122 public String
getSelfNumber() {
123 return m
.getSelfNumber();
127 public void subscribeReceive() {
128 if (dbusMessageHandler
== null) {
129 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
130 m
.addReceiveHandler(dbusMessageHandler
);
136 public void unsubscribeReceive() {
137 subscriberCount
= Math
.max(0, subscriberCount
- 1);
138 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
139 m
.removeReceiveHandler(dbusMessageHandler
);
140 dbusMessageHandler
= null;
145 public void submitRateLimitChallenge(String challenge
, String captcha
) {
147 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
148 } catch (IOException e
) {
149 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
155 public void unregister() throws Error
.Failure
{
158 } catch (IOException e
) {
159 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
164 public void deleteAccount() throws Error
.Failure
{
167 } catch (IOException e
) {
168 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
173 public void addDevice(String uri
) {
175 m
.addDeviceLink(new URI(uri
));
176 } catch (IOException
| InvalidDeviceLinkException e
) {
177 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
178 } catch (URISyntaxException e
) {
179 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
180 + " Device link uri has invalid format: "
186 public DBusPath
getDevice(long deviceId
) {
188 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
189 if (deviceOptional
.isEmpty()) {
190 throw new Error
.DeviceNotFound("Device not found");
192 return deviceOptional
.get().getObjectPath();
196 public List
<StructDevice
> listDevices() {
202 public DBusPath
getThisDevice() {
208 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
209 return sendMessage(message
, attachments
, List
.of(recipient
));
213 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
215 final var results
= m
.sendMessage(new Message(message
,
221 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
222 .map(RecipientIdentifier
.class::cast
)
223 .collect(Collectors
.toSet()));
225 checkSendMessageResults(results
);
226 return results
.timestamp();
227 } catch (AttachmentInvalidException e
) {
228 throw new Error
.AttachmentInvalid(e
.getMessage());
229 } catch (IOException
| InvalidStickerException e
) {
230 throw new Error
.Failure(e
);
231 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
232 throw new Error
.GroupNotFound(e
.getMessage());
233 } catch (UnregisteredRecipientException e
) {
234 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
239 public long sendRemoteDeleteMessage(
240 final long targetSentTimestamp
, final String recipient
242 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
246 public long sendRemoteDeleteMessage(
247 final long targetSentTimestamp
, final List
<String
> recipients
250 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
251 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
252 .map(RecipientIdentifier
.class::cast
)
253 .collect(Collectors
.toSet()));
254 checkSendMessageResults(results
);
255 return results
.timestamp();
256 } catch (IOException e
) {
257 throw new Error
.Failure(e
.getMessage());
258 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
259 throw new Error
.GroupNotFound(e
.getMessage());
264 public long sendMessageReaction(
266 final boolean remove
,
267 final String targetAuthor
,
268 final long targetSentTimestamp
,
269 final String recipient
271 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
275 public long sendMessageReaction(
277 final boolean remove
,
278 final String targetAuthor
,
279 final long targetSentTimestamp
,
280 final List
<String
> recipients
283 final var results
= m
.sendMessageReaction(emoji
,
285 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
287 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
288 .map(RecipientIdentifier
.class::cast
)
289 .collect(Collectors
.toSet()));
290 checkSendMessageResults(results
);
291 return results
.timestamp();
292 } catch (IOException e
) {
293 throw new Error
.Failure(e
.getMessage());
294 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
295 throw new Error
.GroupNotFound(e
.getMessage());
296 } catch (UnregisteredRecipientException e
) {
297 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
302 public long sendPaymentNotification(
303 final byte[] receipt
, final String note
, final String recipient
304 ) throws Error
.Failure
{
306 final var results
= m
.sendPaymentNotificationMessage(receipt
,
308 getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
309 checkSendMessageResults(results
);
310 return results
.timestamp();
311 } catch (IOException e
) {
312 throw new Error
.Failure(e
.getMessage());
317 public void sendTyping(
318 final String recipient
, final boolean stop
319 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
321 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
322 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
323 .map(RecipientIdentifier
.class::cast
)
324 .collect(Collectors
.toSet()));
325 checkSendMessageResults(results
);
326 } catch (IOException e
) {
327 throw new Error
.Failure(e
.getMessage());
328 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
329 throw new Error
.GroupNotFound(e
.getMessage());
334 public void sendReadReceipt(
335 final String recipient
, final List
<Long
> messageIds
336 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
338 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
340 checkSendMessageResults(results
);
341 } catch (IOException e
) {
342 throw new Error
.Failure(e
.getMessage());
347 public void sendViewedReceipt(
348 final String recipient
, final List
<Long
> messageIds
349 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
351 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
353 checkSendMessageResults(results
);
354 } catch (IOException e
) {
355 throw new Error
.Failure(e
.getMessage());
360 public void sendContacts() {
363 } catch (IOException e
) {
364 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
369 public void sendSyncRequest() {
371 m
.requestAllSyncData();
372 } catch (IOException e
) {
373 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
378 public long sendNoteToSelfMessage(
379 final String message
, final List
<String
> attachments
380 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
382 final var results
= m
.sendMessage(new Message(message
,
387 List
.of()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
388 checkSendMessageResults(results
);
389 return results
.timestamp();
390 } catch (AttachmentInvalidException e
) {
391 throw new Error
.AttachmentInvalid(e
.getMessage());
392 } catch (IOException
| InvalidStickerException e
) {
393 throw new Error
.Failure(e
.getMessage());
394 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
395 throw new Error
.GroupNotFound(e
.getMessage());
396 } catch (UnregisteredRecipientException e
) {
397 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
402 public void sendEndSessionMessage(final List
<String
> recipients
) {
404 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
405 checkSendMessageResults(results
);
406 } catch (IOException e
) {
407 throw new Error
.Failure(e
.getMessage());
412 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
413 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
417 public void deleteContact(final String recipient
) throws Error
.Failure
{
418 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
422 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
424 var results
= m
.sendMessage(new Message(message
,
429 List
.of()), Set
.of(getGroupRecipientIdentifier(groupId
)));
430 checkSendMessageResults(results
);
431 return results
.timestamp();
432 } catch (IOException
| InvalidStickerException e
) {
433 throw new Error
.Failure(e
.getMessage());
434 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
435 throw new Error
.GroupNotFound(e
.getMessage());
436 } catch (AttachmentInvalidException e
) {
437 throw new Error
.AttachmentInvalid(e
.getMessage());
438 } catch (UnregisteredRecipientException e
) {
439 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
444 public void sendGroupTyping(
445 final byte[] groupId
, final boolean stop
446 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
448 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
449 Set
.of(getGroupRecipientIdentifier(groupId
)));
450 checkSendMessageResults(results
);
451 } catch (IOException e
) {
452 throw new Error
.Failure(e
.getMessage());
453 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
454 throw new Error
.GroupNotFound(e
.getMessage());
459 public long sendGroupRemoteDeleteMessage(
460 final long targetSentTimestamp
, final byte[] groupId
463 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
464 Set
.of(getGroupRecipientIdentifier(groupId
)));
465 checkSendMessageResults(results
);
466 return results
.timestamp();
467 } catch (IOException e
) {
468 throw new Error
.Failure(e
.getMessage());
469 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
470 throw new Error
.GroupNotFound(e
.getMessage());
475 public long sendGroupMessageReaction(
477 final boolean remove
,
478 final String targetAuthor
,
479 final long targetSentTimestamp
,
483 final var results
= m
.sendMessageReaction(emoji
,
485 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
487 Set
.of(getGroupRecipientIdentifier(groupId
)));
488 checkSendMessageResults(results
);
489 return results
.timestamp();
490 } catch (IOException e
) {
491 throw new Error
.Failure(e
.getMessage());
492 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
493 throw new Error
.GroupNotFound(e
.getMessage());
494 } catch (UnregisteredRecipientException e
) {
495 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
499 // Since contact names might be empty if not defined, also potentially return
502 public String
getContactName(final String number
) {
503 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
504 return name
== null ?
"" : name
;
508 public void setContactName(final String number
, final String name
) {
510 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
, "");
511 } catch (NotPrimaryDeviceException e
) {
512 throw new Error
.Failure("This command doesn't work on linked devices.");
513 } catch (IOException e
) {
514 throw new Error
.Failure("Contact is not registered.");
515 } catch (UnregisteredRecipientException e
) {
516 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
521 public void setExpirationTimer(final String number
, final int expiration
) {
523 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
524 } catch (IOException e
) {
525 throw new Error
.Failure(e
.getMessage());
526 } catch (UnregisteredRecipientException e
) {
527 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
532 public void setContactBlocked(final String number
, final boolean blocked
) {
534 m
.setContactsBlocked(List
.of(getSingleRecipientIdentifier(number
, m
.getSelfNumber())), blocked
);
535 } catch (NotPrimaryDeviceException e
) {
536 throw new Error
.Failure("This command doesn't work on linked devices.");
537 } catch (IOException e
) {
538 throw new Error
.Failure(e
.getMessage());
539 } catch (UnregisteredRecipientException e
) {
540 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
545 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
547 m
.setGroupsBlocked(List
.of(getGroupId(groupId
)), blocked
);
548 } catch (NotPrimaryDeviceException e
) {
549 throw new Error
.Failure("This command doesn't work on linked devices.");
550 } catch (GroupNotFoundException e
) {
551 throw new Error
.GroupNotFound(e
.getMessage());
552 } catch (IOException e
) {
553 throw new Error
.Failure(e
.getMessage());
558 public List
<byte[]> getGroupIds() {
559 var groups
= m
.getGroups();
560 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
564 public DBusPath
getGroup(final byte[] groupId
) {
566 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
567 if (groupOptional
.isEmpty()) {
568 throw new Error
.GroupNotFound("Group not found");
570 return groupOptional
.get().getObjectPath();
574 public List
<StructGroup
> listGroups() {
580 public String
getGroupName(final byte[] groupId
) {
581 var group
= m
.getGroup(getGroupId(groupId
));
582 if (group
== null || group
.title() == null) {
585 return group
.title();
590 public List
<String
> getGroupMembers(final byte[] groupId
) {
591 var group
= m
.getGroup(getGroupId(groupId
));
595 final var members
= group
.members();
596 return getRecipientStrings(members
);
601 public byte[] createGroup(
602 final String name
, final List
<String
> members
, final String avatar
603 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
604 return updateGroup(new byte[0], name
, members
, avatar
);
608 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
610 groupId
= nullIfEmpty(groupId
);
611 name
= nullIfEmpty(name
);
612 avatar
= nullIfEmpty(avatar
);
613 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
614 if (groupId
== null) {
615 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
617 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
618 return results
.first().serialize();
620 final var results
= m
.updateGroup(getGroupId(groupId
),
621 UpdateGroup
.newBuilder()
623 .withMembers(memberIdentifiers
)
624 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
626 if (results
!= null) {
627 checkGroupSendMessageResults(results
.timestamp(), results
.results());
631 } catch (IOException e
) {
632 throw new Error
.Failure(e
.getMessage());
633 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
634 throw new Error
.GroupNotFound(e
.getMessage());
635 } catch (AttachmentInvalidException e
) {
636 throw new Error
.AttachmentInvalid(e
.getMessage());
637 } catch (UnregisteredRecipientException e
) {
638 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
643 public boolean isRegistered() {
648 public boolean isRegistered(String number
) {
649 var result
= isRegistered(List
.of(number
));
650 return result
.get(0);
654 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
655 if (numbers
.isEmpty()) {
659 Map
<String
, UserStatus
> registered
;
661 registered
= m
.getUserStatus(new HashSet
<>(numbers
));
662 } catch (IOException e
) {
663 throw new Error
.Failure(e
.getMessage());
666 return numbers
.stream().map(number
-> registered
.get(number
).uuid() != null).toList();
670 public void updateProfile(
676 final boolean removeAvatar
679 givenName
= nullIfEmpty(givenName
);
680 familyName
= nullIfEmpty(familyName
);
681 about
= nullIfEmpty(about
);
682 aboutEmoji
= nullIfEmpty(aboutEmoji
);
683 avatarPath
= nullIfEmpty(avatarPath
);
684 File avatarFile
= removeAvatar
|| avatarPath
== null ?
null : new File(avatarPath
);
685 m
.updateProfile(UpdateProfile
.newBuilder()
686 .withGivenName(givenName
)
687 .withFamilyName(familyName
)
689 .withAboutEmoji(aboutEmoji
)
690 .withAvatar(avatarFile
)
691 .withDeleteAvatar(removeAvatar
)
693 } catch (IOException e
) {
694 throw new Error
.Failure(e
.getMessage());
699 public void updateProfile(
702 final String aboutEmoji
,
704 final boolean removeAvatar
706 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
710 public void removePin() {
712 m
.setRegistrationLockPin(Optional
.empty());
713 } catch (IOException e
) {
714 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
715 } catch (NotPrimaryDeviceException e
) {
716 throw new Error
.Failure("This command doesn't work on linked devices.");
721 public void setPin(String registrationLockPin
) {
723 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
724 } catch (IOException e
) {
725 throw new Error
.Failure("Set pin error: " + e
.getMessage());
726 } catch (NotPrimaryDeviceException e
) {
727 throw new Error
.Failure("This command doesn't work on linked devices.");
731 // Provide option to query a version string in order to react on potential
732 // future interface changes
734 public String
version() {
735 return BaseConfig
.PROJECT_VERSION
;
738 // Create a unique list of Numbers from Identities and Contacts to really get
739 // all numbers the system knows
741 public List
<String
> listNumbers() {
742 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.empty())
744 .map(r
-> r
.getAddress().number().orElse(null))
745 .filter(Objects
::nonNull
)
751 public List
<String
> getContactNumber(final String name
) {
752 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.of(name
))
754 .map(r
-> r
.getAddress().getLegacyIdentifier())
759 public void quitGroup(final byte[] groupId
) {
760 var group
= getGroupId(groupId
);
762 m
.quitGroup(group
, Set
.of());
763 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
764 throw new Error
.GroupNotFound(e
.getMessage());
765 } catch (IOException
| LastGroupAdminException e
) {
766 throw new Error
.Failure(e
.getMessage());
767 } catch (UnregisteredRecipientException e
) {
768 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
773 public byte[] joinGroup(final String groupLink
) {
775 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
776 if (linkUrl
== null) {
777 throw new Error
.Failure("Group link is invalid:");
779 final var result
= m
.joinGroup(linkUrl
);
780 return result
.first().serialize();
781 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
782 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
783 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
784 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
785 } catch (IOException e
) {
786 throw new Error
.Failure(e
.getMessage());
791 public boolean isContactBlocked(final String number
) {
792 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
796 public boolean isGroupBlocked(final byte[] groupId
) {
797 var group
= m
.getGroup(getGroupId(groupId
));
801 return group
.isBlocked();
806 public boolean isMember(final byte[] groupId
) {
807 var group
= m
.getGroup(getGroupId(groupId
));
811 return group
.isMember();
816 public String
uploadStickerPack(String stickerPackPath
) {
817 File path
= new File(stickerPackPath
);
819 return m
.uploadStickerPack(path
).toString();
820 } catch (IOException e
) {
821 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
822 } catch (StickerPackInvalidException e
) {
823 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
827 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
828 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
834 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
836 if (result
.isIdentityFailure()) {
837 throw new Error
.UntrustedIdentity(message
);
839 throw new Error
.Failure(message
);
843 private void checkSendMessageResults(final SendMessageResults results
) {
844 final var sendMessageResults
= results
.results().values().stream().findFirst();
845 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
846 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
850 if (results
.hasSuccess()) {
854 var message
= new StringBuilder();
855 message
.append("Failed to send messages:\n");
856 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
857 for (var error
: errors
) {
858 message
.append(error
).append('\n');
860 message
.append(results
.timestamp());
862 throw new Error
.Failure(message
.toString());
865 private static void checkGroupSendMessageResults(
866 long timestamp
, Collection
<SendMessageResult
> results
867 ) throws DBusExecutionException
{
868 if (results
.size() == 1) {
869 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
873 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
874 if (errors
.size() == 0 || errors
.size() < results
.size()) {
878 var message
= new StringBuilder();
879 message
.append("Failed to send message:\n");
880 for (var error
: errors
) {
881 message
.append(error
).append('\n');
883 message
.append(timestamp
);
885 throw new Error
.Failure(message
.toString());
888 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
889 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
892 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
893 final Collection
<String
> recipientStrings
, final String localNumber
894 ) throws DBusExecutionException
{
895 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
896 for (var recipientString
: recipientStrings
) {
897 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
902 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
903 final String recipientString
, final String localNumber
904 ) throws DBusExecutionException
{
906 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
907 } catch (InvalidNumberException e
) {
908 throw new Error
.InvalidNumber(e
.getMessage());
912 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
913 return new RecipientIdentifier
.Group(getGroupId(groupId
));
916 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
918 return GroupId
.unknownVersion(groupId
);
919 } catch (Throwable e
) {
920 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
924 private byte[] nullIfEmpty(final byte[] array
) {
925 return array
.length
== 0 ?
null : array
;
928 private String
nullIfEmpty(final String name
) {
929 return name
.isEmpty() ?
null : name
;
932 private String
emptyIfNull(final String string
) {
933 return string
== null ?
"" : string
;
936 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
937 return basePath
+ "/Devices/" + deviceId
;
940 private void updateDevices() {
941 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
943 linkedDevices
= m
.getLinkedDevices();
944 } catch (IOException e
) {
945 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
950 linkedDevices
.forEach(d
-> {
951 final var object
= new DbusSignalDeviceImpl(d
);
952 final var deviceObjectPath
= object
.getObjectPath();
953 exportObject(object
);
954 if (d
.isThisDevice()) {
955 thisDevice
= new DBusPath(deviceObjectPath
);
957 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
961 private void unExportDevices() {
962 this.devices
.stream()
963 .map(StructDevice
::getObjectPath
)
964 .map(DBusPath
::getPath
)
965 .forEach(connection
::unExportObject
);
966 this.devices
.clear();
969 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
970 return basePath
+ "/Groups/" + Base64
.getEncoder()
971 .encodeToString(groupId
)
977 private void updateGroups() {
978 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
979 groups
= m
.getGroups();
983 groups
.forEach(g
-> {
984 final var object
= new DbusSignalGroupImpl(g
.groupId());
985 exportObject(object
);
986 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
987 g
.groupId().serialize(),
988 emptyIfNull(g
.title())));
992 private void unExportGroups() {
993 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
997 private static String
getConfigurationObjectPath(String basePath
) {
998 return basePath
+ "/Configuration";
1001 private void updateConfiguration() {
1002 unExportConfiguration();
1003 final var object
= new DbusSignalConfigurationImpl();
1004 exportObject(object
);
1007 private void unExportConfiguration() {
1008 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
1009 connection
.unExportObject(objectPath
);
1012 private void exportObject(final DBusInterface object
) {
1014 connection
.exportObject(object
);
1015 logger
.debug("Exported dbus object: " + object
.getObjectPath());
1016 } catch (DBusException e
) {
1017 e
.printStackTrace();
1021 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
1023 private final org
.asamk
.signal
.manager
.api
.Device device
;
1025 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1026 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1027 List
.of(new DbusProperty
<>("Id", device
::id
),
1028 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1029 new DbusProperty
<>("Created", device
::created
),
1030 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1031 this.device
= device
;
1035 public String
getObjectPath() {
1036 return getDeviceObjectPath(objectPath
, device
.id());
1040 public void removeDevice() throws Error
.Failure
{
1042 m
.removeLinkedDevices(device
.id());
1044 } catch (IOException e
) {
1045 throw new Error
.Failure(e
.getMessage());
1049 private void setDeviceName(String name
) {
1050 if (!device
.isThisDevice()) {
1051 throw new Error
.Failure("Only the name of this device can be changed");
1054 m
.updateAccountAttributes(name
);
1055 // update device list
1057 } catch (IOException e
) {
1058 throw new Error
.Failure(e
.getMessage());
1063 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1065 public DbusSignalConfigurationImpl(
1067 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1068 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1069 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1070 this::getUnidentifiedDeliveryIndicators
,
1071 this::setUnidentifiedDeliveryIndicators
),
1072 new DbusProperty
<>("TypingIndicators",
1073 this::getTypingIndicators
,
1074 this::setTypingIndicators
),
1075 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1080 public String
getObjectPath() {
1081 return getConfigurationObjectPath(objectPath
);
1084 public void setReadReceipts(Boolean readReceipts
) {
1085 setConfiguration(readReceipts
, null, null, null);
1088 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1089 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1092 public void setTypingIndicators(Boolean typingIndicators
) {
1093 setConfiguration(null, null, typingIndicators
, null);
1096 public void setLinkPreviews(Boolean linkPreviews
) {
1097 setConfiguration(null, null, null, linkPreviews
);
1100 private void setConfiguration(
1101 Boolean readReceipts
,
1102 Boolean unidentifiedDeliveryIndicators
,
1103 Boolean typingIndicators
,
1104 Boolean linkPreviews
1107 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1108 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1109 Optional
.ofNullable(typingIndicators
),
1110 Optional
.ofNullable(linkPreviews
)));
1111 } catch (IOException e
) {
1112 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1113 } catch (NotPrimaryDeviceException e
) {
1114 throw new Error
.Failure("This command doesn't work on linked devices.");
1118 private boolean getReadReceipts() {
1119 return m
.getConfiguration().readReceipts().orElse(false);
1122 private boolean getUnidentifiedDeliveryIndicators() {
1123 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1126 private boolean getTypingIndicators() {
1127 return m
.getConfiguration().typingIndicators().orElse(false);
1130 private boolean getLinkPreviews() {
1131 return m
.getConfiguration().linkPreviews().orElse(false);
1135 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1137 private final GroupId groupId
;
1139 public DbusSignalGroupImpl(final GroupId groupId
) {
1140 this.groupId
= groupId
;
1141 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1142 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1143 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1144 new DbusProperty
<>("Description",
1145 () -> emptyIfNull(getGroup().description()),
1146 this::setGroupDescription
),
1147 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1148 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1149 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1150 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1151 new DbusProperty
<>("MessageExpirationTimer",
1152 () -> getGroup().messageExpirationTimer(),
1153 this::setMessageExpirationTime
),
1154 new DbusProperty
<>("Members",
1155 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1156 new DbusProperty
<>("PendingMembers",
1157 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1158 new DbusProperty
<>("RequestingMembers",
1159 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1160 new DbusProperty
<>("Admins",
1161 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1162 new DbusProperty
<>("Banned",
1163 () -> new Variant
<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
1164 new DbusProperty
<>("PermissionAddMember",
1165 () -> getGroup().permissionAddMember().name(),
1166 this::setGroupPermissionAddMember
),
1167 new DbusProperty
<>("PermissionEditDetails",
1168 () -> getGroup().permissionEditDetails().name(),
1169 this::setGroupPermissionEditDetails
),
1170 new DbusProperty
<>("PermissionSendMessage",
1171 () -> getGroup().permissionSendMessage().name(),
1172 this::setGroupPermissionSendMessage
),
1173 new DbusProperty
<>("GroupInviteLink", () -> {
1174 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1175 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1180 public String
getObjectPath() {
1181 return getGroupObjectPath(objectPath
, groupId
.serialize());
1185 public void quitGroup() throws Error
.Failure
{
1187 m
.quitGroup(groupId
, Set
.of());
1188 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1189 throw new Error
.GroupNotFound(e
.getMessage());
1190 } catch (IOException e
) {
1191 throw new Error
.Failure(e
.getMessage());
1192 } catch (LastGroupAdminException e
) {
1193 throw new Error
.LastGroupAdmin(e
.getMessage());
1194 } catch (UnregisteredRecipientException e
) {
1195 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1200 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1202 m
.deleteGroup(groupId
);
1203 } catch (IOException e
) {
1204 throw new Error
.Failure(e
.getMessage());
1210 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1211 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1212 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1216 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1217 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1218 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1222 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1223 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1224 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1228 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1229 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1230 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1234 public void resetLink() throws Error
.Failure
{
1235 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1239 public void disableLink() throws Error
.Failure
{
1240 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1244 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1245 updateGroup(UpdateGroup
.newBuilder()
1246 .withGroupLinkState(requiresApproval
1247 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1248 : GroupLinkState
.ENABLED
)
1252 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1253 return m
.getGroup(groupId
);
1256 private void setGroupName(final String name
) {
1257 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1260 private void setGroupDescription(final String description
) {
1261 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1264 private void setGroupAvatar(final String avatar
) {
1265 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1268 private void setMessageExpirationTime(final int expirationTime
) {
1269 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1272 private void setGroupPermissionAddMember(final String permission
) {
1273 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1276 private void setGroupPermissionEditDetails(final String permission
) {
1277 updateGroup(UpdateGroup
.newBuilder()
1278 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1282 private void setGroupPermissionSendMessage(final String permission
) {
1283 updateGroup(UpdateGroup
.newBuilder()
1284 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1288 private void setIsBlocked(final boolean isBlocked
) {
1290 m
.setGroupsBlocked(List
.of(groupId
), isBlocked
);
1291 } catch (NotPrimaryDeviceException e
) {
1292 throw new Error
.Failure("This command doesn't work on linked devices.");
1293 } catch (GroupNotFoundException e
) {
1294 throw new Error
.GroupNotFound(e
.getMessage());
1295 } catch (IOException e
) {
1296 throw new Error
.Failure(e
.getMessage());
1300 private void updateGroup(final UpdateGroup updateGroup
) {
1302 m
.updateGroup(groupId
, updateGroup
);
1303 } catch (IOException e
) {
1304 throw new Error
.Failure(e
.getMessage());
1305 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1306 throw new Error
.GroupNotFound(e
.getMessage());
1307 } catch (AttachmentInvalidException e
) {
1308 throw new Error
.AttachmentInvalid(e
.getMessage());
1309 } catch (UnregisteredRecipientException e
) {
1310 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");