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
));
566 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
567 return results
.first().serialize();
569 final var results
= m
.updateGroup(getGroupId(groupId
),
570 UpdateGroup
.newBuilder()
572 .withMembers(memberIdentifiers
)
573 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
575 if (results
!= null) {
576 checkSendMessageResults(results
.timestamp(), results
.results());
580 } catch (IOException e
) {
581 throw new Error
.Failure(e
.getMessage());
582 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
583 throw new Error
.GroupNotFound(e
.getMessage());
584 } catch (AttachmentInvalidException e
) {
585 throw new Error
.AttachmentInvalid(e
.getMessage());
590 public boolean isRegistered() {
595 public boolean isRegistered(String number
) {
596 var result
= isRegistered(List
.of(number
));
597 return result
.get(0);
601 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
602 if (numbers
.isEmpty()) {
606 Map
<String
, Pair
<String
, UUID
>> registered
;
608 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
609 } catch (IOException e
) {
610 throw new Error
.Failure(e
.getMessage());
613 return numbers
.stream().map(number
-> {
614 var uuid
= registered
.get(number
).second();
620 public void updateProfile(
626 final boolean removeAvatar
629 givenName
= nullIfEmpty(givenName
);
630 familyName
= nullIfEmpty(familyName
);
631 about
= nullIfEmpty(about
);
632 aboutEmoji
= nullIfEmpty(aboutEmoji
);
633 avatarPath
= nullIfEmpty(avatarPath
);
634 Optional
<File
> avatarFile
= removeAvatar
636 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
637 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
638 } catch (IOException e
) {
639 throw new Error
.Failure(e
.getMessage());
644 public void updateProfile(
647 final String aboutEmoji
,
649 final boolean removeAvatar
651 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
655 public void removePin() {
657 m
.setRegistrationLockPin(Optional
.empty());
658 } catch (IOException e
) {
659 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
664 public void setPin(String registrationLockPin
) {
666 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
667 } catch (IOException e
) {
668 throw new Error
.Failure("Set pin error: " + e
.getMessage());
672 // Provide option to query a version string in order to react on potential
673 // future interface changes
675 public String
version() {
676 return BaseConfig
.PROJECT_VERSION
;
679 // Create a unique list of Numbers from Identities and Contacts to really get
680 // all numbers the system knows
682 public List
<String
> listNumbers() {
683 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
684 m
.getContacts().stream().map(Pair
::first
))
685 .map(a
-> a
.number().orElse(null))
686 .filter(Objects
::nonNull
)
692 public List
<String
> getContactNumber(final String name
) {
693 // Contact names have precedence.
694 var numbers
= new ArrayList
<String
>();
695 var contacts
= m
.getContacts();
696 for (var c
: contacts
) {
697 if (name
.equals(c
.second().getName())) {
698 numbers
.add(c
.first().getLegacyIdentifier());
701 // Try profiles if no contact name was found
702 for (var identity
: m
.getIdentities()) {
703 final var address
= identity
.recipient();
704 var number
= address
.number().orElse(null);
705 if (number
!= null) {
706 Profile profile
= null;
708 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
709 } catch (IOException ignored
) {
711 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
720 public void quitGroup(final byte[] groupId
) {
721 var group
= getGroupId(groupId
);
723 m
.quitGroup(group
, Set
.of());
724 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
725 throw new Error
.GroupNotFound(e
.getMessage());
726 } catch (IOException
| LastGroupAdminException e
) {
727 throw new Error
.Failure(e
.getMessage());
732 public byte[] joinGroup(final String groupLink
) {
734 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
735 if (linkUrl
== null) {
736 throw new Error
.Failure("Group link is invalid:");
738 final var result
= m
.joinGroup(linkUrl
);
739 return result
.first().serialize();
740 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
741 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
742 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
743 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
744 } catch (IOException e
) {
745 throw new Error
.Failure(e
.getMessage());
750 public boolean isContactBlocked(final String number
) {
751 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
755 public boolean isGroupBlocked(final byte[] groupId
) {
756 var group
= m
.getGroup(getGroupId(groupId
));
760 return group
.isBlocked();
765 public boolean isMember(final byte[] groupId
) {
766 var group
= m
.getGroup(getGroupId(groupId
));
770 return group
.isMember();
775 public String
uploadStickerPack(String stickerPackPath
) {
776 File path
= new File(stickerPackPath
);
778 return m
.uploadStickerPack(path
).toString();
779 } catch (IOException e
) {
780 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
781 } catch (StickerPackInvalidException e
) {
782 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
786 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
787 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
793 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
795 if (result
.isIdentityFailure()) {
796 throw new Error
.UntrustedIdentity(message
);
798 throw new Error
.Failure(message
);
802 private static void checkSendMessageResults(
803 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
804 ) throws DBusExecutionException
{
805 final var sendMessageResults
= results
.values().stream().findFirst();
806 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
807 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
811 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
812 if (errors
.size() == 0) {
816 var message
= new StringBuilder();
817 message
.append(timestamp
).append('\n');
818 message
.append("Failed to send (some) messages:\n");
819 for (var error
: errors
) {
820 message
.append(error
).append('\n');
823 throw new Error
.Failure(message
.toString());
826 private static void checkSendMessageResults(
827 long timestamp
, Collection
<SendMessageResult
> results
828 ) throws DBusExecutionException
{
829 if (results
.size() == 1) {
830 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
834 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
835 if (errors
.size() == 0) {
839 var message
= new StringBuilder();
840 message
.append(timestamp
).append('\n');
841 message
.append("Failed to send (some) messages:\n");
842 for (var error
: errors
) {
843 message
.append(error
).append('\n');
846 throw new Error
.Failure(message
.toString());
849 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
850 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
853 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
854 final Collection
<String
> recipientStrings
, final String localNumber
855 ) throws DBusExecutionException
{
856 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
857 for (var recipientString
: recipientStrings
) {
858 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
863 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
864 final String recipientString
, final String localNumber
865 ) throws DBusExecutionException
{
867 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
868 } catch (InvalidNumberException e
) {
869 throw new Error
.InvalidNumber(e
.getMessage());
873 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
874 return new RecipientIdentifier
.Group(getGroupId(groupId
));
877 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
879 return GroupId
.unknownVersion(groupId
);
880 } catch (Throwable e
) {
881 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
885 private byte[] nullIfEmpty(final byte[] array
) {
886 return array
.length
== 0 ?
null : array
;
889 private String
nullIfEmpty(final String name
) {
890 return name
.isEmpty() ?
null : name
;
893 private String
emptyIfNull(final String string
) {
894 return string
== null ?
"" : string
;
897 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
898 return basePath
+ "/Devices/" + deviceId
;
901 private void updateDevices() {
902 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
904 linkedDevices
= m
.getLinkedDevices();
905 } catch (IOException e
) {
906 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
911 linkedDevices
.forEach(d
-> {
912 final var object
= new DbusSignalDeviceImpl(d
);
913 final var deviceObjectPath
= object
.getObjectPath();
914 exportObject(object
);
915 if (d
.isThisDevice()) {
916 thisDevice
= new DBusPath(deviceObjectPath
);
918 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
922 private void unExportDevices() {
923 this.devices
.stream()
924 .map(StructDevice
::getObjectPath
)
925 .map(DBusPath
::getPath
)
926 .forEach(connection
::unExportObject
);
927 this.devices
.clear();
930 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
931 return basePath
+ "/Groups/" + Base64
.getEncoder()
932 .encodeToString(groupId
)
938 private void updateGroups() {
939 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
940 groups
= m
.getGroups();
944 groups
.forEach(g
-> {
945 final var object
= new DbusSignalGroupImpl(g
.groupId());
946 exportObject(object
);
947 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
948 g
.groupId().serialize(),
949 emptyIfNull(g
.title())));
953 private void unExportGroups() {
954 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
958 private static String
getConfigurationObjectPath(String basePath
) {
959 return basePath
+ "/Configuration";
962 private void updateConfiguration() {
963 unExportConfiguration();
964 final var object
= new DbusSignalConfigurationImpl();
965 exportObject(object
);
968 private void unExportConfiguration() {
969 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
970 connection
.unExportObject(objectPath
);
973 private void exportObject(final DBusInterface object
) {
975 connection
.exportObject(object
);
976 logger
.debug("Exported dbus object: " + object
.getObjectPath());
977 } catch (DBusException e
) {
982 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
984 private final org
.asamk
.signal
.manager
.api
.Device device
;
986 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
987 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
988 List
.of(new DbusProperty
<>("Id", device
::id
),
989 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
990 new DbusProperty
<>("Created", device
::created
),
991 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
992 this.device
= device
;
996 public String
getObjectPath() {
997 return getDeviceObjectPath(objectPath
, device
.id());
1001 public void removeDevice() throws Error
.Failure
{
1003 m
.removeLinkedDevices(device
.id());
1005 } catch (IOException e
) {
1006 throw new Error
.Failure(e
.getMessage());
1010 private void setDeviceName(String name
) {
1011 if (!device
.isThisDevice()) {
1012 throw new Error
.Failure("Only the name of this device can be changed");
1015 m
.updateAccountAttributes(name
);
1016 // update device list
1018 } catch (IOException e
) {
1019 throw new Error
.Failure(e
.getMessage());
1024 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1026 public DbusSignalConfigurationImpl(
1028 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1029 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1030 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1031 this::getUnidentifiedDeliveryIndicators
,
1032 this::setUnidentifiedDeliveryIndicators
),
1033 new DbusProperty
<>("TypingIndicators",
1034 this::getTypingIndicators
,
1035 this::setTypingIndicators
),
1036 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1041 public String
getObjectPath() {
1042 return getConfigurationObjectPath(objectPath
);
1045 public void setReadReceipts(Boolean readReceipts
) {
1046 setConfiguration(readReceipts
, null, null, null);
1049 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1050 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1053 public void setTypingIndicators(Boolean typingIndicators
) {
1054 setConfiguration(null, null, typingIndicators
, null);
1057 public void setLinkPreviews(Boolean linkPreviews
) {
1058 setConfiguration(null, null, null, linkPreviews
);
1061 private void setConfiguration(
1062 Boolean readReceipts
,
1063 Boolean unidentifiedDeliveryIndicators
,
1064 Boolean typingIndicators
,
1065 Boolean linkPreviews
1068 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1069 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1070 Optional
.ofNullable(typingIndicators
),
1071 Optional
.ofNullable(linkPreviews
)));
1072 } catch (IOException e
) {
1073 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1074 } catch (NotMasterDeviceException e
) {
1075 throw new Error
.Failure("This command doesn't work on linked devices.");
1079 private boolean getReadReceipts() {
1080 return m
.getConfiguration().readReceipts().orElse(false);
1083 private boolean getUnidentifiedDeliveryIndicators() {
1084 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1087 private boolean getTypingIndicators() {
1088 return m
.getConfiguration().typingIndicators().orElse(false);
1091 private boolean getLinkPreviews() {
1092 return m
.getConfiguration().linkPreviews().orElse(false);
1096 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1098 private final GroupId groupId
;
1100 public DbusSignalGroupImpl(final GroupId groupId
) {
1101 this.groupId
= groupId
;
1102 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1103 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1104 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1105 new DbusProperty
<>("Description",
1106 () -> emptyIfNull(getGroup().description()),
1107 this::setGroupDescription
),
1108 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1109 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1110 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1111 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1112 new DbusProperty
<>("MessageExpirationTimer",
1113 () -> getGroup().messageExpirationTimer(),
1114 this::setMessageExpirationTime
),
1115 new DbusProperty
<>("Members",
1116 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1117 new DbusProperty
<>("PendingMembers",
1118 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1119 new DbusProperty
<>("RequestingMembers",
1120 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1121 new DbusProperty
<>("Admins",
1122 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1123 new DbusProperty
<>("PermissionAddMember",
1124 () -> getGroup().permissionAddMember().name(),
1125 this::setGroupPermissionAddMember
),
1126 new DbusProperty
<>("PermissionEditDetails",
1127 () -> getGroup().permissionEditDetails().name(),
1128 this::setGroupPermissionEditDetails
),
1129 new DbusProperty
<>("PermissionSendMessage",
1130 () -> getGroup().permissionSendMessage().name(),
1131 this::setGroupPermissionSendMessage
),
1132 new DbusProperty
<>("GroupInviteLink", () -> {
1133 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1134 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1139 public String
getObjectPath() {
1140 return getGroupObjectPath(objectPath
, groupId
.serialize());
1144 public void quitGroup() throws Error
.Failure
{
1146 m
.quitGroup(groupId
, Set
.of());
1147 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1148 throw new Error
.GroupNotFound(e
.getMessage());
1149 } catch (IOException e
) {
1150 throw new Error
.Failure(e
.getMessage());
1151 } catch (LastGroupAdminException e
) {
1152 throw new Error
.LastGroupAdmin(e
.getMessage());
1157 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1159 m
.deleteGroup(groupId
);
1160 } catch (IOException e
) {
1161 throw new Error
.Failure(e
.getMessage());
1167 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1168 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1169 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1173 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1174 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1175 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1179 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1180 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1181 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1185 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1186 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1187 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1191 public void resetLink() throws Error
.Failure
{
1192 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1196 public void disableLink() throws Error
.Failure
{
1197 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1201 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1202 updateGroup(UpdateGroup
.newBuilder()
1203 .withGroupLinkState(requiresApproval
1204 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1205 : GroupLinkState
.ENABLED
)
1209 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1210 return m
.getGroup(groupId
);
1213 private void setGroupName(final String name
) {
1214 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1217 private void setGroupDescription(final String description
) {
1218 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1221 private void setGroupAvatar(final String avatar
) {
1222 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1225 private void setMessageExpirationTime(final int expirationTime
) {
1226 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1229 private void setGroupPermissionAddMember(final String permission
) {
1230 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1233 private void setGroupPermissionEditDetails(final String permission
) {
1234 updateGroup(UpdateGroup
.newBuilder()
1235 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1239 private void setGroupPermissionSendMessage(final String permission
) {
1240 updateGroup(UpdateGroup
.newBuilder()
1241 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1245 private void setIsBlocked(final boolean isBlocked
) {
1247 m
.setGroupBlocked(groupId
, isBlocked
);
1248 } catch (NotMasterDeviceException e
) {
1249 throw new Error
.Failure("This command doesn't work on linked devices.");
1250 } catch (GroupNotFoundException e
) {
1251 throw new Error
.GroupNotFound(e
.getMessage());
1252 } catch (IOException e
) {
1253 throw new Error
.Failure(e
.getMessage());
1257 private void updateGroup(final UpdateGroup updateGroup
) {
1259 m
.updateGroup(groupId
, updateGroup
);
1260 } catch (IOException e
) {
1261 throw new Error
.Failure(e
.getMessage());
1262 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1263 throw new Error
.GroupNotFound(e
.getMessage());
1264 } catch (AttachmentInvalidException e
) {
1265 throw new Error
.AttachmentInvalid(e
.getMessage());