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
.DeviceLinkUrl
;
8 import org
.asamk
.signal
.manager
.api
.GroupId
;
9 import org
.asamk
.signal
.manager
.api
.GroupInviteLinkUrl
;
10 import org
.asamk
.signal
.manager
.api
.GroupLinkState
;
11 import org
.asamk
.signal
.manager
.api
.GroupNotFoundException
;
12 import org
.asamk
.signal
.manager
.api
.GroupPermission
;
13 import org
.asamk
.signal
.manager
.api
.GroupSendingNotAllowedException
;
14 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
15 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
16 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
17 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
18 import org
.asamk
.signal
.manager
.api
.LastGroupAdminException
;
19 import org
.asamk
.signal
.manager
.api
.Message
;
20 import org
.asamk
.signal
.manager
.api
.NotAGroupMemberException
;
21 import org
.asamk
.signal
.manager
.api
.NotPrimaryDeviceException
;
22 import org
.asamk
.signal
.manager
.api
.PendingAdminApprovalException
;
23 import org
.asamk
.signal
.manager
.api
.RecipientAddress
;
24 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
25 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
26 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
27 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
28 import org
.asamk
.signal
.manager
.api
.TypingAction
;
29 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
30 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
31 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
32 import org
.asamk
.signal
.manager
.api
.UserStatus
;
33 import org
.asamk
.signal
.util
.SendMessageResultUtils
;
34 import org
.freedesktop
.dbus
.DBusPath
;
35 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
36 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
37 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
38 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
39 import org
.freedesktop
.dbus
.types
.Variant
;
40 import org
.slf4j
.Logger
;
41 import org
.slf4j
.LoggerFactory
;
44 import java
.io
.IOException
;
46 import java
.net
.URISyntaxException
;
47 import java
.util
.ArrayList
;
48 import java
.util
.Arrays
;
49 import java
.util
.Base64
;
50 import java
.util
.Collection
;
51 import java
.util
.HashSet
;
52 import java
.util
.List
;
54 import java
.util
.Objects
;
55 import java
.util
.Optional
;
57 import java
.util
.stream
.Collectors
;
59 import static org
.asamk
.signal
.dbus
.DbusUtils
.makeValidObjectPathElement
;
61 public class DbusSignalImpl
implements Signal
{
63 private final Manager m
;
64 private final DBusConnection connection
;
65 private final String objectPath
;
66 private final boolean noReceiveOnStart
;
68 private DBusPath thisDevice
;
69 private final List
<StructDevice
> devices
= new ArrayList
<>();
70 private final List
<StructGroup
> groups
= new ArrayList
<>();
71 private DbusReceiveMessageHandler dbusMessageHandler
;
72 private int subscriberCount
;
74 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
76 public DbusSignalImpl(
77 final Manager m
, DBusConnection connection
, final String objectPath
, final boolean noReceiveOnStart
80 this.connection
= connection
;
81 this.objectPath
= objectPath
;
82 this.noReceiveOnStart
= noReceiveOnStart
;
84 m
.addAddressChangedListener(() -> {
90 public void initObjects() {
92 if (!noReceiveOnStart
) {
97 private void exportObjects() {
102 updateConfiguration();
105 public void close() {
106 if (dbusMessageHandler
!= null) {
107 m
.removeReceiveHandler(dbusMessageHandler
);
108 dbusMessageHandler
= null;
113 private void unExportObjects() {
116 unExportConfiguration();
117 connection
.unExportObject(this.objectPath
);
121 public String
getObjectPath() {
126 public String
getSelfNumber() {
127 return m
.getSelfNumber();
131 public void subscribeReceive() {
132 if (dbusMessageHandler
== null) {
133 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
134 m
.addReceiveHandler(dbusMessageHandler
);
140 public void unsubscribeReceive() {
141 subscriberCount
= Math
.max(0, subscriberCount
- 1);
142 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
143 m
.removeReceiveHandler(dbusMessageHandler
);
144 dbusMessageHandler
= null;
149 public void submitRateLimitChallenge(String challenge
, String captcha
) {
151 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
152 } catch (IOException e
) {
153 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
159 public void unregister() throws Error
.Failure
{
162 } catch (IOException e
) {
163 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
168 public void deleteAccount() throws Error
.Failure
{
171 } catch (IOException e
) {
172 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
177 public void addDevice(String uri
) {
179 var deviceLinkUrl
= DeviceLinkUrl
.parseDeviceLinkUri(new URI(uri
));
180 m
.addDeviceLink(deviceLinkUrl
);
181 } catch (IOException
| InvalidDeviceLinkException e
) {
182 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
183 } catch (URISyntaxException e
) {
184 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
185 + " Device link uri has invalid format: "
191 public DBusPath
getDevice(long deviceId
) {
193 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
194 if (deviceOptional
.isEmpty()) {
195 throw new Error
.DeviceNotFound("Device not found");
197 return deviceOptional
.get().getObjectPath();
201 public List
<StructDevice
> listDevices() {
207 public DBusPath
getThisDevice() {
213 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
214 return sendMessage(message
, attachments
, List
.of(recipient
));
218 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
220 final var results
= m
.sendMessage(new Message(message
,
228 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
229 .map(RecipientIdentifier
.class::cast
)
230 .collect(Collectors
.toSet()));
232 checkSendMessageResults(results
);
233 return results
.timestamp();
234 } catch (AttachmentInvalidException e
) {
235 throw new Error
.AttachmentInvalid(e
.getMessage());
236 } catch (IOException
| InvalidStickerException e
) {
237 throw new Error
.Failure(e
);
238 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
239 throw new Error
.GroupNotFound(e
.getMessage());
240 } catch (UnregisteredRecipientException e
) {
241 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
246 public long sendRemoteDeleteMessage(
247 final long targetSentTimestamp
, final String recipient
249 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
253 public long sendRemoteDeleteMessage(
254 final long targetSentTimestamp
, final List
<String
> recipients
257 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
258 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
259 .map(RecipientIdentifier
.class::cast
)
260 .collect(Collectors
.toSet()));
261 checkSendMessageResults(results
);
262 return results
.timestamp();
263 } catch (IOException e
) {
264 throw new Error
.Failure(e
.getMessage());
265 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
266 throw new Error
.GroupNotFound(e
.getMessage());
271 public long sendMessageReaction(
273 final boolean remove
,
274 final String targetAuthor
,
275 final long targetSentTimestamp
,
276 final String recipient
278 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
282 public long sendMessageReaction(
284 final boolean remove
,
285 final String targetAuthor
,
286 final long targetSentTimestamp
,
287 final List
<String
> recipients
290 final var results
= m
.sendMessageReaction(emoji
,
292 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
294 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
295 .map(RecipientIdentifier
.class::cast
)
296 .collect(Collectors
.toSet()),
298 checkSendMessageResults(results
);
299 return results
.timestamp();
300 } catch (IOException e
) {
301 throw new Error
.Failure(e
.getMessage());
302 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
303 throw new Error
.GroupNotFound(e
.getMessage());
304 } catch (UnregisteredRecipientException e
) {
305 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
310 public long sendPaymentNotification(
311 final byte[] receipt
, final String note
, final String recipient
312 ) throws Error
.Failure
{
314 final var results
= m
.sendPaymentNotificationMessage(receipt
,
316 getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
317 checkSendMessageResults(results
);
318 return results
.timestamp();
319 } catch (IOException e
) {
320 throw new Error
.Failure(e
.getMessage());
325 public void sendTyping(
326 final String recipient
, final boolean stop
327 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
329 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
330 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
331 .map(RecipientIdentifier
.class::cast
)
332 .collect(Collectors
.toSet()));
333 checkSendMessageResults(results
);
334 } catch (IOException e
) {
335 throw new Error
.Failure(e
.getMessage());
336 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
337 throw new Error
.GroupNotFound(e
.getMessage());
342 public void sendReadReceipt(
343 final String recipient
, final List
<Long
> messageIds
344 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
346 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
348 checkSendMessageResults(results
);
349 } catch (IOException e
) {
350 throw new Error
.Failure(e
.getMessage());
355 public void sendViewedReceipt(
356 final String recipient
, final List
<Long
> messageIds
357 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
359 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
361 checkSendMessageResults(results
);
362 } catch (IOException e
) {
363 throw new Error
.Failure(e
.getMessage());
368 public void sendContacts() {
371 } catch (IOException e
) {
372 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
377 public void sendSyncRequest() {
379 m
.requestAllSyncData();
380 } catch (IOException e
) {
381 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
386 public long sendNoteToSelfMessage(
387 final String message
, final List
<String
> attachments
388 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
390 final var results
= m
.sendMessage(new Message(message
,
397 List
.of()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
398 checkSendMessageResults(results
);
399 return results
.timestamp();
400 } catch (AttachmentInvalidException e
) {
401 throw new Error
.AttachmentInvalid(e
.getMessage());
402 } catch (IOException
| InvalidStickerException e
) {
403 throw new Error
.Failure(e
.getMessage());
404 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
405 throw new Error
.GroupNotFound(e
.getMessage());
406 } catch (UnregisteredRecipientException e
) {
407 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
412 public void sendEndSessionMessage(final List
<String
> recipients
) {
414 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
415 checkSendMessageResults(results
);
416 } catch (IOException e
) {
417 throw new Error
.Failure(e
.getMessage());
422 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
423 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
427 public void deleteContact(final String recipient
) throws Error
.Failure
{
428 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
432 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
434 var results
= m
.sendMessage(new Message(message
,
441 List
.of()), Set
.of(getGroupRecipientIdentifier(groupId
)));
442 checkSendMessageResults(results
);
443 return results
.timestamp();
444 } catch (IOException
| InvalidStickerException e
) {
445 throw new Error
.Failure(e
.getMessage());
446 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
447 throw new Error
.GroupNotFound(e
.getMessage());
448 } catch (AttachmentInvalidException e
) {
449 throw new Error
.AttachmentInvalid(e
.getMessage());
450 } catch (UnregisteredRecipientException e
) {
451 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
456 public void sendGroupTyping(
457 final byte[] groupId
, final boolean stop
458 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
460 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
461 Set
.of(getGroupRecipientIdentifier(groupId
)));
462 checkSendMessageResults(results
);
463 } catch (IOException e
) {
464 throw new Error
.Failure(e
.getMessage());
465 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
466 throw new Error
.GroupNotFound(e
.getMessage());
471 public long sendGroupRemoteDeleteMessage(
472 final long targetSentTimestamp
, final byte[] groupId
475 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
476 Set
.of(getGroupRecipientIdentifier(groupId
)));
477 checkSendMessageResults(results
);
478 return results
.timestamp();
479 } catch (IOException e
) {
480 throw new Error
.Failure(e
.getMessage());
481 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
482 throw new Error
.GroupNotFound(e
.getMessage());
487 public long sendGroupMessageReaction(
489 final boolean remove
,
490 final String targetAuthor
,
491 final long targetSentTimestamp
,
495 final var results
= m
.sendMessageReaction(emoji
,
497 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
499 Set
.of(getGroupRecipientIdentifier(groupId
)),
501 checkSendMessageResults(results
);
502 return results
.timestamp();
503 } catch (IOException e
) {
504 throw new Error
.Failure(e
.getMessage());
505 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
506 throw new Error
.GroupNotFound(e
.getMessage());
507 } catch (UnregisteredRecipientException e
) {
508 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
512 // Since contact names might be empty if not defined, also potentially return
515 public String
getContactName(final String number
) {
516 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
517 return name
== null ?
"" : name
;
521 public void setContactName(final String number
, final String name
) {
523 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
, "");
524 } catch (NotPrimaryDeviceException e
) {
525 throw new Error
.Failure("This command doesn't work on linked devices.");
526 } catch (IOException e
) {
527 throw new Error
.Failure("Contact is not registered.");
528 } catch (UnregisteredRecipientException e
) {
529 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
534 public void setExpirationTimer(final String number
, final int expiration
) {
536 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
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 setContactBlocked(final String number
, final boolean blocked
) {
547 m
.setContactsBlocked(List
.of(getSingleRecipientIdentifier(number
, m
.getSelfNumber())), blocked
);
548 } catch (NotPrimaryDeviceException e
) {
549 throw new Error
.Failure("This command doesn't work on linked devices.");
550 } catch (IOException e
) {
551 throw new Error
.Failure(e
.getMessage());
552 } catch (UnregisteredRecipientException e
) {
553 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
558 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
560 m
.setGroupsBlocked(List
.of(getGroupId(groupId
)), blocked
);
561 } catch (NotPrimaryDeviceException e
) {
562 throw new Error
.Failure("This command doesn't work on linked devices.");
563 } catch (GroupNotFoundException e
) {
564 throw new Error
.GroupNotFound(e
.getMessage());
565 } catch (IOException e
) {
566 throw new Error
.Failure(e
.getMessage());
571 public List
<byte[]> getGroupIds() {
572 var groups
= m
.getGroups();
573 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
577 public DBusPath
getGroup(final byte[] groupId
) {
579 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
580 if (groupOptional
.isEmpty()) {
581 throw new Error
.GroupNotFound("Group not found");
583 return groupOptional
.get().getObjectPath();
587 public List
<StructGroup
> listGroups() {
593 public String
getGroupName(final byte[] groupId
) {
594 var group
= m
.getGroup(getGroupId(groupId
));
595 if (group
== null || group
.title() == null) {
598 return group
.title();
603 public List
<String
> getGroupMembers(final byte[] groupId
) {
604 var group
= m
.getGroup(getGroupId(groupId
));
608 final var members
= group
.members();
609 return getRecipientStrings(members
);
614 public byte[] createGroup(
615 final String name
, final List
<String
> members
, final String avatar
616 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
617 return updateGroup(new byte[0], name
, members
, avatar
);
621 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
623 groupId
= nullIfEmpty(groupId
);
624 name
= nullIfEmpty(name
);
625 avatar
= nullIfEmpty(avatar
);
626 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
627 if (groupId
== null) {
628 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
);
630 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
631 return results
.first().serialize();
633 final var results
= m
.updateGroup(getGroupId(groupId
),
634 UpdateGroup
.newBuilder()
636 .withMembers(memberIdentifiers
)
637 .withAvatarFile(avatar
)
639 if (results
!= null) {
640 checkGroupSendMessageResults(results
.timestamp(), results
.results());
644 } catch (IOException e
) {
645 throw new Error
.Failure(e
.getMessage());
646 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
647 throw new Error
.GroupNotFound(e
.getMessage());
648 } catch (AttachmentInvalidException e
) {
649 throw new Error
.AttachmentInvalid(e
.getMessage());
650 } catch (UnregisteredRecipientException e
) {
651 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
656 public boolean isRegistered() {
661 public boolean isRegistered(String number
) {
662 var result
= isRegistered(List
.of(number
));
663 return result
.get(0);
667 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
668 if (numbers
.isEmpty()) {
672 Map
<String
, UserStatus
> registered
;
674 registered
= m
.getUserStatus(new HashSet
<>(numbers
));
675 } catch (IOException e
) {
676 throw new Error
.Failure(e
.getMessage());
679 return numbers
.stream().map(number
-> registered
.get(number
).uuid() != null).toList();
683 public void updateProfile(
689 final boolean removeAvatar
692 givenName
= nullIfEmpty(givenName
);
693 familyName
= nullIfEmpty(familyName
);
694 about
= nullIfEmpty(about
);
695 aboutEmoji
= nullIfEmpty(aboutEmoji
);
696 avatarPath
= nullIfEmpty(avatarPath
);
697 final var avatarFile
= removeAvatar
|| avatarPath
== null ?
null : avatarPath
;
698 m
.updateProfile(UpdateProfile
.newBuilder()
699 .withGivenName(givenName
)
700 .withFamilyName(familyName
)
702 .withAboutEmoji(aboutEmoji
)
703 .withAvatar(avatarFile
)
704 .withDeleteAvatar(removeAvatar
)
706 } catch (IOException e
) {
707 throw new Error
.Failure(e
.getMessage());
712 public void updateProfile(
715 final String aboutEmoji
,
717 final boolean removeAvatar
719 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
723 public void removePin() {
725 m
.setRegistrationLockPin(Optional
.empty());
726 } catch (IOException e
) {
727 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
728 } catch (NotPrimaryDeviceException e
) {
729 throw new Error
.Failure("This command doesn't work on linked devices.");
734 public void setPin(String registrationLockPin
) {
736 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
737 } catch (IOException e
) {
738 throw new Error
.Failure("Set pin error: " + e
.getMessage());
739 } catch (NotPrimaryDeviceException e
) {
740 throw new Error
.Failure("This command doesn't work on linked devices.");
744 // Provide option to query a version string in order to react on potential
745 // future interface changes
747 public String
version() {
748 return BaseConfig
.PROJECT_VERSION
;
751 // Create a unique list of Numbers from Identities and Contacts to really get
752 // all numbers the system knows
754 public List
<String
> listNumbers() {
755 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.empty())
757 .map(r
-> r
.getAddress().number().orElse(null))
758 .filter(Objects
::nonNull
)
764 public List
<String
> getContactNumber(final String name
) {
765 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.of(name
))
767 .map(r
-> r
.getAddress().getLegacyIdentifier())
772 public void quitGroup(final byte[] groupId
) {
773 var group
= getGroupId(groupId
);
775 m
.quitGroup(group
, Set
.of());
776 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
777 throw new Error
.GroupNotFound(e
.getMessage());
778 } catch (IOException
| LastGroupAdminException e
) {
779 throw new Error
.Failure(e
.getMessage());
780 } catch (UnregisteredRecipientException e
) {
781 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
786 public byte[] joinGroup(final String groupLink
) {
788 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
789 if (linkUrl
== null) {
790 throw new Error
.Failure("Group link is invalid:");
792 final var result
= m
.joinGroup(linkUrl
);
793 return result
.first().serialize();
794 } catch (PendingAdminApprovalException e
) {
795 throw new Error
.Failure("Pending admin approval: " + e
.getMessage());
796 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
797 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
798 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
799 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
800 } catch (IOException e
) {
801 throw new Error
.Failure(e
.getMessage());
806 public boolean isContactBlocked(final String number
) {
807 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
811 public boolean isGroupBlocked(final byte[] groupId
) {
812 var group
= m
.getGroup(getGroupId(groupId
));
816 return group
.isBlocked();
821 public boolean isMember(final byte[] groupId
) {
822 var group
= m
.getGroup(getGroupId(groupId
));
826 return group
.isMember();
831 public String
uploadStickerPack(String stickerPackPath
) {
832 File path
= new File(stickerPackPath
);
834 return m
.uploadStickerPack(path
).toString();
835 } catch (IOException e
) {
836 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
837 } catch (StickerPackInvalidException e
) {
838 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
842 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
843 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
849 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
851 if (result
.isIdentityFailure()) {
852 throw new Error
.UntrustedIdentity(message
);
854 throw new Error
.Failure(message
);
858 private void checkSendMessageResults(final SendMessageResults results
) {
859 final var sendMessageResults
= results
.results().values().stream().findFirst();
860 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
861 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
865 if (results
.hasSuccess()) {
869 var message
= new StringBuilder();
870 message
.append("Failed to send messages:\n");
871 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
872 for (var error
: errors
) {
873 message
.append(error
).append('\n');
875 message
.append(results
.timestamp());
877 throw new Error
.Failure(message
.toString());
880 private static void checkGroupSendMessageResults(
881 long timestamp
, Collection
<SendMessageResult
> results
882 ) throws DBusExecutionException
{
883 if (results
.size() == 1) {
884 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
888 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
889 if (errors
.size() == 0 || errors
.size() < results
.size()) {
893 var message
= new StringBuilder();
894 message
.append("Failed to send message:\n");
895 for (var error
: errors
) {
896 message
.append(error
).append('\n');
898 message
.append(timestamp
);
900 throw new Error
.Failure(message
.toString());
903 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
904 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
907 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
908 final Collection
<String
> recipientStrings
, final String localNumber
909 ) throws DBusExecutionException
{
910 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
911 for (var recipientString
: recipientStrings
) {
912 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
917 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
918 final String recipientString
, final String localNumber
919 ) throws DBusExecutionException
{
921 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
922 } catch (InvalidNumberException e
) {
923 throw new Error
.InvalidNumber(e
.getMessage());
927 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
928 return new RecipientIdentifier
.Group(getGroupId(groupId
));
931 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
933 return GroupId
.unknownVersion(groupId
);
934 } catch (Throwable e
) {
935 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
939 private byte[] nullIfEmpty(final byte[] array
) {
940 return array
.length
== 0 ?
null : array
;
943 private String
nullIfEmpty(final String name
) {
944 return name
.isEmpty() ?
null : name
;
947 private String
emptyIfNull(final String string
) {
948 return string
== null ?
"" : string
;
951 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
952 return basePath
+ "/Devices/" + deviceId
;
955 private void updateDevices() {
956 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
958 linkedDevices
= m
.getLinkedDevices();
959 } catch (IOException e
) {
960 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
965 linkedDevices
.forEach(d
-> {
966 final var object
= new DbusSignalDeviceImpl(d
);
967 final var deviceObjectPath
= object
.getObjectPath();
968 exportObject(object
);
969 if (d
.isThisDevice()) {
970 thisDevice
= new DBusPath(deviceObjectPath
);
972 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
976 private void unExportDevices() {
977 this.devices
.stream()
978 .map(StructDevice
::getObjectPath
)
979 .map(DBusPath
::getPath
)
980 .forEach(connection
::unExportObject
);
981 this.devices
.clear();
984 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
985 return basePath
+ "/Groups/" + makeValidObjectPathElement(Base64
.getEncoder().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.");