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
.PendingAdminApprovalException
;
14 import org
.asamk
.signal
.manager
.api
.RecipientAddress
;
15 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
16 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
17 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
18 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
19 import org
.asamk
.signal
.manager
.api
.TypingAction
;
20 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
21 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
22 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
23 import org
.asamk
.signal
.manager
.api
.UserStatus
;
24 import org
.asamk
.signal
.manager
.groups
.GroupId
;
25 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
26 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
27 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
28 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
29 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
30 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
31 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
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
,
223 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
224 .map(RecipientIdentifier
.class::cast
)
225 .collect(Collectors
.toSet()));
227 checkSendMessageResults(results
);
228 return results
.timestamp();
229 } catch (AttachmentInvalidException e
) {
230 throw new Error
.AttachmentInvalid(e
.getMessage());
231 } catch (IOException
| InvalidStickerException e
) {
232 throw new Error
.Failure(e
);
233 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
234 throw new Error
.GroupNotFound(e
.getMessage());
235 } catch (UnregisteredRecipientException e
) {
236 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
241 public long sendRemoteDeleteMessage(
242 final long targetSentTimestamp
, final String recipient
244 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
248 public long sendRemoteDeleteMessage(
249 final long targetSentTimestamp
, final List
<String
> recipients
252 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
253 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
254 .map(RecipientIdentifier
.class::cast
)
255 .collect(Collectors
.toSet()));
256 checkSendMessageResults(results
);
257 return results
.timestamp();
258 } catch (IOException e
) {
259 throw new Error
.Failure(e
.getMessage());
260 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
261 throw new Error
.GroupNotFound(e
.getMessage());
266 public long sendMessageReaction(
268 final boolean remove
,
269 final String targetAuthor
,
270 final long targetSentTimestamp
,
271 final String recipient
273 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
277 public long sendMessageReaction(
279 final boolean remove
,
280 final String targetAuthor
,
281 final long targetSentTimestamp
,
282 final List
<String
> recipients
285 final var results
= m
.sendMessageReaction(emoji
,
287 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
289 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
290 .map(RecipientIdentifier
.class::cast
)
291 .collect(Collectors
.toSet()),
293 checkSendMessageResults(results
);
294 return results
.timestamp();
295 } catch (IOException e
) {
296 throw new Error
.Failure(e
.getMessage());
297 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
298 throw new Error
.GroupNotFound(e
.getMessage());
299 } catch (UnregisteredRecipientException e
) {
300 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
305 public long sendPaymentNotification(
306 final byte[] receipt
, final String note
, final String recipient
307 ) throws Error
.Failure
{
309 final var results
= m
.sendPaymentNotificationMessage(receipt
,
311 getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
312 checkSendMessageResults(results
);
313 return results
.timestamp();
314 } catch (IOException e
) {
315 throw new Error
.Failure(e
.getMessage());
320 public void sendTyping(
321 final String recipient
, final boolean stop
322 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
324 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
325 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
326 .map(RecipientIdentifier
.class::cast
)
327 .collect(Collectors
.toSet()));
328 checkSendMessageResults(results
);
329 } catch (IOException e
) {
330 throw new Error
.Failure(e
.getMessage());
331 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
332 throw new Error
.GroupNotFound(e
.getMessage());
337 public void sendReadReceipt(
338 final String recipient
, final List
<Long
> messageIds
339 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
341 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
343 checkSendMessageResults(results
);
344 } catch (IOException e
) {
345 throw new Error
.Failure(e
.getMessage());
350 public void sendViewedReceipt(
351 final String recipient
, final List
<Long
> messageIds
352 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
354 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
356 checkSendMessageResults(results
);
357 } catch (IOException e
) {
358 throw new Error
.Failure(e
.getMessage());
363 public void sendContacts() {
366 } catch (IOException e
) {
367 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
372 public void sendSyncRequest() {
374 m
.requestAllSyncData();
375 } catch (IOException e
) {
376 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
381 public long sendNoteToSelfMessage(
382 final String message
, final List
<String
> attachments
383 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
385 final var results
= m
.sendMessage(new Message(message
,
391 Optional
.empty()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
392 checkSendMessageResults(results
);
393 return results
.timestamp();
394 } catch (AttachmentInvalidException e
) {
395 throw new Error
.AttachmentInvalid(e
.getMessage());
396 } catch (IOException
| InvalidStickerException e
) {
397 throw new Error
.Failure(e
.getMessage());
398 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
399 throw new Error
.GroupNotFound(e
.getMessage());
400 } catch (UnregisteredRecipientException e
) {
401 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
406 public void sendEndSessionMessage(final List
<String
> recipients
) {
408 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
409 checkSendMessageResults(results
);
410 } catch (IOException e
) {
411 throw new Error
.Failure(e
.getMessage());
416 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
417 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
421 public void deleteContact(final String recipient
) throws Error
.Failure
{
422 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
426 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
428 var results
= m
.sendMessage(new Message(message
,
434 Optional
.empty()), Set
.of(getGroupRecipientIdentifier(groupId
)));
435 checkSendMessageResults(results
);
436 return results
.timestamp();
437 } catch (IOException
| InvalidStickerException e
) {
438 throw new Error
.Failure(e
.getMessage());
439 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
440 throw new Error
.GroupNotFound(e
.getMessage());
441 } catch (AttachmentInvalidException e
) {
442 throw new Error
.AttachmentInvalid(e
.getMessage());
443 } catch (UnregisteredRecipientException e
) {
444 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
449 public void sendGroupTyping(
450 final byte[] groupId
, final boolean stop
451 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
453 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
454 Set
.of(getGroupRecipientIdentifier(groupId
)));
455 checkSendMessageResults(results
);
456 } catch (IOException e
) {
457 throw new Error
.Failure(e
.getMessage());
458 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
459 throw new Error
.GroupNotFound(e
.getMessage());
464 public long sendGroupRemoteDeleteMessage(
465 final long targetSentTimestamp
, final byte[] groupId
468 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
469 Set
.of(getGroupRecipientIdentifier(groupId
)));
470 checkSendMessageResults(results
);
471 return results
.timestamp();
472 } catch (IOException e
) {
473 throw new Error
.Failure(e
.getMessage());
474 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
475 throw new Error
.GroupNotFound(e
.getMessage());
480 public long sendGroupMessageReaction(
482 final boolean remove
,
483 final String targetAuthor
,
484 final long targetSentTimestamp
,
488 final var results
= m
.sendMessageReaction(emoji
,
490 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
492 Set
.of(getGroupRecipientIdentifier(groupId
)),
494 checkSendMessageResults(results
);
495 return results
.timestamp();
496 } catch (IOException e
) {
497 throw new Error
.Failure(e
.getMessage());
498 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
499 throw new Error
.GroupNotFound(e
.getMessage());
500 } catch (UnregisteredRecipientException e
) {
501 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
505 // Since contact names might be empty if not defined, also potentially return
508 public String
getContactName(final String number
) {
509 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
510 return name
== null ?
"" : name
;
514 public void setContactName(final String number
, final String name
) {
516 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
, "");
517 } catch (NotPrimaryDeviceException e
) {
518 throw new Error
.Failure("This command doesn't work on linked devices.");
519 } catch (IOException e
) {
520 throw new Error
.Failure("Contact is not registered.");
521 } catch (UnregisteredRecipientException e
) {
522 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
527 public void setExpirationTimer(final String number
, final int expiration
) {
529 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
530 } catch (IOException e
) {
531 throw new Error
.Failure(e
.getMessage());
532 } catch (UnregisteredRecipientException e
) {
533 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
538 public void setContactBlocked(final String number
, final boolean blocked
) {
540 m
.setContactsBlocked(List
.of(getSingleRecipientIdentifier(number
, m
.getSelfNumber())), blocked
);
541 } catch (NotPrimaryDeviceException e
) {
542 throw new Error
.Failure("This command doesn't work on linked devices.");
543 } catch (IOException e
) {
544 throw new Error
.Failure(e
.getMessage());
545 } catch (UnregisteredRecipientException e
) {
546 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
551 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
553 m
.setGroupsBlocked(List
.of(getGroupId(groupId
)), blocked
);
554 } catch (NotPrimaryDeviceException e
) {
555 throw new Error
.Failure("This command doesn't work on linked devices.");
556 } catch (GroupNotFoundException e
) {
557 throw new Error
.GroupNotFound(e
.getMessage());
558 } catch (IOException e
) {
559 throw new Error
.Failure(e
.getMessage());
564 public List
<byte[]> getGroupIds() {
565 var groups
= m
.getGroups();
566 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
570 public DBusPath
getGroup(final byte[] groupId
) {
572 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
573 if (groupOptional
.isEmpty()) {
574 throw new Error
.GroupNotFound("Group not found");
576 return groupOptional
.get().getObjectPath();
580 public List
<StructGroup
> listGroups() {
586 public String
getGroupName(final byte[] groupId
) {
587 var group
= m
.getGroup(getGroupId(groupId
));
588 if (group
== null || group
.title() == null) {
591 return group
.title();
596 public List
<String
> getGroupMembers(final byte[] groupId
) {
597 var group
= m
.getGroup(getGroupId(groupId
));
601 final var members
= group
.members();
602 return getRecipientStrings(members
);
607 public byte[] createGroup(
608 final String name
, final List
<String
> members
, final String avatar
609 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
610 return updateGroup(new byte[0], name
, members
, avatar
);
614 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
616 groupId
= nullIfEmpty(groupId
);
617 name
= nullIfEmpty(name
);
618 avatar
= nullIfEmpty(avatar
);
619 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
620 if (groupId
== null) {
621 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
);
623 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
624 return results
.first().serialize();
626 final var results
= m
.updateGroup(getGroupId(groupId
),
627 UpdateGroup
.newBuilder()
629 .withMembers(memberIdentifiers
)
630 .withAvatarFile(avatar
)
632 if (results
!= null) {
633 checkGroupSendMessageResults(results
.timestamp(), results
.results());
637 } catch (IOException e
) {
638 throw new Error
.Failure(e
.getMessage());
639 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
640 throw new Error
.GroupNotFound(e
.getMessage());
641 } catch (AttachmentInvalidException e
) {
642 throw new Error
.AttachmentInvalid(e
.getMessage());
643 } catch (UnregisteredRecipientException e
) {
644 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
649 public boolean isRegistered() {
654 public boolean isRegistered(String number
) {
655 var result
= isRegistered(List
.of(number
));
656 return result
.get(0);
660 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
661 if (numbers
.isEmpty()) {
665 Map
<String
, UserStatus
> registered
;
667 registered
= m
.getUserStatus(new HashSet
<>(numbers
));
668 } catch (IOException e
) {
669 throw new Error
.Failure(e
.getMessage());
672 return numbers
.stream().map(number
-> registered
.get(number
).uuid() != null).toList();
676 public void updateProfile(
682 final boolean removeAvatar
685 givenName
= nullIfEmpty(givenName
);
686 familyName
= nullIfEmpty(familyName
);
687 about
= nullIfEmpty(about
);
688 aboutEmoji
= nullIfEmpty(aboutEmoji
);
689 avatarPath
= nullIfEmpty(avatarPath
);
690 final var avatarFile
= removeAvatar
|| avatarPath
== null ?
null : avatarPath
;
691 m
.updateProfile(UpdateProfile
.newBuilder()
692 .withGivenName(givenName
)
693 .withFamilyName(familyName
)
695 .withAboutEmoji(aboutEmoji
)
696 .withAvatar(avatarFile
)
697 .withDeleteAvatar(removeAvatar
)
699 } catch (IOException e
) {
700 throw new Error
.Failure(e
.getMessage());
705 public void updateProfile(
708 final String aboutEmoji
,
710 final boolean removeAvatar
712 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
716 public void removePin() {
718 m
.setRegistrationLockPin(Optional
.empty());
719 } catch (IOException e
) {
720 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
721 } catch (NotPrimaryDeviceException e
) {
722 throw new Error
.Failure("This command doesn't work on linked devices.");
727 public void setPin(String registrationLockPin
) {
729 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
730 } catch (IOException e
) {
731 throw new Error
.Failure("Set pin error: " + e
.getMessage());
732 } catch (NotPrimaryDeviceException e
) {
733 throw new Error
.Failure("This command doesn't work on linked devices.");
737 // Provide option to query a version string in order to react on potential
738 // future interface changes
740 public String
version() {
741 return BaseConfig
.PROJECT_VERSION
;
744 // Create a unique list of Numbers from Identities and Contacts to really get
745 // all numbers the system knows
747 public List
<String
> listNumbers() {
748 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.empty())
750 .map(r
-> r
.getAddress().number().orElse(null))
751 .filter(Objects
::nonNull
)
757 public List
<String
> getContactNumber(final String name
) {
758 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.of(name
))
760 .map(r
-> r
.getAddress().getLegacyIdentifier())
765 public void quitGroup(final byte[] groupId
) {
766 var group
= getGroupId(groupId
);
768 m
.quitGroup(group
, Set
.of());
769 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
770 throw new Error
.GroupNotFound(e
.getMessage());
771 } catch (IOException
| LastGroupAdminException e
) {
772 throw new Error
.Failure(e
.getMessage());
773 } catch (UnregisteredRecipientException e
) {
774 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
779 public byte[] joinGroup(final String groupLink
) {
781 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
782 if (linkUrl
== null) {
783 throw new Error
.Failure("Group link is invalid:");
785 final var result
= m
.joinGroup(linkUrl
);
786 return result
.first().serialize();
787 } catch (PendingAdminApprovalException e
) {
788 throw new Error
.Failure("Pending admin approval: " + e
.getMessage());
789 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
790 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
791 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
792 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
793 } catch (IOException e
) {
794 throw new Error
.Failure(e
.getMessage());
799 public boolean isContactBlocked(final String number
) {
800 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
804 public boolean isGroupBlocked(final byte[] groupId
) {
805 var group
= m
.getGroup(getGroupId(groupId
));
809 return group
.isBlocked();
814 public boolean isMember(final byte[] groupId
) {
815 var group
= m
.getGroup(getGroupId(groupId
));
819 return group
.isMember();
824 public String
uploadStickerPack(String stickerPackPath
) {
825 File path
= new File(stickerPackPath
);
827 return m
.uploadStickerPack(path
).toString();
828 } catch (IOException e
) {
829 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
830 } catch (StickerPackInvalidException e
) {
831 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
835 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
836 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
842 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
844 if (result
.isIdentityFailure()) {
845 throw new Error
.UntrustedIdentity(message
);
847 throw new Error
.Failure(message
);
851 private void checkSendMessageResults(final SendMessageResults results
) {
852 final var sendMessageResults
= results
.results().values().stream().findFirst();
853 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
854 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
858 if (results
.hasSuccess()) {
862 var message
= new StringBuilder();
863 message
.append("Failed to send messages:\n");
864 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
865 for (var error
: errors
) {
866 message
.append(error
).append('\n');
868 message
.append(results
.timestamp());
870 throw new Error
.Failure(message
.toString());
873 private static void checkGroupSendMessageResults(
874 long timestamp
, Collection
<SendMessageResult
> results
875 ) throws DBusExecutionException
{
876 if (results
.size() == 1) {
877 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
881 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
882 if (errors
.size() == 0 || errors
.size() < results
.size()) {
886 var message
= new StringBuilder();
887 message
.append("Failed to send message:\n");
888 for (var error
: errors
) {
889 message
.append(error
).append('\n');
891 message
.append(timestamp
);
893 throw new Error
.Failure(message
.toString());
896 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
897 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
900 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
901 final Collection
<String
> recipientStrings
, final String localNumber
902 ) throws DBusExecutionException
{
903 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
904 for (var recipientString
: recipientStrings
) {
905 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
910 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
911 final String recipientString
, final String localNumber
912 ) throws DBusExecutionException
{
914 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
915 } catch (InvalidNumberException e
) {
916 throw new Error
.InvalidNumber(e
.getMessage());
920 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
921 return new RecipientIdentifier
.Group(getGroupId(groupId
));
924 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
926 return GroupId
.unknownVersion(groupId
);
927 } catch (Throwable e
) {
928 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
932 private byte[] nullIfEmpty(final byte[] array
) {
933 return array
.length
== 0 ?
null : array
;
936 private String
nullIfEmpty(final String name
) {
937 return name
.isEmpty() ?
null : name
;
940 private String
emptyIfNull(final String string
) {
941 return string
== null ?
"" : string
;
944 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
945 return basePath
+ "/Devices/" + deviceId
;
948 private void updateDevices() {
949 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
951 linkedDevices
= m
.getLinkedDevices();
952 } catch (IOException e
) {
953 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
958 linkedDevices
.forEach(d
-> {
959 final var object
= new DbusSignalDeviceImpl(d
);
960 final var deviceObjectPath
= object
.getObjectPath();
961 exportObject(object
);
962 if (d
.isThisDevice()) {
963 thisDevice
= new DBusPath(deviceObjectPath
);
965 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
969 private void unExportDevices() {
970 this.devices
.stream()
971 .map(StructDevice
::getObjectPath
)
972 .map(DBusPath
::getPath
)
973 .forEach(connection
::unExportObject
);
974 this.devices
.clear();
977 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
978 return basePath
+ "/Groups/" + Base64
.getEncoder()
979 .encodeToString(groupId
)
985 private void updateGroups() {
986 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
987 groups
= m
.getGroups();
991 groups
.forEach(g
-> {
992 final var object
= new DbusSignalGroupImpl(g
.groupId());
993 exportObject(object
);
994 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
995 g
.groupId().serialize(),
996 emptyIfNull(g
.title())));
1000 private void unExportGroups() {
1001 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
1002 this.groups
.clear();
1005 private static String
getConfigurationObjectPath(String basePath
) {
1006 return basePath
+ "/Configuration";
1009 private void updateConfiguration() {
1010 unExportConfiguration();
1011 final var object
= new DbusSignalConfigurationImpl();
1012 exportObject(object
);
1015 private void unExportConfiguration() {
1016 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
1017 connection
.unExportObject(objectPath
);
1020 private void exportObject(final DBusInterface object
) {
1022 connection
.exportObject(object
);
1023 logger
.debug("Exported dbus object: " + object
.getObjectPath());
1024 } catch (DBusException e
) {
1025 e
.printStackTrace();
1029 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
1031 private final org
.asamk
.signal
.manager
.api
.Device device
;
1033 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1034 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1035 List
.of(new DbusProperty
<>("Id", device
::id
),
1036 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1037 new DbusProperty
<>("Created", device
::created
),
1038 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1039 this.device
= device
;
1043 public String
getObjectPath() {
1044 return getDeviceObjectPath(objectPath
, device
.id());
1048 public void removeDevice() throws Error
.Failure
{
1050 m
.removeLinkedDevices(device
.id());
1052 } catch (IOException e
) {
1053 throw new Error
.Failure(e
.getMessage());
1057 private void setDeviceName(String name
) {
1058 if (!device
.isThisDevice()) {
1059 throw new Error
.Failure("Only the name of this device can be changed");
1062 m
.updateAccountAttributes(name
);
1063 // update device list
1065 } catch (IOException e
) {
1066 throw new Error
.Failure(e
.getMessage());
1071 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1073 public DbusSignalConfigurationImpl(
1075 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1076 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1077 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1078 this::getUnidentifiedDeliveryIndicators
,
1079 this::setUnidentifiedDeliveryIndicators
),
1080 new DbusProperty
<>("TypingIndicators",
1081 this::getTypingIndicators
,
1082 this::setTypingIndicators
),
1083 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1088 public String
getObjectPath() {
1089 return getConfigurationObjectPath(objectPath
);
1092 public void setReadReceipts(Boolean readReceipts
) {
1093 setConfiguration(readReceipts
, null, null, null);
1096 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1097 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1100 public void setTypingIndicators(Boolean typingIndicators
) {
1101 setConfiguration(null, null, typingIndicators
, null);
1104 public void setLinkPreviews(Boolean linkPreviews
) {
1105 setConfiguration(null, null, null, linkPreviews
);
1108 private void setConfiguration(
1109 Boolean readReceipts
,
1110 Boolean unidentifiedDeliveryIndicators
,
1111 Boolean typingIndicators
,
1112 Boolean linkPreviews
1115 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1116 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1117 Optional
.ofNullable(typingIndicators
),
1118 Optional
.ofNullable(linkPreviews
)));
1119 } catch (IOException e
) {
1120 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1121 } catch (NotPrimaryDeviceException e
) {
1122 throw new Error
.Failure("This command doesn't work on linked devices.");
1126 private boolean getReadReceipts() {
1127 return m
.getConfiguration().readReceipts().orElse(false);
1130 private boolean getUnidentifiedDeliveryIndicators() {
1131 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1134 private boolean getTypingIndicators() {
1135 return m
.getConfiguration().typingIndicators().orElse(false);
1138 private boolean getLinkPreviews() {
1139 return m
.getConfiguration().linkPreviews().orElse(false);
1143 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1145 private final GroupId groupId
;
1147 public DbusSignalGroupImpl(final GroupId groupId
) {
1148 this.groupId
= groupId
;
1149 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1150 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1151 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1152 new DbusProperty
<>("Description",
1153 () -> emptyIfNull(getGroup().description()),
1154 this::setGroupDescription
),
1155 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1156 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1157 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1158 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1159 new DbusProperty
<>("MessageExpirationTimer",
1160 () -> getGroup().messageExpirationTimer(),
1161 this::setMessageExpirationTime
),
1162 new DbusProperty
<>("Members",
1163 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1164 new DbusProperty
<>("PendingMembers",
1165 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1166 new DbusProperty
<>("RequestingMembers",
1167 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1168 new DbusProperty
<>("Admins",
1169 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1170 new DbusProperty
<>("Banned",
1171 () -> new Variant
<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
1172 new DbusProperty
<>("PermissionAddMember",
1173 () -> getGroup().permissionAddMember().name(),
1174 this::setGroupPermissionAddMember
),
1175 new DbusProperty
<>("PermissionEditDetails",
1176 () -> getGroup().permissionEditDetails().name(),
1177 this::setGroupPermissionEditDetails
),
1178 new DbusProperty
<>("PermissionSendMessage",
1179 () -> getGroup().permissionSendMessage().name(),
1180 this::setGroupPermissionSendMessage
),
1181 new DbusProperty
<>("GroupInviteLink", () -> {
1182 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1183 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1188 public String
getObjectPath() {
1189 return getGroupObjectPath(objectPath
, groupId
.serialize());
1193 public void quitGroup() throws Error
.Failure
{
1195 m
.quitGroup(groupId
, Set
.of());
1196 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1197 throw new Error
.GroupNotFound(e
.getMessage());
1198 } catch (IOException e
) {
1199 throw new Error
.Failure(e
.getMessage());
1200 } catch (LastGroupAdminException e
) {
1201 throw new Error
.LastGroupAdmin(e
.getMessage());
1202 } catch (UnregisteredRecipientException e
) {
1203 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1208 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1210 m
.deleteGroup(groupId
);
1211 } catch (IOException e
) {
1212 throw new Error
.Failure(e
.getMessage());
1218 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1219 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1220 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1224 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1225 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1226 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1230 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1231 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1232 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1236 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1237 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1238 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1242 public void resetLink() throws Error
.Failure
{
1243 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1247 public void disableLink() throws Error
.Failure
{
1248 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1252 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1253 updateGroup(UpdateGroup
.newBuilder()
1254 .withGroupLinkState(requiresApproval
1255 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1256 : GroupLinkState
.ENABLED
)
1260 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1261 return m
.getGroup(groupId
);
1264 private void setGroupName(final String name
) {
1265 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1268 private void setGroupDescription(final String description
) {
1269 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1272 private void setGroupAvatar(final String avatar
) {
1273 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(avatar
).build());
1276 private void setMessageExpirationTime(final int expirationTime
) {
1277 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1280 private void setGroupPermissionAddMember(final String permission
) {
1281 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1284 private void setGroupPermissionEditDetails(final String permission
) {
1285 updateGroup(UpdateGroup
.newBuilder()
1286 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1290 private void setGroupPermissionSendMessage(final String permission
) {
1291 updateGroup(UpdateGroup
.newBuilder()
1292 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1296 private void setIsBlocked(final boolean isBlocked
) {
1298 m
.setGroupsBlocked(List
.of(groupId
), isBlocked
);
1299 } catch (NotPrimaryDeviceException e
) {
1300 throw new Error
.Failure("This command doesn't work on linked devices.");
1301 } catch (GroupNotFoundException e
) {
1302 throw new Error
.GroupNotFound(e
.getMessage());
1303 } catch (IOException e
) {
1304 throw new Error
.Failure(e
.getMessage());
1308 private void updateGroup(final UpdateGroup updateGroup
) {
1310 m
.updateGroup(groupId
, updateGroup
);
1311 } catch (IOException e
) {
1312 throw new Error
.Failure(e
.getMessage());
1313 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1314 throw new Error
.GroupNotFound(e
.getMessage());
1315 } catch (AttachmentInvalidException e
) {
1316 throw new Error
.AttachmentInvalid(e
.getMessage());
1317 } catch (UnregisteredRecipientException e
) {
1318 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");