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
.api
.UserStatus
;
23 import org
.asamk
.signal
.manager
.groups
.GroupId
;
24 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
25 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
26 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
27 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
28 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
29 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
30 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
31 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
32 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
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
;
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
, UserStatus
> registered
;
646 registered
= m
.getUserStatus(new HashSet
<>(numbers
));
647 } catch (IOException e
) {
648 throw new Error
.Failure(e
.getMessage());
651 return numbers
.stream().map(number
-> registered
.get(number
).uuid() != null).toList();
655 public void updateProfile(
661 final boolean removeAvatar
664 givenName
= nullIfEmpty(givenName
);
665 familyName
= nullIfEmpty(familyName
);
666 about
= nullIfEmpty(about
);
667 aboutEmoji
= nullIfEmpty(aboutEmoji
);
668 avatarPath
= nullIfEmpty(avatarPath
);
669 Optional
<File
> avatarFile
= removeAvatar
671 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
672 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
673 } catch (IOException e
) {
674 throw new Error
.Failure(e
.getMessage());
679 public void updateProfile(
682 final String aboutEmoji
,
684 final boolean removeAvatar
686 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
690 public void removePin() {
692 m
.setRegistrationLockPin(Optional
.empty());
693 } catch (IOException e
) {
694 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
695 } catch (NotMasterDeviceException e
) {
696 throw new Error
.Failure("This command doesn't work on linked devices.");
701 public void setPin(String registrationLockPin
) {
703 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
704 } catch (IOException e
) {
705 throw new Error
.Failure("Set pin error: " + e
.getMessage());
706 } catch (NotMasterDeviceException e
) {
707 throw new Error
.Failure("This command doesn't work on linked devices.");
711 // Provide option to query a version string in order to react on potential
712 // future interface changes
714 public String
version() {
715 return BaseConfig
.PROJECT_VERSION
;
718 // Create a unique list of Numbers from Identities and Contacts to really get
719 // all numbers the system knows
721 public List
<String
> listNumbers() {
722 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
723 m
.getContacts().stream().map(Pair
::first
))
724 .map(a
-> a
.number().orElse(null))
725 .filter(Objects
::nonNull
)
731 public List
<String
> getContactNumber(final String name
) {
732 // Contact names have precedence.
733 var numbers
= new ArrayList
<String
>();
734 var contacts
= m
.getContacts();
735 for (var c
: contacts
) {
736 if (name
.equals(c
.second().getName())) {
737 numbers
.add(c
.first().getLegacyIdentifier());
740 // Try profiles if no contact name was found
741 for (var identity
: m
.getIdentities()) {
742 final var address
= identity
.recipient();
743 var number
= address
.number().orElse(null);
744 if (number
!= null) {
745 Profile profile
= null;
747 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
748 } catch (IOException
| UnregisteredRecipientException ignored
) {
750 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
759 public void quitGroup(final byte[] groupId
) {
760 var group
= getGroupId(groupId
);
762 m
.quitGroup(group
, Set
.of());
763 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
764 throw new Error
.GroupNotFound(e
.getMessage());
765 } catch (IOException
| LastGroupAdminException e
) {
766 throw new Error
.Failure(e
.getMessage());
767 } catch (UnregisteredRecipientException e
) {
768 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
773 public byte[] joinGroup(final String groupLink
) {
775 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
776 if (linkUrl
== null) {
777 throw new Error
.Failure("Group link is invalid:");
779 final var result
= m
.joinGroup(linkUrl
);
780 return result
.first().serialize();
781 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
782 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
783 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
784 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
785 } catch (IOException e
) {
786 throw new Error
.Failure(e
.getMessage());
791 public boolean isContactBlocked(final String number
) {
792 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
796 public boolean isGroupBlocked(final byte[] groupId
) {
797 var group
= m
.getGroup(getGroupId(groupId
));
801 return group
.isBlocked();
806 public boolean isMember(final byte[] groupId
) {
807 var group
= m
.getGroup(getGroupId(groupId
));
811 return group
.isMember();
816 public String
uploadStickerPack(String stickerPackPath
) {
817 File path
= new File(stickerPackPath
);
819 return m
.uploadStickerPack(path
).toString();
820 } catch (IOException e
) {
821 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
822 } catch (StickerPackInvalidException e
) {
823 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
827 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
828 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
834 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
836 if (result
.isIdentityFailure()) {
837 throw new Error
.UntrustedIdentity(message
);
839 throw new Error
.Failure(message
);
843 private void checkSendMessageResults(final SendMessageResults results
) {
844 final var sendMessageResults
= results
.results().values().stream().findFirst();
845 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
846 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
850 if (results
.hasSuccess()) {
854 var message
= new StringBuilder();
855 message
.append("Failed to send messages:\n");
856 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
857 for (var error
: errors
) {
858 message
.append(error
).append('\n');
860 message
.append(results
.timestamp());
862 throw new Error
.Failure(message
.toString());
865 private static void checkGroupSendMessageResults(
866 long timestamp
, Collection
<SendMessageResult
> results
867 ) throws DBusExecutionException
{
868 if (results
.size() == 1) {
869 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
873 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
874 if (errors
.size() == 0 || errors
.size() < results
.size()) {
878 var message
= new StringBuilder();
879 message
.append("Failed to send message:\n");
880 for (var error
: errors
) {
881 message
.append(error
).append('\n');
883 message
.append(timestamp
);
885 throw new Error
.Failure(message
.toString());
888 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
889 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
892 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
893 final Collection
<String
> recipientStrings
, final String localNumber
894 ) throws DBusExecutionException
{
895 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
896 for (var recipientString
: recipientStrings
) {
897 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
902 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
903 final String recipientString
, final String localNumber
904 ) throws DBusExecutionException
{
906 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
907 } catch (InvalidNumberException e
) {
908 throw new Error
.InvalidNumber(e
.getMessage());
912 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
913 return new RecipientIdentifier
.Group(getGroupId(groupId
));
916 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
918 return GroupId
.unknownVersion(groupId
);
919 } catch (Throwable e
) {
920 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
924 private byte[] nullIfEmpty(final byte[] array
) {
925 return array
.length
== 0 ?
null : array
;
928 private String
nullIfEmpty(final String name
) {
929 return name
.isEmpty() ?
null : name
;
932 private String
emptyIfNull(final String string
) {
933 return string
== null ?
"" : string
;
936 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
937 return basePath
+ "/Devices/" + deviceId
;
940 private void updateDevices() {
941 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
943 linkedDevices
= m
.getLinkedDevices();
944 } catch (IOException e
) {
945 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
950 linkedDevices
.forEach(d
-> {
951 final var object
= new DbusSignalDeviceImpl(d
);
952 final var deviceObjectPath
= object
.getObjectPath();
953 exportObject(object
);
954 if (d
.isThisDevice()) {
955 thisDevice
= new DBusPath(deviceObjectPath
);
957 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
961 private void unExportDevices() {
962 this.devices
.stream()
963 .map(StructDevice
::getObjectPath
)
964 .map(DBusPath
::getPath
)
965 .forEach(connection
::unExportObject
);
966 this.devices
.clear();
969 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
970 return basePath
+ "/Groups/" + Base64
.getEncoder()
971 .encodeToString(groupId
)
977 private void updateGroups() {
978 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
979 groups
= m
.getGroups();
983 groups
.forEach(g
-> {
984 final var object
= new DbusSignalGroupImpl(g
.groupId());
985 exportObject(object
);
986 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
987 g
.groupId().serialize(),
988 emptyIfNull(g
.title())));
992 private void unExportGroups() {
993 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
997 private static String
getConfigurationObjectPath(String basePath
) {
998 return basePath
+ "/Configuration";
1001 private void updateConfiguration() {
1002 unExportConfiguration();
1003 final var object
= new DbusSignalConfigurationImpl();
1004 exportObject(object
);
1007 private void unExportConfiguration() {
1008 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
1009 connection
.unExportObject(objectPath
);
1012 private void exportObject(final DBusInterface object
) {
1014 connection
.exportObject(object
);
1015 logger
.debug("Exported dbus object: " + object
.getObjectPath());
1016 } catch (DBusException e
) {
1017 e
.printStackTrace();
1021 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
1023 private final org
.asamk
.signal
.manager
.api
.Device device
;
1025 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1026 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1027 List
.of(new DbusProperty
<>("Id", device
::id
),
1028 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1029 new DbusProperty
<>("Created", device
::created
),
1030 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1031 this.device
= device
;
1035 public String
getObjectPath() {
1036 return getDeviceObjectPath(objectPath
, device
.id());
1040 public void removeDevice() throws Error
.Failure
{
1042 m
.removeLinkedDevices(device
.id());
1044 } catch (IOException e
) {
1045 throw new Error
.Failure(e
.getMessage());
1049 private void setDeviceName(String name
) {
1050 if (!device
.isThisDevice()) {
1051 throw new Error
.Failure("Only the name of this device can be changed");
1054 m
.updateAccountAttributes(name
);
1055 // update device list
1057 } catch (IOException e
) {
1058 throw new Error
.Failure(e
.getMessage());
1063 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1065 public DbusSignalConfigurationImpl(
1067 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1068 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1069 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1070 this::getUnidentifiedDeliveryIndicators
,
1071 this::setUnidentifiedDeliveryIndicators
),
1072 new DbusProperty
<>("TypingIndicators",
1073 this::getTypingIndicators
,
1074 this::setTypingIndicators
),
1075 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1080 public String
getObjectPath() {
1081 return getConfigurationObjectPath(objectPath
);
1084 public void setReadReceipts(Boolean readReceipts
) {
1085 setConfiguration(readReceipts
, null, null, null);
1088 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1089 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1092 public void setTypingIndicators(Boolean typingIndicators
) {
1093 setConfiguration(null, null, typingIndicators
, null);
1096 public void setLinkPreviews(Boolean linkPreviews
) {
1097 setConfiguration(null, null, null, linkPreviews
);
1100 private void setConfiguration(
1101 Boolean readReceipts
,
1102 Boolean unidentifiedDeliveryIndicators
,
1103 Boolean typingIndicators
,
1104 Boolean linkPreviews
1107 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1108 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1109 Optional
.ofNullable(typingIndicators
),
1110 Optional
.ofNullable(linkPreviews
)));
1111 } catch (IOException e
) {
1112 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1113 } catch (NotMasterDeviceException e
) {
1114 throw new Error
.Failure("This command doesn't work on linked devices.");
1118 private boolean getReadReceipts() {
1119 return m
.getConfiguration().readReceipts().orElse(false);
1122 private boolean getUnidentifiedDeliveryIndicators() {
1123 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1126 private boolean getTypingIndicators() {
1127 return m
.getConfiguration().typingIndicators().orElse(false);
1130 private boolean getLinkPreviews() {
1131 return m
.getConfiguration().linkPreviews().orElse(false);
1135 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1137 private final GroupId groupId
;
1139 public DbusSignalGroupImpl(final GroupId groupId
) {
1140 this.groupId
= groupId
;
1141 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1142 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1143 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1144 new DbusProperty
<>("Description",
1145 () -> emptyIfNull(getGroup().description()),
1146 this::setGroupDescription
),
1147 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1148 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1149 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1150 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1151 new DbusProperty
<>("MessageExpirationTimer",
1152 () -> getGroup().messageExpirationTimer(),
1153 this::setMessageExpirationTime
),
1154 new DbusProperty
<>("Members",
1155 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1156 new DbusProperty
<>("PendingMembers",
1157 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1158 new DbusProperty
<>("RequestingMembers",
1159 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1160 new DbusProperty
<>("Admins",
1161 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1162 new DbusProperty
<>("Banned",
1163 () -> new Variant
<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
1164 new DbusProperty
<>("PermissionAddMember",
1165 () -> getGroup().permissionAddMember().name(),
1166 this::setGroupPermissionAddMember
),
1167 new DbusProperty
<>("PermissionEditDetails",
1168 () -> getGroup().permissionEditDetails().name(),
1169 this::setGroupPermissionEditDetails
),
1170 new DbusProperty
<>("PermissionSendMessage",
1171 () -> getGroup().permissionSendMessage().name(),
1172 this::setGroupPermissionSendMessage
),
1173 new DbusProperty
<>("GroupInviteLink", () -> {
1174 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1175 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1180 public String
getObjectPath() {
1181 return getGroupObjectPath(objectPath
, groupId
.serialize());
1185 public void quitGroup() throws Error
.Failure
{
1187 m
.quitGroup(groupId
, Set
.of());
1188 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1189 throw new Error
.GroupNotFound(e
.getMessage());
1190 } catch (IOException e
) {
1191 throw new Error
.Failure(e
.getMessage());
1192 } catch (LastGroupAdminException e
) {
1193 throw new Error
.LastGroupAdmin(e
.getMessage());
1194 } catch (UnregisteredRecipientException e
) {
1195 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1200 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1202 m
.deleteGroup(groupId
);
1203 } catch (IOException e
) {
1204 throw new Error
.Failure(e
.getMessage());
1210 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1211 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1212 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1216 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1217 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1218 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1222 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1223 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1224 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1228 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1229 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1230 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1234 public void resetLink() throws Error
.Failure
{
1235 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1239 public void disableLink() throws Error
.Failure
{
1240 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1244 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1245 updateGroup(UpdateGroup
.newBuilder()
1246 .withGroupLinkState(requiresApproval
1247 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1248 : GroupLinkState
.ENABLED
)
1252 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1253 return m
.getGroup(groupId
);
1256 private void setGroupName(final String name
) {
1257 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1260 private void setGroupDescription(final String description
) {
1261 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1264 private void setGroupAvatar(final String avatar
) {
1265 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1268 private void setMessageExpirationTime(final int expirationTime
) {
1269 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1272 private void setGroupPermissionAddMember(final String permission
) {
1273 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1276 private void setGroupPermissionEditDetails(final String permission
) {
1277 updateGroup(UpdateGroup
.newBuilder()
1278 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1282 private void setGroupPermissionSendMessage(final String permission
) {
1283 updateGroup(UpdateGroup
.newBuilder()
1284 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1288 private void setIsBlocked(final boolean isBlocked
) {
1290 m
.setGroupBlocked(groupId
, isBlocked
);
1291 } catch (NotMasterDeviceException e
) {
1292 throw new Error
.Failure("This command doesn't work on linked devices.");
1293 } catch (GroupNotFoundException e
) {
1294 throw new Error
.GroupNotFound(e
.getMessage());
1295 } catch (IOException e
) {
1296 throw new Error
.Failure(e
.getMessage());
1300 private void updateGroup(final UpdateGroup updateGroup
) {
1302 m
.updateGroup(groupId
, updateGroup
);
1303 } catch (IOException e
) {
1304 throw new Error
.Failure(e
.getMessage());
1305 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1306 throw new Error
.GroupNotFound(e
.getMessage());
1307 } catch (AttachmentInvalidException e
) {
1308 throw new Error
.AttachmentInvalid(e
.getMessage());
1309 } catch (UnregisteredRecipientException e
) {
1310 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");