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
.Identity
;
8 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
9 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
10 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
11 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
12 import org
.asamk
.signal
.manager
.api
.Message
;
13 import org
.asamk
.signal
.manager
.api
.NotMasterDeviceException
;
14 import org
.asamk
.signal
.manager
.api
.Pair
;
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
.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
.Profile
;
31 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
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
.UUID
;
57 import java
.util
.stream
.Collectors
;
58 import java
.util
.stream
.Stream
;
60 public class DbusSignalImpl
implements Signal
{
62 private final Manager m
;
63 private final DBusConnection connection
;
64 private final String objectPath
;
65 private final boolean noReceiveOnStart
;
67 private DBusPath thisDevice
;
68 private final List
<StructDevice
> devices
= new ArrayList
<>();
69 private final List
<StructGroup
> groups
= new ArrayList
<>();
70 private DbusReceiveMessageHandler dbusMessageHandler
;
71 private int subscriberCount
;
73 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
75 public DbusSignalImpl(
76 final Manager m
, DBusConnection connection
, final String objectPath
, final boolean noReceiveOnStart
79 this.connection
= connection
;
80 this.objectPath
= objectPath
;
81 this.noReceiveOnStart
= noReceiveOnStart
;
83 m
.addAddressChangedListener(() -> {
89 public void initObjects() {
91 if (!noReceiveOnStart
) {
96 private void exportObjects() {
101 updateConfiguration();
104 public void close() {
105 if (dbusMessageHandler
!= null) {
106 m
.removeReceiveHandler(dbusMessageHandler
);
107 dbusMessageHandler
= null;
112 private void unExportObjects() {
115 unExportConfiguration();
116 connection
.unExportObject(this.objectPath
);
120 public String
getObjectPath() {
125 public String
getSelfNumber() {
126 return m
.getSelfNumber();
130 public void subscribeReceive() {
131 if (dbusMessageHandler
== null) {
132 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
133 m
.addReceiveHandler(dbusMessageHandler
);
139 public void unsubscribeReceive() {
140 subscriberCount
= Math
.max(0, subscriberCount
- 1);
141 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
142 m
.removeReceiveHandler(dbusMessageHandler
);
143 dbusMessageHandler
= null;
148 public void submitRateLimitChallenge(String challenge
, String captcha
) {
150 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
151 } catch (IOException e
) {
152 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
158 public void unregister() throws Error
.Failure
{
161 } catch (IOException e
) {
162 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
167 public void deleteAccount() throws Error
.Failure
{
170 } catch (IOException e
) {
171 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
176 public void addDevice(String uri
) {
178 m
.addDeviceLink(new URI(uri
));
179 } catch (IOException
| InvalidDeviceLinkException e
) {
180 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
181 } catch (URISyntaxException e
) {
182 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
183 + " Device link uri has invalid format: "
189 public DBusPath
getDevice(long deviceId
) {
191 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
192 if (deviceOptional
.isEmpty()) {
193 throw new Error
.DeviceNotFound("Device not found");
195 return deviceOptional
.get().getObjectPath();
199 public List
<StructDevice
> listDevices() {
205 public DBusPath
getThisDevice() {
211 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
212 return sendMessage(message
, attachments
, List
.of(recipient
));
216 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
218 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()));
292 checkSendMessageResults(results
);
293 return results
.timestamp();
294 } catch (IOException e
) {
295 throw new Error
.Failure(e
.getMessage());
296 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
297 throw new Error
.GroupNotFound(e
.getMessage());
298 } catch (UnregisteredRecipientException e
) {
299 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
304 public void sendTyping(
305 final String recipient
, final boolean stop
306 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
308 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
309 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
310 .map(RecipientIdentifier
.class::cast
)
311 .collect(Collectors
.toSet()));
312 checkSendMessageResults(results
);
313 } catch (IOException e
) {
314 throw new Error
.Failure(e
.getMessage());
315 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
316 throw new Error
.GroupNotFound(e
.getMessage());
321 public void sendReadReceipt(
322 final String recipient
, final List
<Long
> messageIds
323 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
325 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
327 checkSendMessageResults(results
);
328 } catch (IOException e
) {
329 throw new Error
.Failure(e
.getMessage());
334 public void sendViewedReceipt(
335 final String recipient
, final List
<Long
> messageIds
336 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
338 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
340 checkSendMessageResults(results
);
341 } catch (IOException e
) {
342 throw new Error
.Failure(e
.getMessage());
347 public void sendContacts() {
350 } catch (IOException e
) {
351 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
356 public void sendSyncRequest() {
358 m
.requestAllSyncData();
359 } catch (IOException e
) {
360 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
365 public long sendNoteToSelfMessage(
366 final String message
, final List
<String
> attachments
367 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
369 final var results
= m
.sendMessage(new Message(message
,
373 Optional
.empty()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
374 checkSendMessageResults(results
);
375 return results
.timestamp();
376 } catch (AttachmentInvalidException e
) {
377 throw new Error
.AttachmentInvalid(e
.getMessage());
378 } catch (IOException
| InvalidStickerException e
) {
379 throw new Error
.Failure(e
.getMessage());
380 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
381 throw new Error
.GroupNotFound(e
.getMessage());
382 } catch (UnregisteredRecipientException e
) {
383 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
388 public void sendEndSessionMessage(final List
<String
> recipients
) {
390 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
391 checkSendMessageResults(results
);
392 } catch (IOException e
) {
393 throw new Error
.Failure(e
.getMessage());
398 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
399 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
403 public void deleteContact(final String recipient
) throws Error
.Failure
{
404 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
408 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
410 var results
= m
.sendMessage(new Message(message
,
414 Optional
.empty()), Set
.of(getGroupRecipientIdentifier(groupId
)));
415 checkSendMessageResults(results
);
416 return results
.timestamp();
417 } catch (IOException
| InvalidStickerException e
) {
418 throw new Error
.Failure(e
.getMessage());
419 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
420 throw new Error
.GroupNotFound(e
.getMessage());
421 } catch (AttachmentInvalidException e
) {
422 throw new Error
.AttachmentInvalid(e
.getMessage());
423 } catch (UnregisteredRecipientException e
) {
424 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
429 public void sendGroupTyping(
430 final byte[] groupId
, final boolean stop
431 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
433 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
434 Set
.of(getGroupRecipientIdentifier(groupId
)));
435 checkSendMessageResults(results
);
436 } catch (IOException e
) {
437 throw new Error
.Failure(e
.getMessage());
438 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
439 throw new Error
.GroupNotFound(e
.getMessage());
444 public long sendGroupRemoteDeleteMessage(
445 final long targetSentTimestamp
, final byte[] groupId
448 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
449 Set
.of(getGroupRecipientIdentifier(groupId
)));
450 checkSendMessageResults(results
);
451 return results
.timestamp();
452 } catch (IOException e
) {
453 throw new Error
.Failure(e
.getMessage());
454 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
455 throw new Error
.GroupNotFound(e
.getMessage());
460 public long sendGroupMessageReaction(
462 final boolean remove
,
463 final String targetAuthor
,
464 final long targetSentTimestamp
,
468 final var results
= m
.sendMessageReaction(emoji
,
470 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
472 Set
.of(getGroupRecipientIdentifier(groupId
)));
473 checkSendMessageResults(results
);
474 return results
.timestamp();
475 } catch (IOException e
) {
476 throw new Error
.Failure(e
.getMessage());
477 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
478 throw new Error
.GroupNotFound(e
.getMessage());
479 } catch (UnregisteredRecipientException e
) {
480 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
484 // Since contact names might be empty if not defined, also potentially return
487 public String
getContactName(final String number
) {
488 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
489 return name
== null ?
"" : name
;
493 public void setContactName(final String number
, final String name
) {
495 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
496 } catch (NotMasterDeviceException e
) {
497 throw new Error
.Failure("This command doesn't work on linked devices.");
498 } catch (IOException e
) {
499 throw new Error
.Failure("Contact is not registered.");
500 } catch (UnregisteredRecipientException e
) {
501 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
506 public void setExpirationTimer(final String number
, final int expiration
) {
508 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
509 } catch (IOException e
) {
510 throw new Error
.Failure(e
.getMessage());
511 } catch (UnregisteredRecipientException e
) {
512 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
517 public void setContactBlocked(final String number
, final boolean blocked
) {
519 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
520 } catch (NotMasterDeviceException e
) {
521 throw new Error
.Failure("This command doesn't work on linked devices.");
522 } catch (IOException e
) {
523 throw new Error
.Failure(e
.getMessage());
524 } catch (UnregisteredRecipientException e
) {
525 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
530 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
532 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
533 } catch (NotMasterDeviceException e
) {
534 throw new Error
.Failure("This command doesn't work on linked devices.");
535 } catch (GroupNotFoundException e
) {
536 throw new Error
.GroupNotFound(e
.getMessage());
537 } catch (IOException e
) {
538 throw new Error
.Failure(e
.getMessage());
543 public List
<byte[]> getGroupIds() {
544 var groups
= m
.getGroups();
545 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
549 public DBusPath
getGroup(final byte[] groupId
) {
551 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
552 if (groupOptional
.isEmpty()) {
553 throw new Error
.GroupNotFound("Group not found");
555 return groupOptional
.get().getObjectPath();
559 public List
<StructGroup
> listGroups() {
565 public String
getGroupName(final byte[] groupId
) {
566 var group
= m
.getGroup(getGroupId(groupId
));
567 if (group
== null || group
.title() == null) {
570 return group
.title();
575 public List
<String
> getGroupMembers(final byte[] groupId
) {
576 var group
= m
.getGroup(getGroupId(groupId
));
580 final var members
= group
.members();
581 return getRecipientStrings(members
);
586 public byte[] createGroup(
587 final String name
, final List
<String
> members
, final String avatar
588 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
589 return updateGroup(new byte[0], name
, members
, avatar
);
593 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
595 groupId
= nullIfEmpty(groupId
);
596 name
= nullIfEmpty(name
);
597 avatar
= nullIfEmpty(avatar
);
598 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
599 if (groupId
== null) {
600 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
602 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
603 return results
.first().serialize();
605 final var results
= m
.updateGroup(getGroupId(groupId
),
606 UpdateGroup
.newBuilder()
608 .withMembers(memberIdentifiers
)
609 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
611 if (results
!= null) {
612 checkGroupSendMessageResults(results
.timestamp(), results
.results());
616 } catch (IOException e
) {
617 throw new Error
.Failure(e
.getMessage());
618 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
619 throw new Error
.GroupNotFound(e
.getMessage());
620 } catch (AttachmentInvalidException e
) {
621 throw new Error
.AttachmentInvalid(e
.getMessage());
622 } catch (UnregisteredRecipientException e
) {
623 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
628 public boolean isRegistered() {
633 public boolean isRegistered(String number
) {
634 var result
= isRegistered(List
.of(number
));
635 return result
.get(0);
639 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
640 if (numbers
.isEmpty()) {
644 Map
<String
, Pair
<String
, UUID
>> registered
;
646 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
647 } catch (IOException e
) {
648 throw new Error
.Failure(e
.getMessage());
651 return numbers
.stream().map(number
-> {
652 var uuid
= registered
.get(number
).second();
658 public void updateProfile(
664 final boolean removeAvatar
667 givenName
= nullIfEmpty(givenName
);
668 familyName
= nullIfEmpty(familyName
);
669 about
= nullIfEmpty(about
);
670 aboutEmoji
= nullIfEmpty(aboutEmoji
);
671 avatarPath
= nullIfEmpty(avatarPath
);
672 Optional
<File
> avatarFile
= removeAvatar
674 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
675 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
676 } catch (IOException e
) {
677 throw new Error
.Failure(e
.getMessage());
682 public void updateProfile(
685 final String aboutEmoji
,
687 final boolean removeAvatar
689 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
693 public void removePin() {
695 m
.setRegistrationLockPin(Optional
.empty());
696 } catch (IOException e
) {
697 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
698 } catch (NotMasterDeviceException e
) {
699 throw new Error
.Failure("This command doesn't work on linked devices.");
704 public void setPin(String registrationLockPin
) {
706 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
707 } catch (IOException e
) {
708 throw new Error
.Failure("Set pin error: " + e
.getMessage());
709 } catch (NotMasterDeviceException e
) {
710 throw new Error
.Failure("This command doesn't work on linked devices.");
714 // Provide option to query a version string in order to react on potential
715 // future interface changes
717 public String
version() {
718 return BaseConfig
.PROJECT_VERSION
;
721 // Create a unique list of Numbers from Identities and Contacts to really get
722 // all numbers the system knows
724 public List
<String
> listNumbers() {
725 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
726 m
.getContacts().stream().map(Pair
::first
))
727 .map(a
-> a
.number().orElse(null))
728 .filter(Objects
::nonNull
)
734 public List
<String
> getContactNumber(final String name
) {
735 // Contact names have precedence.
736 var numbers
= new ArrayList
<String
>();
737 var contacts
= m
.getContacts();
738 for (var c
: contacts
) {
739 if (name
.equals(c
.second().getName())) {
740 numbers
.add(c
.first().getLegacyIdentifier());
743 // Try profiles if no contact name was found
744 for (var identity
: m
.getIdentities()) {
745 final var address
= identity
.recipient();
746 var number
= address
.number().orElse(null);
747 if (number
!= null) {
748 Profile profile
= null;
750 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
751 } catch (IOException
| UnregisteredRecipientException ignored
) {
753 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
762 public void quitGroup(final byte[] groupId
) {
763 var group
= getGroupId(groupId
);
765 m
.quitGroup(group
, Set
.of());
766 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
767 throw new Error
.GroupNotFound(e
.getMessage());
768 } catch (IOException
| LastGroupAdminException e
) {
769 throw new Error
.Failure(e
.getMessage());
770 } catch (UnregisteredRecipientException e
) {
771 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
776 public byte[] joinGroup(final String groupLink
) {
778 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
779 if (linkUrl
== null) {
780 throw new Error
.Failure("Group link is invalid:");
782 final var result
= m
.joinGroup(linkUrl
);
783 return result
.first().serialize();
784 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
785 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
786 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
787 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
788 } catch (IOException e
) {
789 throw new Error
.Failure(e
.getMessage());
794 public boolean isContactBlocked(final String number
) {
795 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
799 public boolean isGroupBlocked(final byte[] groupId
) {
800 var group
= m
.getGroup(getGroupId(groupId
));
804 return group
.isBlocked();
809 public boolean isMember(final byte[] groupId
) {
810 var group
= m
.getGroup(getGroupId(groupId
));
814 return group
.isMember();
819 public String
uploadStickerPack(String stickerPackPath
) {
820 File path
= new File(stickerPackPath
);
822 return m
.uploadStickerPack(path
).toString();
823 } catch (IOException e
) {
824 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
825 } catch (StickerPackInvalidException e
) {
826 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
830 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
831 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
837 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
839 if (result
.isIdentityFailure()) {
840 throw new Error
.UntrustedIdentity(message
);
842 throw new Error
.Failure(message
);
846 private void checkSendMessageResults(final SendMessageResults results
) {
847 final var sendMessageResults
= results
.results().values().stream().findFirst();
848 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
849 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
853 if (results
.hasSuccess()) {
857 var message
= new StringBuilder();
858 message
.append("Failed to send messages:\n");
859 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
860 for (var error
: errors
) {
861 message
.append(error
).append('\n');
863 message
.append(results
.timestamp());
865 throw new Error
.Failure(message
.toString());
868 private static void checkGroupSendMessageResults(
869 long timestamp
, Collection
<SendMessageResult
> results
870 ) throws DBusExecutionException
{
871 if (results
.size() == 1) {
872 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
876 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
877 if (errors
.size() == 0 || errors
.size() < results
.size()) {
881 var message
= new StringBuilder();
882 message
.append("Failed to send message:\n");
883 for (var error
: errors
) {
884 message
.append(error
).append('\n');
886 message
.append(timestamp
);
888 throw new Error
.Failure(message
.toString());
891 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
892 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
895 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
896 final Collection
<String
> recipientStrings
, final String localNumber
897 ) throws DBusExecutionException
{
898 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
899 for (var recipientString
: recipientStrings
) {
900 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
905 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
906 final String recipientString
, final String localNumber
907 ) throws DBusExecutionException
{
909 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
910 } catch (InvalidNumberException e
) {
911 throw new Error
.InvalidNumber(e
.getMessage());
915 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
916 return new RecipientIdentifier
.Group(getGroupId(groupId
));
919 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
921 return GroupId
.unknownVersion(groupId
);
922 } catch (Throwable e
) {
923 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
927 private byte[] nullIfEmpty(final byte[] array
) {
928 return array
.length
== 0 ?
null : array
;
931 private String
nullIfEmpty(final String name
) {
932 return name
.isEmpty() ?
null : name
;
935 private String
emptyIfNull(final String string
) {
936 return string
== null ?
"" : string
;
939 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
940 return basePath
+ "/Devices/" + deviceId
;
943 private void updateDevices() {
944 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
946 linkedDevices
= m
.getLinkedDevices();
947 } catch (IOException e
) {
948 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
953 linkedDevices
.forEach(d
-> {
954 final var object
= new DbusSignalDeviceImpl(d
);
955 final var deviceObjectPath
= object
.getObjectPath();
956 exportObject(object
);
957 if (d
.isThisDevice()) {
958 thisDevice
= new DBusPath(deviceObjectPath
);
960 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
964 private void unExportDevices() {
965 this.devices
.stream()
966 .map(StructDevice
::getObjectPath
)
967 .map(DBusPath
::getPath
)
968 .forEach(connection
::unExportObject
);
969 this.devices
.clear();
972 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
973 return basePath
+ "/Groups/" + Base64
.getEncoder()
974 .encodeToString(groupId
)
980 private void updateGroups() {
981 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
982 groups
= m
.getGroups();
986 groups
.forEach(g
-> {
987 final var object
= new DbusSignalGroupImpl(g
.groupId());
988 exportObject(object
);
989 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
990 g
.groupId().serialize(),
991 emptyIfNull(g
.title())));
995 private void unExportGroups() {
996 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
1000 private static String
getConfigurationObjectPath(String basePath
) {
1001 return basePath
+ "/Configuration";
1004 private void updateConfiguration() {
1005 unExportConfiguration();
1006 final var object
= new DbusSignalConfigurationImpl();
1007 exportObject(object
);
1010 private void unExportConfiguration() {
1011 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
1012 connection
.unExportObject(objectPath
);
1015 private void exportObject(final DBusInterface object
) {
1017 connection
.exportObject(object
);
1018 logger
.debug("Exported dbus object: " + object
.getObjectPath());
1019 } catch (DBusException e
) {
1020 e
.printStackTrace();
1024 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
1026 private final org
.asamk
.signal
.manager
.api
.Device device
;
1028 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1029 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1030 List
.of(new DbusProperty
<>("Id", device
::id
),
1031 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1032 new DbusProperty
<>("Created", device
::created
),
1033 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1034 this.device
= device
;
1038 public String
getObjectPath() {
1039 return getDeviceObjectPath(objectPath
, device
.id());
1043 public void removeDevice() throws Error
.Failure
{
1045 m
.removeLinkedDevices(device
.id());
1047 } catch (IOException e
) {
1048 throw new Error
.Failure(e
.getMessage());
1052 private void setDeviceName(String name
) {
1053 if (!device
.isThisDevice()) {
1054 throw new Error
.Failure("Only the name of this device can be changed");
1057 m
.updateAccountAttributes(name
);
1058 // update device list
1060 } catch (IOException e
) {
1061 throw new Error
.Failure(e
.getMessage());
1066 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1068 public DbusSignalConfigurationImpl(
1070 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1071 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1072 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1073 this::getUnidentifiedDeliveryIndicators
,
1074 this::setUnidentifiedDeliveryIndicators
),
1075 new DbusProperty
<>("TypingIndicators",
1076 this::getTypingIndicators
,
1077 this::setTypingIndicators
),
1078 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1083 public String
getObjectPath() {
1084 return getConfigurationObjectPath(objectPath
);
1087 public void setReadReceipts(Boolean readReceipts
) {
1088 setConfiguration(readReceipts
, null, null, null);
1091 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1092 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1095 public void setTypingIndicators(Boolean typingIndicators
) {
1096 setConfiguration(null, null, typingIndicators
, null);
1099 public void setLinkPreviews(Boolean linkPreviews
) {
1100 setConfiguration(null, null, null, linkPreviews
);
1103 private void setConfiguration(
1104 Boolean readReceipts
,
1105 Boolean unidentifiedDeliveryIndicators
,
1106 Boolean typingIndicators
,
1107 Boolean linkPreviews
1110 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1111 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1112 Optional
.ofNullable(typingIndicators
),
1113 Optional
.ofNullable(linkPreviews
)));
1114 } catch (IOException e
) {
1115 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1116 } catch (NotMasterDeviceException e
) {
1117 throw new Error
.Failure("This command doesn't work on linked devices.");
1121 private boolean getReadReceipts() {
1122 return m
.getConfiguration().readReceipts().orElse(false);
1125 private boolean getUnidentifiedDeliveryIndicators() {
1126 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1129 private boolean getTypingIndicators() {
1130 return m
.getConfiguration().typingIndicators().orElse(false);
1133 private boolean getLinkPreviews() {
1134 return m
.getConfiguration().linkPreviews().orElse(false);
1138 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1140 private final GroupId groupId
;
1142 public DbusSignalGroupImpl(final GroupId groupId
) {
1143 this.groupId
= groupId
;
1144 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1145 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1146 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1147 new DbusProperty
<>("Description",
1148 () -> emptyIfNull(getGroup().description()),
1149 this::setGroupDescription
),
1150 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1151 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1152 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1153 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1154 new DbusProperty
<>("MessageExpirationTimer",
1155 () -> getGroup().messageExpirationTimer(),
1156 this::setMessageExpirationTime
),
1157 new DbusProperty
<>("Members",
1158 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1159 new DbusProperty
<>("PendingMembers",
1160 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1161 new DbusProperty
<>("RequestingMembers",
1162 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1163 new DbusProperty
<>("Admins",
1164 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1165 new DbusProperty
<>("PermissionAddMember",
1166 () -> getGroup().permissionAddMember().name(),
1167 this::setGroupPermissionAddMember
),
1168 new DbusProperty
<>("PermissionEditDetails",
1169 () -> getGroup().permissionEditDetails().name(),
1170 this::setGroupPermissionEditDetails
),
1171 new DbusProperty
<>("PermissionSendMessage",
1172 () -> getGroup().permissionSendMessage().name(),
1173 this::setGroupPermissionSendMessage
),
1174 new DbusProperty
<>("GroupInviteLink", () -> {
1175 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1176 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1181 public String
getObjectPath() {
1182 return getGroupObjectPath(objectPath
, groupId
.serialize());
1186 public void quitGroup() throws Error
.Failure
{
1188 m
.quitGroup(groupId
, Set
.of());
1189 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1190 throw new Error
.GroupNotFound(e
.getMessage());
1191 } catch (IOException e
) {
1192 throw new Error
.Failure(e
.getMessage());
1193 } catch (LastGroupAdminException e
) {
1194 throw new Error
.LastGroupAdmin(e
.getMessage());
1195 } catch (UnregisteredRecipientException e
) {
1196 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1201 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1203 m
.deleteGroup(groupId
);
1204 } catch (IOException e
) {
1205 throw new Error
.Failure(e
.getMessage());
1211 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1212 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1213 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1217 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1218 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1219 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1223 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1224 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1225 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1229 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1230 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1231 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1235 public void resetLink() throws Error
.Failure
{
1236 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1240 public void disableLink() throws Error
.Failure
{
1241 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1245 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1246 updateGroup(UpdateGroup
.newBuilder()
1247 .withGroupLinkState(requiresApproval
1248 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1249 : GroupLinkState
.ENABLED
)
1253 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1254 return m
.getGroup(groupId
);
1257 private void setGroupName(final String name
) {
1258 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1261 private void setGroupDescription(final String description
) {
1262 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1265 private void setGroupAvatar(final String avatar
) {
1266 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1269 private void setMessageExpirationTime(final int expirationTime
) {
1270 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1273 private void setGroupPermissionAddMember(final String permission
) {
1274 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1277 private void setGroupPermissionEditDetails(final String permission
) {
1278 updateGroup(UpdateGroup
.newBuilder()
1279 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1283 private void setGroupPermissionSendMessage(final String permission
) {
1284 updateGroup(UpdateGroup
.newBuilder()
1285 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1289 private void setIsBlocked(final boolean isBlocked
) {
1291 m
.setGroupBlocked(groupId
, isBlocked
);
1292 } catch (NotMasterDeviceException e
) {
1293 throw new Error
.Failure("This command doesn't work on linked devices.");
1294 } catch (GroupNotFoundException e
) {
1295 throw new Error
.GroupNotFound(e
.getMessage());
1296 } catch (IOException e
) {
1297 throw new Error
.Failure(e
.getMessage());
1301 private void updateGroup(final UpdateGroup updateGroup
) {
1303 m
.updateGroup(groupId
, updateGroup
);
1304 } catch (IOException e
) {
1305 throw new Error
.Failure(e
.getMessage());
1306 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1307 throw new Error
.GroupNotFound(e
.getMessage());
1308 } catch (AttachmentInvalidException e
) {
1309 throw new Error
.AttachmentInvalid(e
.getMessage());
1310 } catch (UnregisteredRecipientException e
) {
1311 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");