1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.BaseConfig
;
5 import org
.asamk
.signal
.manager
.Manager
;
6 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
7 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
8 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
9 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
10 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
11 import org
.asamk
.signal
.manager
.api
.Message
;
12 import org
.asamk
.signal
.manager
.api
.NotPrimaryDeviceException
;
13 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
14 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
15 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
16 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
17 import org
.asamk
.signal
.manager
.api
.TypingAction
;
18 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
19 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
20 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
21 import org
.asamk
.signal
.manager
.api
.UserStatus
;
22 import org
.asamk
.signal
.manager
.groups
.GroupId
;
23 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
24 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
25 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
26 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
27 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
28 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
29 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
30 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
31 import org
.asamk
.signal
.util
.SendMessageResultUtils
;
32 import org
.freedesktop
.dbus
.DBusPath
;
33 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
35 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
36 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
37 import org
.freedesktop
.dbus
.types
.Variant
;
38 import org
.slf4j
.Logger
;
39 import org
.slf4j
.LoggerFactory
;
42 import java
.io
.IOException
;
44 import java
.net
.URISyntaxException
;
45 import java
.util
.ArrayList
;
46 import java
.util
.Arrays
;
47 import java
.util
.Base64
;
48 import java
.util
.Collection
;
49 import java
.util
.HashSet
;
50 import java
.util
.List
;
52 import java
.util
.Objects
;
53 import java
.util
.Optional
;
55 import java
.util
.stream
.Collectors
;
57 public class DbusSignalImpl
implements Signal
{
59 private final Manager m
;
60 private final DBusConnection connection
;
61 private final String objectPath
;
62 private final boolean noReceiveOnStart
;
64 private DBusPath thisDevice
;
65 private final List
<StructDevice
> devices
= new ArrayList
<>();
66 private final List
<StructGroup
> groups
= new ArrayList
<>();
67 private DbusReceiveMessageHandler dbusMessageHandler
;
68 private int subscriberCount
;
70 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
72 public DbusSignalImpl(
73 final Manager m
, DBusConnection connection
, final String objectPath
, final boolean noReceiveOnStart
76 this.connection
= connection
;
77 this.objectPath
= objectPath
;
78 this.noReceiveOnStart
= noReceiveOnStart
;
80 m
.addAddressChangedListener(() -> {
86 public void initObjects() {
88 if (!noReceiveOnStart
) {
93 private void exportObjects() {
98 updateConfiguration();
101 public void close() {
102 if (dbusMessageHandler
!= null) {
103 m
.removeReceiveHandler(dbusMessageHandler
);
104 dbusMessageHandler
= null;
109 private void unExportObjects() {
112 unExportConfiguration();
113 connection
.unExportObject(this.objectPath
);
117 public String
getObjectPath() {
122 public String
getSelfNumber() {
123 return m
.getSelfNumber();
127 public void subscribeReceive() {
128 if (dbusMessageHandler
== null) {
129 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
130 m
.addReceiveHandler(dbusMessageHandler
);
136 public void unsubscribeReceive() {
137 subscriberCount
= Math
.max(0, subscriberCount
- 1);
138 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
139 m
.removeReceiveHandler(dbusMessageHandler
);
140 dbusMessageHandler
= null;
145 public void submitRateLimitChallenge(String challenge
, String captcha
) {
147 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
148 } catch (IOException e
) {
149 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
155 public void unregister() throws Error
.Failure
{
158 } catch (IOException e
) {
159 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
164 public void deleteAccount() throws Error
.Failure
{
167 } catch (IOException e
) {
168 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
173 public void addDevice(String uri
) {
175 m
.addDeviceLink(new URI(uri
));
176 } catch (IOException
| InvalidDeviceLinkException e
) {
177 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
178 } catch (URISyntaxException e
) {
179 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
180 + " Device link uri has invalid format: "
186 public DBusPath
getDevice(long deviceId
) {
188 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
189 if (deviceOptional
.isEmpty()) {
190 throw new Error
.DeviceNotFound("Device not found");
192 return deviceOptional
.get().getObjectPath();
196 public List
<StructDevice
> listDevices() {
202 public DBusPath
getThisDevice() {
208 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
209 return sendMessage(message
, attachments
, List
.of(recipient
));
213 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
215 final var results
= m
.sendMessage(new Message(message
,
221 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
222 .map(RecipientIdentifier
.class::cast
)
223 .collect(Collectors
.toSet()));
225 checkSendMessageResults(results
);
226 return results
.timestamp();
227 } catch (AttachmentInvalidException e
) {
228 throw new Error
.AttachmentInvalid(e
.getMessage());
229 } catch (IOException
| InvalidStickerException e
) {
230 throw new Error
.Failure(e
);
231 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
232 throw new Error
.GroupNotFound(e
.getMessage());
233 } catch (UnregisteredRecipientException e
) {
234 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
239 public long sendRemoteDeleteMessage(
240 final long targetSentTimestamp
, final String recipient
242 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
246 public long sendRemoteDeleteMessage(
247 final long targetSentTimestamp
, final List
<String
> recipients
250 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
251 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
252 .map(RecipientIdentifier
.class::cast
)
253 .collect(Collectors
.toSet()));
254 checkSendMessageResults(results
);
255 return results
.timestamp();
256 } catch (IOException e
) {
257 throw new Error
.Failure(e
.getMessage());
258 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
259 throw new Error
.GroupNotFound(e
.getMessage());
264 public long sendMessageReaction(
266 final boolean remove
,
267 final String targetAuthor
,
268 final long targetSentTimestamp
,
269 final String recipient
271 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
275 public long sendMessageReaction(
277 final boolean remove
,
278 final String targetAuthor
,
279 final long targetSentTimestamp
,
280 final List
<String
> recipients
283 final var results
= m
.sendMessageReaction(emoji
,
285 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
287 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
288 .map(RecipientIdentifier
.class::cast
)
289 .collect(Collectors
.toSet()));
290 checkSendMessageResults(results
);
291 return results
.timestamp();
292 } catch (IOException e
) {
293 throw new Error
.Failure(e
.getMessage());
294 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
295 throw new Error
.GroupNotFound(e
.getMessage());
296 } catch (UnregisteredRecipientException e
) {
297 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
302 public void sendTyping(
303 final String recipient
, final boolean stop
304 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
306 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
307 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
308 .map(RecipientIdentifier
.class::cast
)
309 .collect(Collectors
.toSet()));
310 checkSendMessageResults(results
);
311 } catch (IOException e
) {
312 throw new Error
.Failure(e
.getMessage());
313 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
314 throw new Error
.GroupNotFound(e
.getMessage());
319 public void sendReadReceipt(
320 final String recipient
, final List
<Long
> messageIds
321 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
323 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
325 checkSendMessageResults(results
);
326 } catch (IOException e
) {
327 throw new Error
.Failure(e
.getMessage());
332 public void sendViewedReceipt(
333 final String recipient
, final List
<Long
> messageIds
334 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
336 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
338 checkSendMessageResults(results
);
339 } catch (IOException e
) {
340 throw new Error
.Failure(e
.getMessage());
345 public void sendContacts() {
348 } catch (IOException e
) {
349 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
354 public void sendSyncRequest() {
356 m
.requestAllSyncData();
357 } catch (IOException e
) {
358 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
363 public long sendNoteToSelfMessage(
364 final String message
, final List
<String
> attachments
365 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
367 final var results
= m
.sendMessage(new Message(message
,
372 List
.of()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
373 checkSendMessageResults(results
);
374 return results
.timestamp();
375 } catch (AttachmentInvalidException e
) {
376 throw new Error
.AttachmentInvalid(e
.getMessage());
377 } catch (IOException
| InvalidStickerException e
) {
378 throw new Error
.Failure(e
.getMessage());
379 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
380 throw new Error
.GroupNotFound(e
.getMessage());
381 } catch (UnregisteredRecipientException e
) {
382 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
387 public void sendEndSessionMessage(final List
<String
> recipients
) {
389 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
390 checkSendMessageResults(results
);
391 } catch (IOException e
) {
392 throw new Error
.Failure(e
.getMessage());
397 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
398 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
402 public void deleteContact(final String recipient
) throws Error
.Failure
{
403 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
407 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
409 var results
= m
.sendMessage(new Message(message
,
414 List
.of()), 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 (NotPrimaryDeviceException 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
.setContactsBlocked(List
.of(getSingleRecipientIdentifier(number
, m
.getSelfNumber())), blocked
);
520 } catch (NotPrimaryDeviceException 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
.setGroupsBlocked(List
.of(getGroupId(groupId
)), blocked
);
533 } catch (NotPrimaryDeviceException 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 File avatarFile
= removeAvatar
|| avatarPath
== null ?
null : new File(avatarPath
);
670 m
.updateProfile(UpdateProfile
.newBuilder()
671 .withGivenName(givenName
)
672 .withFamilyName(familyName
)
674 .withAboutEmoji(aboutEmoji
)
675 .withAvatar(avatarFile
)
676 .withDeleteAvatar(removeAvatar
)
678 } catch (IOException e
) {
679 throw new Error
.Failure(e
.getMessage());
684 public void updateProfile(
687 final String aboutEmoji
,
689 final boolean removeAvatar
691 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
695 public void removePin() {
697 m
.setRegistrationLockPin(Optional
.empty());
698 } catch (IOException e
) {
699 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
700 } catch (NotPrimaryDeviceException e
) {
701 throw new Error
.Failure("This command doesn't work on linked devices.");
706 public void setPin(String registrationLockPin
) {
708 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
709 } catch (IOException e
) {
710 throw new Error
.Failure("Set pin error: " + e
.getMessage());
711 } catch (NotPrimaryDeviceException e
) {
712 throw new Error
.Failure("This command doesn't work on linked devices.");
716 // Provide option to query a version string in order to react on potential
717 // future interface changes
719 public String
version() {
720 return BaseConfig
.PROJECT_VERSION
;
723 // Create a unique list of Numbers from Identities and Contacts to really get
724 // all numbers the system knows
726 public List
<String
> listNumbers() {
727 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.empty())
729 .map(r
-> r
.getAddress().number().orElse(null))
730 .filter(Objects
::nonNull
)
736 public List
<String
> getContactNumber(final String name
) {
737 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.of(name
))
739 .map(r
-> r
.getAddress().getLegacyIdentifier())
744 public void quitGroup(final byte[] groupId
) {
745 var group
= getGroupId(groupId
);
747 m
.quitGroup(group
, Set
.of());
748 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
749 throw new Error
.GroupNotFound(e
.getMessage());
750 } catch (IOException
| LastGroupAdminException e
) {
751 throw new Error
.Failure(e
.getMessage());
752 } catch (UnregisteredRecipientException e
) {
753 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
758 public byte[] joinGroup(final String groupLink
) {
760 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
761 if (linkUrl
== null) {
762 throw new Error
.Failure("Group link is invalid:");
764 final var result
= m
.joinGroup(linkUrl
);
765 return result
.first().serialize();
766 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
767 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
768 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
769 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
770 } catch (IOException e
) {
771 throw new Error
.Failure(e
.getMessage());
776 public boolean isContactBlocked(final String number
) {
777 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
781 public boolean isGroupBlocked(final byte[] groupId
) {
782 var group
= m
.getGroup(getGroupId(groupId
));
786 return group
.isBlocked();
791 public boolean isMember(final byte[] groupId
) {
792 var group
= m
.getGroup(getGroupId(groupId
));
796 return group
.isMember();
801 public String
uploadStickerPack(String stickerPackPath
) {
802 File path
= new File(stickerPackPath
);
804 return m
.uploadStickerPack(path
).toString();
805 } catch (IOException e
) {
806 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
807 } catch (StickerPackInvalidException e
) {
808 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
812 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
813 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
819 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
821 if (result
.isIdentityFailure()) {
822 throw new Error
.UntrustedIdentity(message
);
824 throw new Error
.Failure(message
);
828 private void checkSendMessageResults(final SendMessageResults results
) {
829 final var sendMessageResults
= results
.results().values().stream().findFirst();
830 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
831 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
835 if (results
.hasSuccess()) {
839 var message
= new StringBuilder();
840 message
.append("Failed to send messages:\n");
841 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
842 for (var error
: errors
) {
843 message
.append(error
).append('\n');
845 message
.append(results
.timestamp());
847 throw new Error
.Failure(message
.toString());
850 private static void checkGroupSendMessageResults(
851 long timestamp
, Collection
<SendMessageResult
> results
852 ) throws DBusExecutionException
{
853 if (results
.size() == 1) {
854 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
858 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
859 if (errors
.size() == 0 || errors
.size() < results
.size()) {
863 var message
= new StringBuilder();
864 message
.append("Failed to send message:\n");
865 for (var error
: errors
) {
866 message
.append(error
).append('\n');
868 message
.append(timestamp
);
870 throw new Error
.Failure(message
.toString());
873 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
874 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
877 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
878 final Collection
<String
> recipientStrings
, final String localNumber
879 ) throws DBusExecutionException
{
880 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
881 for (var recipientString
: recipientStrings
) {
882 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
887 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
888 final String recipientString
, final String localNumber
889 ) throws DBusExecutionException
{
891 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
892 } catch (InvalidNumberException e
) {
893 throw new Error
.InvalidNumber(e
.getMessage());
897 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
898 return new RecipientIdentifier
.Group(getGroupId(groupId
));
901 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
903 return GroupId
.unknownVersion(groupId
);
904 } catch (Throwable e
) {
905 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
909 private byte[] nullIfEmpty(final byte[] array
) {
910 return array
.length
== 0 ?
null : array
;
913 private String
nullIfEmpty(final String name
) {
914 return name
.isEmpty() ?
null : name
;
917 private String
emptyIfNull(final String string
) {
918 return string
== null ?
"" : string
;
921 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
922 return basePath
+ "/Devices/" + deviceId
;
925 private void updateDevices() {
926 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
928 linkedDevices
= m
.getLinkedDevices();
929 } catch (IOException e
) {
930 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
935 linkedDevices
.forEach(d
-> {
936 final var object
= new DbusSignalDeviceImpl(d
);
937 final var deviceObjectPath
= object
.getObjectPath();
938 exportObject(object
);
939 if (d
.isThisDevice()) {
940 thisDevice
= new DBusPath(deviceObjectPath
);
942 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
946 private void unExportDevices() {
947 this.devices
.stream()
948 .map(StructDevice
::getObjectPath
)
949 .map(DBusPath
::getPath
)
950 .forEach(connection
::unExportObject
);
951 this.devices
.clear();
954 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
955 return basePath
+ "/Groups/" + Base64
.getEncoder()
956 .encodeToString(groupId
)
962 private void updateGroups() {
963 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
964 groups
= m
.getGroups();
968 groups
.forEach(g
-> {
969 final var object
= new DbusSignalGroupImpl(g
.groupId());
970 exportObject(object
);
971 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
972 g
.groupId().serialize(),
973 emptyIfNull(g
.title())));
977 private void unExportGroups() {
978 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
982 private static String
getConfigurationObjectPath(String basePath
) {
983 return basePath
+ "/Configuration";
986 private void updateConfiguration() {
987 unExportConfiguration();
988 final var object
= new DbusSignalConfigurationImpl();
989 exportObject(object
);
992 private void unExportConfiguration() {
993 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
994 connection
.unExportObject(objectPath
);
997 private void exportObject(final DBusInterface object
) {
999 connection
.exportObject(object
);
1000 logger
.debug("Exported dbus object: " + object
.getObjectPath());
1001 } catch (DBusException e
) {
1002 e
.printStackTrace();
1006 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
1008 private final org
.asamk
.signal
.manager
.api
.Device device
;
1010 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1011 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1012 List
.of(new DbusProperty
<>("Id", device
::id
),
1013 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1014 new DbusProperty
<>("Created", device
::created
),
1015 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1016 this.device
= device
;
1020 public String
getObjectPath() {
1021 return getDeviceObjectPath(objectPath
, device
.id());
1025 public void removeDevice() throws Error
.Failure
{
1027 m
.removeLinkedDevices(device
.id());
1029 } catch (IOException e
) {
1030 throw new Error
.Failure(e
.getMessage());
1034 private void setDeviceName(String name
) {
1035 if (!device
.isThisDevice()) {
1036 throw new Error
.Failure("Only the name of this device can be changed");
1039 m
.updateAccountAttributes(name
);
1040 // update device list
1042 } catch (IOException e
) {
1043 throw new Error
.Failure(e
.getMessage());
1048 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1050 public DbusSignalConfigurationImpl(
1052 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1053 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1054 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1055 this::getUnidentifiedDeliveryIndicators
,
1056 this::setUnidentifiedDeliveryIndicators
),
1057 new DbusProperty
<>("TypingIndicators",
1058 this::getTypingIndicators
,
1059 this::setTypingIndicators
),
1060 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1065 public String
getObjectPath() {
1066 return getConfigurationObjectPath(objectPath
);
1069 public void setReadReceipts(Boolean readReceipts
) {
1070 setConfiguration(readReceipts
, null, null, null);
1073 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1074 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1077 public void setTypingIndicators(Boolean typingIndicators
) {
1078 setConfiguration(null, null, typingIndicators
, null);
1081 public void setLinkPreviews(Boolean linkPreviews
) {
1082 setConfiguration(null, null, null, linkPreviews
);
1085 private void setConfiguration(
1086 Boolean readReceipts
,
1087 Boolean unidentifiedDeliveryIndicators
,
1088 Boolean typingIndicators
,
1089 Boolean linkPreviews
1092 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1093 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1094 Optional
.ofNullable(typingIndicators
),
1095 Optional
.ofNullable(linkPreviews
)));
1096 } catch (IOException e
) {
1097 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1098 } catch (NotPrimaryDeviceException e
) {
1099 throw new Error
.Failure("This command doesn't work on linked devices.");
1103 private boolean getReadReceipts() {
1104 return m
.getConfiguration().readReceipts().orElse(false);
1107 private boolean getUnidentifiedDeliveryIndicators() {
1108 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1111 private boolean getTypingIndicators() {
1112 return m
.getConfiguration().typingIndicators().orElse(false);
1115 private boolean getLinkPreviews() {
1116 return m
.getConfiguration().linkPreviews().orElse(false);
1120 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1122 private final GroupId groupId
;
1124 public DbusSignalGroupImpl(final GroupId groupId
) {
1125 this.groupId
= groupId
;
1126 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1127 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1128 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1129 new DbusProperty
<>("Description",
1130 () -> emptyIfNull(getGroup().description()),
1131 this::setGroupDescription
),
1132 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1133 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1134 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1135 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1136 new DbusProperty
<>("MessageExpirationTimer",
1137 () -> getGroup().messageExpirationTimer(),
1138 this::setMessageExpirationTime
),
1139 new DbusProperty
<>("Members",
1140 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1141 new DbusProperty
<>("PendingMembers",
1142 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1143 new DbusProperty
<>("RequestingMembers",
1144 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1145 new DbusProperty
<>("Admins",
1146 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1147 new DbusProperty
<>("Banned",
1148 () -> new Variant
<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
1149 new DbusProperty
<>("PermissionAddMember",
1150 () -> getGroup().permissionAddMember().name(),
1151 this::setGroupPermissionAddMember
),
1152 new DbusProperty
<>("PermissionEditDetails",
1153 () -> getGroup().permissionEditDetails().name(),
1154 this::setGroupPermissionEditDetails
),
1155 new DbusProperty
<>("PermissionSendMessage",
1156 () -> getGroup().permissionSendMessage().name(),
1157 this::setGroupPermissionSendMessage
),
1158 new DbusProperty
<>("GroupInviteLink", () -> {
1159 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1160 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1165 public String
getObjectPath() {
1166 return getGroupObjectPath(objectPath
, groupId
.serialize());
1170 public void quitGroup() throws Error
.Failure
{
1172 m
.quitGroup(groupId
, Set
.of());
1173 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1174 throw new Error
.GroupNotFound(e
.getMessage());
1175 } catch (IOException e
) {
1176 throw new Error
.Failure(e
.getMessage());
1177 } catch (LastGroupAdminException e
) {
1178 throw new Error
.LastGroupAdmin(e
.getMessage());
1179 } catch (UnregisteredRecipientException e
) {
1180 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1185 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1187 m
.deleteGroup(groupId
);
1188 } catch (IOException e
) {
1189 throw new Error
.Failure(e
.getMessage());
1195 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1196 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1197 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1201 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1202 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1203 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1207 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1208 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1209 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1213 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1214 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1215 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1219 public void resetLink() throws Error
.Failure
{
1220 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1224 public void disableLink() throws Error
.Failure
{
1225 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1229 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1230 updateGroup(UpdateGroup
.newBuilder()
1231 .withGroupLinkState(requiresApproval
1232 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1233 : GroupLinkState
.ENABLED
)
1237 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1238 return m
.getGroup(groupId
);
1241 private void setGroupName(final String name
) {
1242 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1245 private void setGroupDescription(final String description
) {
1246 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1249 private void setGroupAvatar(final String avatar
) {
1250 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1253 private void setMessageExpirationTime(final int expirationTime
) {
1254 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1257 private void setGroupPermissionAddMember(final String permission
) {
1258 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1261 private void setGroupPermissionEditDetails(final String permission
) {
1262 updateGroup(UpdateGroup
.newBuilder()
1263 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1267 private void setGroupPermissionSendMessage(final String permission
) {
1268 updateGroup(UpdateGroup
.newBuilder()
1269 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1273 private void setIsBlocked(final boolean isBlocked
) {
1275 m
.setGroupsBlocked(List
.of(groupId
), isBlocked
);
1276 } catch (NotPrimaryDeviceException e
) {
1277 throw new Error
.Failure("This command doesn't work on linked devices.");
1278 } catch (GroupNotFoundException e
) {
1279 throw new Error
.GroupNotFound(e
.getMessage());
1280 } catch (IOException e
) {
1281 throw new Error
.Failure(e
.getMessage());
1285 private void updateGroup(final UpdateGroup updateGroup
) {
1287 m
.updateGroup(groupId
, updateGroup
);
1288 } catch (IOException e
) {
1289 throw new Error
.Failure(e
.getMessage());
1290 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1291 throw new Error
.GroupNotFound(e
.getMessage());
1292 } catch (AttachmentInvalidException e
) {
1293 throw new Error
.AttachmentInvalid(e
.getMessage());
1294 } catch (UnregisteredRecipientException e
) {
1295 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");