1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.BaseConfig
;
5 import org
.asamk
.signal
.manager
.AttachmentInvalidException
;
6 import org
.asamk
.signal
.manager
.Manager
;
7 import org
.asamk
.signal
.manager
.NotMasterDeviceException
;
8 import org
.asamk
.signal
.manager
.StickerPackInvalidException
;
9 import org
.asamk
.signal
.manager
.api
.Identity
;
10 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
11 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
12 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
13 import org
.asamk
.signal
.manager
.api
.Message
;
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
.TypingAction
;
18 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
19 import org
.asamk
.signal
.manager
.groups
.GroupId
;
20 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
21 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
22 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
23 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
24 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
25 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
26 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
27 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
29 import org
.asamk
.signal
.util
.SendMessageResultUtils
;
30 import org
.freedesktop
.dbus
.DBusPath
;
31 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
32 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
33 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
34 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
35 import org
.freedesktop
.dbus
.types
.Variant
;
36 import org
.slf4j
.Logger
;
37 import org
.slf4j
.LoggerFactory
;
40 import java
.io
.IOException
;
42 import java
.net
.URISyntaxException
;
43 import java
.util
.ArrayList
;
44 import java
.util
.Arrays
;
45 import java
.util
.Base64
;
46 import java
.util
.Collection
;
47 import java
.util
.HashSet
;
48 import java
.util
.List
;
50 import java
.util
.Objects
;
51 import java
.util
.Optional
;
53 import java
.util
.UUID
;
54 import java
.util
.stream
.Collectors
;
55 import java
.util
.stream
.Stream
;
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
;
81 public void initObjects() {
82 if (!noReceiveOnStart
) {
88 updateConfiguration();
92 if (dbusMessageHandler
!= null) {
93 m
.removeReceiveHandler(dbusMessageHandler
);
94 dbusMessageHandler
= null;
98 unExportConfiguration();
102 public String
getObjectPath() {
107 public String
getSelfNumber() {
108 return m
.getSelfNumber();
112 public void subscribeReceive() {
113 if (dbusMessageHandler
== null) {
114 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
115 m
.addReceiveHandler(dbusMessageHandler
);
121 public void unsubscribeReceive() {
122 subscriberCount
= Math
.max(0, subscriberCount
- 1);
123 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
124 m
.removeReceiveHandler(dbusMessageHandler
);
125 dbusMessageHandler
= null;
130 public void submitRateLimitChallenge(String challenge
, String captcha
) {
132 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
133 } catch (IOException e
) {
134 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
140 public void unregister() throws Error
.Failure
{
143 } catch (IOException e
) {
144 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
149 public void deleteAccount() throws Error
.Failure
{
152 } catch (IOException e
) {
153 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
158 public void addDevice(String uri
) {
160 m
.addDeviceLink(new URI(uri
));
161 } catch (IOException
| InvalidDeviceLinkException e
) {
162 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
163 } catch (URISyntaxException e
) {
164 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
165 + " Device link uri has invalid format: "
171 public DBusPath
getDevice(long deviceId
) {
173 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
174 if (deviceOptional
.isEmpty()) {
175 throw new Error
.DeviceNotFound("Device not found");
177 return deviceOptional
.get().getObjectPath();
181 public List
<StructDevice
> listDevices() {
187 public DBusPath
getThisDevice() {
193 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
194 return sendMessage(message
, attachments
, List
.of(recipient
));
198 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
200 final var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
201 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
202 .map(RecipientIdentifier
.class::cast
)
203 .collect(Collectors
.toSet()));
205 checkSendMessageResults(results
.timestamp(), results
.results());
206 return results
.timestamp();
207 } catch (AttachmentInvalidException e
) {
208 throw new Error
.AttachmentInvalid(e
.getMessage());
209 } catch (IOException e
) {
210 throw new Error
.Failure(e
);
211 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
212 throw new Error
.GroupNotFound(e
.getMessage());
217 public long sendRemoteDeleteMessage(
218 final long targetSentTimestamp
, final String recipient
220 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
224 public long sendRemoteDeleteMessage(
225 final long targetSentTimestamp
, final List
<String
> recipients
228 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
229 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
230 .map(RecipientIdentifier
.class::cast
)
231 .collect(Collectors
.toSet()));
232 checkSendMessageResults(results
.timestamp(), results
.results());
233 return results
.timestamp();
234 } catch (IOException e
) {
235 throw new Error
.Failure(e
.getMessage());
236 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
237 throw new Error
.GroupNotFound(e
.getMessage());
242 public long sendMessageReaction(
244 final boolean remove
,
245 final String targetAuthor
,
246 final long targetSentTimestamp
,
247 final String recipient
249 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
253 public long sendMessageReaction(
255 final boolean remove
,
256 final String targetAuthor
,
257 final long targetSentTimestamp
,
258 final List
<String
> recipients
261 final var results
= m
.sendMessageReaction(emoji
,
263 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
265 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
266 .map(RecipientIdentifier
.class::cast
)
267 .collect(Collectors
.toSet()));
268 checkSendMessageResults(results
.timestamp(), results
.results());
269 return results
.timestamp();
270 } catch (IOException e
) {
271 throw new Error
.Failure(e
.getMessage());
272 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
273 throw new Error
.GroupNotFound(e
.getMessage());
278 public void sendTyping(
279 final String recipient
, final boolean stop
280 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
282 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
283 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
284 .map(RecipientIdentifier
.class::cast
)
285 .collect(Collectors
.toSet()));
286 checkSendMessageResults(results
.timestamp(), results
.results());
287 } catch (IOException e
) {
288 throw new Error
.Failure(e
.getMessage());
289 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
290 throw new Error
.GroupNotFound(e
.getMessage());
295 public void sendReadReceipt(
296 final String recipient
, final List
<Long
> messageIds
297 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
299 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
301 checkSendMessageResults(results
.timestamp(), results
.results());
302 } catch (IOException e
) {
303 throw new Error
.Failure(e
.getMessage());
308 public void sendViewedReceipt(
309 final String recipient
, final List
<Long
> messageIds
310 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
312 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
314 checkSendMessageResults(results
.timestamp(), results
.results());
315 } catch (IOException e
) {
316 throw new Error
.Failure(e
.getMessage());
321 public void sendContacts() {
324 } catch (IOException e
) {
325 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
330 public void sendSyncRequest() {
332 m
.requestAllSyncData();
333 } catch (IOException e
) {
334 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
339 public long sendNoteToSelfMessage(
340 final String message
, final List
<String
> attachments
341 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
343 final var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
344 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
345 checkSendMessageResults(results
.timestamp(), results
.results());
346 return results
.timestamp();
347 } catch (AttachmentInvalidException e
) {
348 throw new Error
.AttachmentInvalid(e
.getMessage());
349 } catch (IOException e
) {
350 throw new Error
.Failure(e
.getMessage());
351 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
352 throw new Error
.GroupNotFound(e
.getMessage());
357 public void sendEndSessionMessage(final List
<String
> recipients
) {
359 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
360 checkSendMessageResults(results
.timestamp(), results
.results());
361 } catch (IOException e
) {
362 throw new Error
.Failure(e
.getMessage());
367 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
369 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
370 } catch (IOException e
) {
371 throw new Error
.Failure("Recipient not found");
376 public void deleteContact(final String recipient
) throws Error
.Failure
{
378 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
379 } catch (IOException e
) {
380 throw new Error
.Failure("Contact not found");
385 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
387 var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
388 Set
.of(getGroupRecipientIdentifier(groupId
)));
389 checkSendMessageResults(results
.timestamp(), results
.results());
390 return results
.timestamp();
391 } catch (IOException e
) {
392 throw new Error
.Failure(e
.getMessage());
393 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
394 throw new Error
.GroupNotFound(e
.getMessage());
395 } catch (AttachmentInvalidException e
) {
396 throw new Error
.AttachmentInvalid(e
.getMessage());
401 public void sendGroupTyping(
402 final byte[] groupId
, final boolean stop
403 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
405 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
406 Set
.of(getGroupRecipientIdentifier(groupId
)));
407 checkSendMessageResults(results
.timestamp(), results
.results());
408 } catch (IOException e
) {
409 throw new Error
.Failure(e
.getMessage());
410 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
411 throw new Error
.GroupNotFound(e
.getMessage());
416 public long sendGroupRemoteDeleteMessage(
417 final long targetSentTimestamp
, final byte[] groupId
420 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
421 Set
.of(getGroupRecipientIdentifier(groupId
)));
422 checkSendMessageResults(results
.timestamp(), results
.results());
423 return results
.timestamp();
424 } catch (IOException e
) {
425 throw new Error
.Failure(e
.getMessage());
426 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
427 throw new Error
.GroupNotFound(e
.getMessage());
432 public long sendGroupMessageReaction(
434 final boolean remove
,
435 final String targetAuthor
,
436 final long targetSentTimestamp
,
440 final var results
= m
.sendMessageReaction(emoji
,
442 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
444 Set
.of(getGroupRecipientIdentifier(groupId
)));
445 checkSendMessageResults(results
.timestamp(), results
.results());
446 return results
.timestamp();
447 } catch (IOException e
) {
448 throw new Error
.Failure(e
.getMessage());
449 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
450 throw new Error
.GroupNotFound(e
.getMessage());
454 // Since contact names might be empty if not defined, also potentially return
457 public String
getContactName(final String number
) {
458 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
459 return name
== null ?
"" : name
;
463 public void setContactName(final String number
, final String name
) {
465 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
466 } catch (NotMasterDeviceException e
) {
467 throw new Error
.Failure("This command doesn't work on linked devices.");
468 } catch (IOException e
) {
469 throw new Error
.Failure("Contact is not registered.");
474 public void setExpirationTimer(final String number
, final int expiration
) {
476 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
477 } catch (IOException e
) {
478 throw new Error
.Failure(e
.getMessage());
483 public void setContactBlocked(final String number
, final boolean blocked
) {
485 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
486 } catch (NotMasterDeviceException e
) {
487 throw new Error
.Failure("This command doesn't work on linked devices.");
488 } catch (IOException e
) {
489 throw new Error
.Failure(e
.getMessage());
494 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
496 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
497 } catch (NotMasterDeviceException e
) {
498 throw new Error
.Failure("This command doesn't work on linked devices.");
499 } catch (GroupNotFoundException e
) {
500 throw new Error
.GroupNotFound(e
.getMessage());
501 } catch (IOException e
) {
502 throw new Error
.Failure(e
.getMessage());
507 public List
<byte[]> getGroupIds() {
508 var groups
= m
.getGroups();
509 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
513 public DBusPath
getGroup(final byte[] groupId
) {
515 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
516 if (groupOptional
.isEmpty()) {
517 throw new Error
.GroupNotFound("Group not found");
519 return groupOptional
.get().getObjectPath();
523 public List
<StructGroup
> listGroups() {
529 public String
getGroupName(final byte[] groupId
) {
530 var group
= m
.getGroup(getGroupId(groupId
));
531 if (group
== null || group
.title() == null) {
534 return group
.title();
539 public List
<String
> getGroupMembers(final byte[] groupId
) {
540 var group
= m
.getGroup(getGroupId(groupId
));
544 final var members
= group
.members();
545 return getRecipientStrings(members
);
550 public byte[] createGroup(
551 final String name
, final List
<String
> members
, final String avatar
552 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
553 return updateGroup(new byte[0], name
, members
, avatar
);
557 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
559 groupId
= nullIfEmpty(groupId
);
560 name
= nullIfEmpty(name
);
561 avatar
= nullIfEmpty(avatar
);
562 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
563 if (groupId
== null) {
564 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
565 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
566 return results
.first().serialize();
568 final var results
= m
.updateGroup(getGroupId(groupId
),
569 UpdateGroup
.newBuilder()
571 .withMembers(memberIdentifiers
)
572 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
574 if (results
!= null) {
575 checkSendMessageResults(results
.timestamp(), results
.results());
579 } catch (IOException e
) {
580 throw new Error
.Failure(e
.getMessage());
581 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
582 throw new Error
.GroupNotFound(e
.getMessage());
583 } catch (AttachmentInvalidException e
) {
584 throw new Error
.AttachmentInvalid(e
.getMessage());
589 public boolean isRegistered() {
594 public boolean isRegistered(String number
) {
595 var result
= isRegistered(List
.of(number
));
596 return result
.get(0);
600 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
601 if (numbers
.isEmpty()) {
605 Map
<String
, Pair
<String
, UUID
>> registered
;
607 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
608 } catch (IOException e
) {
609 throw new Error
.Failure(e
.getMessage());
612 return numbers
.stream().map(number
-> {
613 var uuid
= registered
.get(number
).second();
619 public void updateProfile(
625 final boolean removeAvatar
628 givenName
= nullIfEmpty(givenName
);
629 familyName
= nullIfEmpty(familyName
);
630 about
= nullIfEmpty(about
);
631 aboutEmoji
= nullIfEmpty(aboutEmoji
);
632 avatarPath
= nullIfEmpty(avatarPath
);
633 Optional
<File
> avatarFile
= removeAvatar
635 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
636 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
637 } catch (IOException e
) {
638 throw new Error
.Failure(e
.getMessage());
643 public void updateProfile(
646 final String aboutEmoji
,
648 final boolean removeAvatar
650 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
654 public void removePin() {
656 m
.setRegistrationLockPin(Optional
.empty());
657 } catch (IOException e
) {
658 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
663 public void setPin(String registrationLockPin
) {
665 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
666 } catch (IOException e
) {
667 throw new Error
.Failure("Set pin error: " + e
.getMessage());
671 // Provide option to query a version string in order to react on potential
672 // future interface changes
674 public String
version() {
675 return BaseConfig
.PROJECT_VERSION
;
678 // Create a unique list of Numbers from Identities and Contacts to really get
679 // all numbers the system knows
681 public List
<String
> listNumbers() {
682 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
683 m
.getContacts().stream().map(Pair
::first
))
684 .map(a
-> a
.number().orElse(null))
685 .filter(Objects
::nonNull
)
691 public List
<String
> getContactNumber(final String name
) {
692 // Contact names have precedence.
693 var numbers
= new ArrayList
<String
>();
694 var contacts
= m
.getContacts();
695 for (var c
: contacts
) {
696 if (name
.equals(c
.second().getName())) {
697 numbers
.add(c
.first().getLegacyIdentifier());
700 // Try profiles if no contact name was found
701 for (var identity
: m
.getIdentities()) {
702 final var address
= identity
.recipient();
703 var number
= address
.number().orElse(null);
704 if (number
!= null) {
705 Profile profile
= null;
707 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
708 } catch (IOException ignored
) {
710 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
719 public void quitGroup(final byte[] groupId
) {
720 var group
= getGroupId(groupId
);
722 m
.quitGroup(group
, Set
.of());
723 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
724 throw new Error
.GroupNotFound(e
.getMessage());
725 } catch (IOException
| LastGroupAdminException e
) {
726 throw new Error
.Failure(e
.getMessage());
731 public byte[] joinGroup(final String groupLink
) {
733 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
734 if (linkUrl
== null) {
735 throw new Error
.Failure("Group link is invalid:");
737 final var result
= m
.joinGroup(linkUrl
);
738 return result
.first().serialize();
739 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
740 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
741 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
742 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
743 } catch (IOException e
) {
744 throw new Error
.Failure(e
.getMessage());
749 public boolean isContactBlocked(final String number
) {
750 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
754 public boolean isGroupBlocked(final byte[] groupId
) {
755 var group
= m
.getGroup(getGroupId(groupId
));
759 return group
.isBlocked();
764 public boolean isMember(final byte[] groupId
) {
765 var group
= m
.getGroup(getGroupId(groupId
));
769 return group
.isMember();
774 public String
uploadStickerPack(String stickerPackPath
) {
775 File path
= new File(stickerPackPath
);
777 return m
.uploadStickerPack(path
).toString();
778 } catch (IOException e
) {
779 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
780 } catch (StickerPackInvalidException e
) {
781 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
785 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
786 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
792 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
794 if (result
.isIdentityFailure()) {
795 throw new Error
.UntrustedIdentity(message
);
797 throw new Error
.Failure(message
);
801 private static void checkSendMessageResults(
802 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
803 ) throws DBusExecutionException
{
804 final var sendMessageResults
= results
.values().stream().findFirst();
805 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
806 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
810 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
811 if (errors
.size() == 0) {
815 var message
= new StringBuilder();
816 message
.append(timestamp
).append('\n');
817 message
.append("Failed to send (some) messages:\n");
818 for (var error
: errors
) {
819 message
.append(error
).append('\n');
822 throw new Error
.Failure(message
.toString());
825 private static void checkSendMessageResults(
826 long timestamp
, Collection
<SendMessageResult
> results
827 ) throws DBusExecutionException
{
828 if (results
.size() == 1) {
829 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
833 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
834 if (errors
.size() == 0) {
838 var message
= new StringBuilder();
839 message
.append(timestamp
).append('\n');
840 message
.append("Failed to send (some) messages:\n");
841 for (var error
: errors
) {
842 message
.append(error
).append('\n');
845 throw new Error
.Failure(message
.toString());
848 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
849 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
852 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
853 final Collection
<String
> recipientStrings
, final String localNumber
854 ) throws DBusExecutionException
{
855 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
856 for (var recipientString
: recipientStrings
) {
857 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
862 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
863 final String recipientString
, final String localNumber
864 ) throws DBusExecutionException
{
866 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
867 } catch (InvalidNumberException e
) {
868 throw new Error
.InvalidNumber(e
.getMessage());
872 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
873 return new RecipientIdentifier
.Group(getGroupId(groupId
));
876 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
878 return GroupId
.unknownVersion(groupId
);
879 } catch (Throwable e
) {
880 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
884 private byte[] nullIfEmpty(final byte[] array
) {
885 return array
.length
== 0 ?
null : array
;
888 private String
nullIfEmpty(final String name
) {
889 return name
.isEmpty() ?
null : name
;
892 private String
emptyIfNull(final String string
) {
893 return string
== null ?
"" : string
;
896 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
897 return basePath
+ "/Devices/" + deviceId
;
900 private void updateDevices() {
901 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
903 linkedDevices
= m
.getLinkedDevices();
904 } catch (IOException e
) {
905 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
910 linkedDevices
.forEach(d
-> {
911 final var object
= new DbusSignalDeviceImpl(d
);
912 final var deviceObjectPath
= object
.getObjectPath();
913 exportObject(object
);
914 if (d
.isThisDevice()) {
915 thisDevice
= new DBusPath(deviceObjectPath
);
917 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
921 private void unExportDevices() {
922 this.devices
.stream()
923 .map(StructDevice
::getObjectPath
)
924 .map(DBusPath
::getPath
)
925 .forEach(connection
::unExportObject
);
926 this.devices
.clear();
929 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
930 return basePath
+ "/Groups/" + Base64
.getEncoder()
931 .encodeToString(groupId
)
937 private void updateGroups() {
938 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
939 groups
= m
.getGroups();
943 groups
.forEach(g
-> {
944 final var object
= new DbusSignalGroupImpl(g
.groupId());
945 exportObject(object
);
946 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
947 g
.groupId().serialize(),
948 emptyIfNull(g
.title())));
952 private void unExportGroups() {
953 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
957 private static String
getConfigurationObjectPath(String basePath
) {
958 return basePath
+ "/Configuration";
961 private void updateConfiguration() {
962 unExportConfiguration();
963 final var object
= new DbusSignalConfigurationImpl();
964 exportObject(object
);
967 private void unExportConfiguration() {
968 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
969 connection
.unExportObject(objectPath
);
972 private void exportObject(final DBusInterface object
) {
974 connection
.exportObject(object
);
975 logger
.debug("Exported dbus object: " + object
.getObjectPath());
976 } catch (DBusException e
) {
981 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
983 private final org
.asamk
.signal
.manager
.api
.Device device
;
985 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
986 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
987 List
.of(new DbusProperty
<>("Id", device
::id
),
988 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
989 new DbusProperty
<>("Created", device
::created
),
990 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
991 this.device
= device
;
995 public String
getObjectPath() {
996 return getDeviceObjectPath(objectPath
, device
.id());
1000 public void removeDevice() throws Error
.Failure
{
1002 m
.removeLinkedDevices(device
.id());
1004 } catch (IOException e
) {
1005 throw new Error
.Failure(e
.getMessage());
1009 private void setDeviceName(String name
) {
1010 if (!device
.isThisDevice()) {
1011 throw new Error
.Failure("Only the name of this device can be changed");
1014 m
.updateAccountAttributes(name
);
1015 // update device list
1017 } catch (IOException e
) {
1018 throw new Error
.Failure(e
.getMessage());
1023 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1025 public DbusSignalConfigurationImpl(
1027 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1028 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1029 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1030 this::getUnidentifiedDeliveryIndicators
,
1031 this::setUnidentifiedDeliveryIndicators
),
1032 new DbusProperty
<>("TypingIndicators",
1033 this::getTypingIndicators
,
1034 this::setTypingIndicators
),
1035 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1040 public String
getObjectPath() {
1041 return getConfigurationObjectPath(objectPath
);
1044 public void setReadReceipts(Boolean readReceipts
) {
1045 setConfiguration(readReceipts
, null, null, null);
1048 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1049 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1052 public void setTypingIndicators(Boolean typingIndicators
) {
1053 setConfiguration(null, null, typingIndicators
, null);
1056 public void setLinkPreviews(Boolean linkPreviews
) {
1057 setConfiguration(null, null, null, linkPreviews
);
1060 private void setConfiguration(
1061 Boolean readReceipts
,
1062 Boolean unidentifiedDeliveryIndicators
,
1063 Boolean typingIndicators
,
1064 Boolean linkPreviews
1067 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1068 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1069 Optional
.ofNullable(typingIndicators
),
1070 Optional
.ofNullable(linkPreviews
)));
1071 } catch (IOException e
) {
1072 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1073 } catch (NotMasterDeviceException e
) {
1074 throw new Error
.Failure("This command doesn't work on linked devices.");
1078 private boolean getReadReceipts() {
1079 return m
.getConfiguration().readReceipts().orElse(false);
1082 private boolean getUnidentifiedDeliveryIndicators() {
1083 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1086 private boolean getTypingIndicators() {
1087 return m
.getConfiguration().typingIndicators().orElse(false);
1090 private boolean getLinkPreviews() {
1091 return m
.getConfiguration().linkPreviews().orElse(false);
1095 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1097 private final GroupId groupId
;
1099 public DbusSignalGroupImpl(final GroupId groupId
) {
1100 this.groupId
= groupId
;
1101 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1102 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1103 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1104 new DbusProperty
<>("Description",
1105 () -> emptyIfNull(getGroup().description()),
1106 this::setGroupDescription
),
1107 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1108 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1109 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1110 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1111 new DbusProperty
<>("MessageExpirationTimer",
1112 () -> getGroup().messageExpirationTimer(),
1113 this::setMessageExpirationTime
),
1114 new DbusProperty
<>("Members",
1115 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1116 new DbusProperty
<>("PendingMembers",
1117 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1118 new DbusProperty
<>("RequestingMembers",
1119 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1120 new DbusProperty
<>("Admins",
1121 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1122 new DbusProperty
<>("PermissionAddMember",
1123 () -> getGroup().permissionAddMember().name(),
1124 this::setGroupPermissionAddMember
),
1125 new DbusProperty
<>("PermissionEditDetails",
1126 () -> getGroup().permissionEditDetails().name(),
1127 this::setGroupPermissionEditDetails
),
1128 new DbusProperty
<>("PermissionSendMessage",
1129 () -> getGroup().permissionSendMessage().name(),
1130 this::setGroupPermissionSendMessage
),
1131 new DbusProperty
<>("GroupInviteLink", () -> {
1132 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1133 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1138 public String
getObjectPath() {
1139 return getGroupObjectPath(objectPath
, groupId
.serialize());
1143 public void quitGroup() throws Error
.Failure
{
1145 m
.quitGroup(groupId
, Set
.of());
1146 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1147 throw new Error
.GroupNotFound(e
.getMessage());
1148 } catch (IOException e
) {
1149 throw new Error
.Failure(e
.getMessage());
1150 } catch (LastGroupAdminException e
) {
1151 throw new Error
.LastGroupAdmin(e
.getMessage());
1156 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1157 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1158 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1162 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1163 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1164 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1168 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1169 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1170 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1174 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1175 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1176 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1180 public void resetLink() throws Error
.Failure
{
1181 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1185 public void disableLink() throws Error
.Failure
{
1186 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1190 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1191 updateGroup(UpdateGroup
.newBuilder()
1192 .withGroupLinkState(requiresApproval
1193 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1194 : GroupLinkState
.ENABLED
)
1198 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1199 return m
.getGroup(groupId
);
1202 private void setGroupName(final String name
) {
1203 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1206 private void setGroupDescription(final String description
) {
1207 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1210 private void setGroupAvatar(final String avatar
) {
1211 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1214 private void setMessageExpirationTime(final int expirationTime
) {
1215 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1218 private void setGroupPermissionAddMember(final String permission
) {
1219 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1222 private void setGroupPermissionEditDetails(final String permission
) {
1223 updateGroup(UpdateGroup
.newBuilder()
1224 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1228 private void setGroupPermissionSendMessage(final String permission
) {
1229 updateGroup(UpdateGroup
.newBuilder()
1230 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1234 private void setIsBlocked(final boolean isBlocked
) {
1236 m
.setGroupBlocked(groupId
, isBlocked
);
1237 } catch (NotMasterDeviceException e
) {
1238 throw new Error
.Failure("This command doesn't work on linked devices.");
1239 } catch (GroupNotFoundException e
) {
1240 throw new Error
.GroupNotFound(e
.getMessage());
1241 } catch (IOException e
) {
1242 throw new Error
.Failure(e
.getMessage());
1246 private void updateGroup(final UpdateGroup updateGroup
) {
1248 m
.updateGroup(groupId
, updateGroup
);
1249 } catch (IOException e
) {
1250 throw new Error
.Failure(e
.getMessage());
1251 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1252 throw new Error
.GroupNotFound(e
.getMessage());
1253 } catch (AttachmentInvalidException e
) {
1254 throw new Error
.AttachmentInvalid(e
.getMessage());