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 sendGroupRemoteDeleteMessage(
243 final long targetSentTimestamp
, final byte[] groupId
246 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
247 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
248 checkSendMessageResults(results
.timestamp(), results
.results());
249 return results
.timestamp();
250 } catch (IOException e
) {
251 throw new Error
.Failure(e
.getMessage());
252 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
253 throw new Error
.GroupNotFound(e
.getMessage());
258 public long sendMessageReaction(
260 final boolean remove
,
261 final String targetAuthor
,
262 final long targetSentTimestamp
,
263 final String recipient
265 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
269 public long sendMessageReaction(
271 final boolean remove
,
272 final String targetAuthor
,
273 final long targetSentTimestamp
,
274 final List
<String
> recipients
277 final var results
= m
.sendMessageReaction(emoji
,
279 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
281 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
282 .map(RecipientIdentifier
.class::cast
)
283 .collect(Collectors
.toSet()));
284 checkSendMessageResults(results
.timestamp(), results
.results());
285 return results
.timestamp();
286 } catch (IOException e
) {
287 throw new Error
.Failure(e
.getMessage());
288 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
289 throw new Error
.GroupNotFound(e
.getMessage());
294 public void sendTyping(
295 final String recipient
, final boolean stop
296 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
298 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
299 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
300 .map(RecipientIdentifier
.class::cast
)
301 .collect(Collectors
.toSet()));
302 checkSendMessageResults(results
.timestamp(), results
.results());
303 } catch (IOException e
) {
304 throw new Error
.Failure(e
.getMessage());
305 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
306 throw new Error
.GroupNotFound(e
.getMessage());
311 public void sendReadReceipt(
312 final String recipient
, final List
<Long
> messageIds
313 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
315 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
317 checkSendMessageResults(results
.timestamp(), results
.results());
318 } catch (IOException e
) {
319 throw new Error
.Failure(e
.getMessage());
324 public void sendViewedReceipt(
325 final String recipient
, final List
<Long
> messageIds
326 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
328 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
330 checkSendMessageResults(results
.timestamp(), results
.results());
331 } catch (IOException e
) {
332 throw new Error
.Failure(e
.getMessage());
337 public void sendContacts() {
340 } catch (IOException e
) {
341 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
346 public void sendSyncRequest() {
348 m
.requestAllSyncData();
349 } catch (IOException e
) {
350 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
355 public long sendNoteToSelfMessage(
356 final String message
, final List
<String
> attachments
357 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
359 final var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
360 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
361 checkSendMessageResults(results
.timestamp(), results
.results());
362 return results
.timestamp();
363 } catch (AttachmentInvalidException e
) {
364 throw new Error
.AttachmentInvalid(e
.getMessage());
365 } catch (IOException e
) {
366 throw new Error
.Failure(e
.getMessage());
367 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
368 throw new Error
.GroupNotFound(e
.getMessage());
373 public void sendEndSessionMessage(final List
<String
> recipients
) {
375 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
376 checkSendMessageResults(results
.timestamp(), results
.results());
377 } catch (IOException e
) {
378 throw new Error
.Failure(e
.getMessage());
383 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
385 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
386 } catch (IOException e
) {
387 throw new Error
.Failure("Recipient not found");
392 public void deleteContact(final String recipient
) throws Error
.Failure
{
394 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
395 } catch (IOException e
) {
396 throw new Error
.Failure("Contact not found");
401 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
403 var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
404 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
405 checkSendMessageResults(results
.timestamp(), results
.results());
406 return results
.timestamp();
407 } catch (IOException e
) {
408 throw new Error
.Failure(e
.getMessage());
409 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
410 throw new Error
.GroupNotFound(e
.getMessage());
411 } catch (AttachmentInvalidException e
) {
412 throw new Error
.AttachmentInvalid(e
.getMessage());
417 public long sendGroupMessageReaction(
419 final boolean remove
,
420 final String targetAuthor
,
421 final long targetSentTimestamp
,
425 final var results
= m
.sendMessageReaction(emoji
,
427 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
429 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
430 checkSendMessageResults(results
.timestamp(), results
.results());
431 return results
.timestamp();
432 } catch (IOException e
) {
433 throw new Error
.Failure(e
.getMessage());
434 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
435 throw new Error
.GroupNotFound(e
.getMessage());
439 // Since contact names might be empty if not defined, also potentially return
442 public String
getContactName(final String number
) {
443 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
444 return name
== null ?
"" : name
;
448 public void setContactName(final String number
, final String name
) {
450 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
451 } catch (NotMasterDeviceException e
) {
452 throw new Error
.Failure("This command doesn't work on linked devices.");
453 } catch (IOException e
) {
454 throw new Error
.Failure("Contact is not registered.");
459 public void setExpirationTimer(final String number
, final int expiration
) {
461 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
462 } catch (IOException e
) {
463 throw new Error
.Failure(e
.getMessage());
468 public void setContactBlocked(final String number
, final boolean blocked
) {
470 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
471 } catch (NotMasterDeviceException e
) {
472 throw new Error
.Failure("This command doesn't work on linked devices.");
473 } catch (IOException e
) {
474 throw new Error
.Failure(e
.getMessage());
479 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
481 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
482 } catch (NotMasterDeviceException e
) {
483 throw new Error
.Failure("This command doesn't work on linked devices.");
484 } catch (GroupNotFoundException e
) {
485 throw new Error
.GroupNotFound(e
.getMessage());
486 } catch (IOException e
) {
487 throw new Error
.Failure(e
.getMessage());
492 public List
<byte[]> getGroupIds() {
493 var groups
= m
.getGroups();
494 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
498 public DBusPath
getGroup(final byte[] groupId
) {
500 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
501 if (groupOptional
.isEmpty()) {
502 throw new Error
.GroupNotFound("Group not found");
504 return groupOptional
.get().getObjectPath();
508 public List
<StructGroup
> listGroups() {
514 public String
getGroupName(final byte[] groupId
) {
515 var group
= m
.getGroup(getGroupId(groupId
));
516 if (group
== null || group
.title() == null) {
519 return group
.title();
524 public List
<String
> getGroupMembers(final byte[] groupId
) {
525 var group
= m
.getGroup(getGroupId(groupId
));
529 final var members
= group
.members();
530 return getRecipientStrings(members
);
535 public byte[] createGroup(
536 final String name
, final List
<String
> members
, final String avatar
537 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
538 return updateGroup(new byte[0], name
, members
, avatar
);
542 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
544 groupId
= nullIfEmpty(groupId
);
545 name
= nullIfEmpty(name
);
546 avatar
= nullIfEmpty(avatar
);
547 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
548 if (groupId
== null) {
549 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
550 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
551 return results
.first().serialize();
553 final var results
= m
.updateGroup(getGroupId(groupId
),
554 UpdateGroup
.newBuilder()
556 .withMembers(memberIdentifiers
)
557 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
559 if (results
!= null) {
560 checkSendMessageResults(results
.timestamp(), results
.results());
564 } catch (IOException e
) {
565 throw new Error
.Failure(e
.getMessage());
566 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
567 throw new Error
.GroupNotFound(e
.getMessage());
568 } catch (AttachmentInvalidException e
) {
569 throw new Error
.AttachmentInvalid(e
.getMessage());
574 public boolean isRegistered() {
579 public boolean isRegistered(String number
) {
580 var result
= isRegistered(List
.of(number
));
581 return result
.get(0);
585 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
586 if (numbers
.isEmpty()) {
590 Map
<String
, Pair
<String
, UUID
>> registered
;
592 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
593 } catch (IOException e
) {
594 throw new Error
.Failure(e
.getMessage());
597 return numbers
.stream().map(number
-> {
598 var uuid
= registered
.get(number
).second();
604 public void updateProfile(
610 final boolean removeAvatar
613 givenName
= nullIfEmpty(givenName
);
614 familyName
= nullIfEmpty(familyName
);
615 about
= nullIfEmpty(about
);
616 aboutEmoji
= nullIfEmpty(aboutEmoji
);
617 avatarPath
= nullIfEmpty(avatarPath
);
618 Optional
<File
> avatarFile
= removeAvatar
620 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
621 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
622 } catch (IOException e
) {
623 throw new Error
.Failure(e
.getMessage());
628 public void updateProfile(
631 final String aboutEmoji
,
633 final boolean removeAvatar
635 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
639 public void removePin() {
641 m
.setRegistrationLockPin(Optional
.empty());
642 } catch (IOException e
) {
643 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
648 public void setPin(String registrationLockPin
) {
650 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
651 } catch (IOException e
) {
652 throw new Error
.Failure("Set pin error: " + e
.getMessage());
656 // Provide option to query a version string in order to react on potential
657 // future interface changes
659 public String
version() {
660 return BaseConfig
.PROJECT_VERSION
;
663 // Create a unique list of Numbers from Identities and Contacts to really get
664 // all numbers the system knows
666 public List
<String
> listNumbers() {
667 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
668 m
.getContacts().stream().map(Pair
::first
))
669 .map(a
-> a
.number().orElse(null))
670 .filter(Objects
::nonNull
)
676 public List
<String
> getContactNumber(final String name
) {
677 // Contact names have precedence.
678 var numbers
= new ArrayList
<String
>();
679 var contacts
= m
.getContacts();
680 for (var c
: contacts
) {
681 if (name
.equals(c
.second().getName())) {
682 numbers
.add(c
.first().getLegacyIdentifier());
685 // Try profiles if no contact name was found
686 for (var identity
: m
.getIdentities()) {
687 final var address
= identity
.recipient();
688 var number
= address
.number().orElse(null);
689 if (number
!= null) {
690 Profile profile
= null;
692 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
693 } catch (IOException ignored
) {
695 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
704 public void quitGroup(final byte[] groupId
) {
705 var group
= getGroupId(groupId
);
707 m
.quitGroup(group
, Set
.of());
708 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
709 throw new Error
.GroupNotFound(e
.getMessage());
710 } catch (IOException
| LastGroupAdminException e
) {
711 throw new Error
.Failure(e
.getMessage());
716 public byte[] joinGroup(final String groupLink
) {
718 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
719 if (linkUrl
== null) {
720 throw new Error
.Failure("Group link is invalid:");
722 final var result
= m
.joinGroup(linkUrl
);
723 return result
.first().serialize();
724 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
725 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
726 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
727 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
728 } catch (IOException e
) {
729 throw new Error
.Failure(e
.getMessage());
734 public boolean isContactBlocked(final String number
) {
735 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
739 public boolean isGroupBlocked(final byte[] groupId
) {
740 var group
= m
.getGroup(getGroupId(groupId
));
744 return group
.isBlocked();
749 public boolean isMember(final byte[] groupId
) {
750 var group
= m
.getGroup(getGroupId(groupId
));
754 return group
.isMember();
759 public String
uploadStickerPack(String stickerPackPath
) {
760 File path
= new File(stickerPackPath
);
762 return m
.uploadStickerPack(path
).toString();
763 } catch (IOException e
) {
764 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
765 } catch (StickerPackInvalidException e
) {
766 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
770 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
771 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
777 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
779 if (result
.isIdentityFailure()) {
780 throw new Error
.UntrustedIdentity(message
);
782 throw new Error
.Failure(message
);
786 private static void checkSendMessageResults(
787 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
788 ) throws DBusExecutionException
{
789 final var sendMessageResults
= results
.values().stream().findFirst();
790 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
791 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
795 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
796 if (errors
.size() == 0) {
800 var message
= new StringBuilder();
801 message
.append(timestamp
).append('\n');
802 message
.append("Failed to send (some) messages:\n");
803 for (var error
: errors
) {
804 message
.append(error
).append('\n');
807 throw new Error
.Failure(message
.toString());
810 private static void checkSendMessageResults(
811 long timestamp
, Collection
<SendMessageResult
> results
812 ) throws DBusExecutionException
{
813 if (results
.size() == 1) {
814 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
818 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
819 if (errors
.size() == 0) {
823 var message
= new StringBuilder();
824 message
.append(timestamp
).append('\n');
825 message
.append("Failed to send (some) messages:\n");
826 for (var error
: errors
) {
827 message
.append(error
).append('\n');
830 throw new Error
.Failure(message
.toString());
833 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
834 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
837 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
838 final Collection
<String
> recipientStrings
, final String localNumber
839 ) throws DBusExecutionException
{
840 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
841 for (var recipientString
: recipientStrings
) {
842 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
847 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
848 final String recipientString
, final String localNumber
849 ) throws DBusExecutionException
{
851 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
852 } catch (InvalidNumberException e
) {
853 throw new Error
.InvalidNumber(e
.getMessage());
857 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
859 return GroupId
.unknownVersion(groupId
);
860 } catch (Throwable e
) {
861 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
865 private byte[] nullIfEmpty(final byte[] array
) {
866 return array
.length
== 0 ?
null : array
;
869 private String
nullIfEmpty(final String name
) {
870 return name
.isEmpty() ?
null : name
;
873 private String
emptyIfNull(final String string
) {
874 return string
== null ?
"" : string
;
877 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
878 return basePath
+ "/Devices/" + deviceId
;
881 private void updateDevices() {
882 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
884 linkedDevices
= m
.getLinkedDevices();
885 } catch (IOException e
) {
886 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
891 linkedDevices
.forEach(d
-> {
892 final var object
= new DbusSignalDeviceImpl(d
);
893 final var deviceObjectPath
= object
.getObjectPath();
894 exportObject(object
);
895 if (d
.isThisDevice()) {
896 thisDevice
= new DBusPath(deviceObjectPath
);
898 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
902 private void unExportDevices() {
903 this.devices
.stream()
904 .map(StructDevice
::getObjectPath
)
905 .map(DBusPath
::getPath
)
906 .forEach(connection
::unExportObject
);
907 this.devices
.clear();
910 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
911 return basePath
+ "/Groups/" + Base64
.getEncoder()
912 .encodeToString(groupId
)
918 private void updateGroups() {
919 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
920 groups
= m
.getGroups();
924 groups
.forEach(g
-> {
925 final var object
= new DbusSignalGroupImpl(g
.groupId());
926 exportObject(object
);
927 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
928 g
.groupId().serialize(),
929 emptyIfNull(g
.title())));
933 private void unExportGroups() {
934 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
938 private static String
getConfigurationObjectPath(String basePath
) {
939 return basePath
+ "/Configuration";
942 private void updateConfiguration() {
943 unExportConfiguration();
944 final var object
= new DbusSignalConfigurationImpl();
945 exportObject(object
);
948 private void unExportConfiguration() {
949 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
950 connection
.unExportObject(objectPath
);
953 private void exportObject(final DBusInterface object
) {
955 connection
.exportObject(object
);
956 logger
.debug("Exported dbus object: " + object
.getObjectPath());
957 } catch (DBusException e
) {
962 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
964 private final org
.asamk
.signal
.manager
.api
.Device device
;
966 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
967 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
968 List
.of(new DbusProperty
<>("Id", device
::id
),
969 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
970 new DbusProperty
<>("Created", device
::created
),
971 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
972 this.device
= device
;
976 public String
getObjectPath() {
977 return getDeviceObjectPath(objectPath
, device
.id());
981 public void removeDevice() throws Error
.Failure
{
983 m
.removeLinkedDevices(device
.id());
985 } catch (IOException e
) {
986 throw new Error
.Failure(e
.getMessage());
990 private void setDeviceName(String name
) {
991 if (!device
.isThisDevice()) {
992 throw new Error
.Failure("Only the name of this device can be changed");
995 m
.updateAccountAttributes(name
);
996 // update device list
998 } catch (IOException e
) {
999 throw new Error
.Failure(e
.getMessage());
1004 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1006 public DbusSignalConfigurationImpl(
1008 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1009 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1010 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1011 this::getUnidentifiedDeliveryIndicators
,
1012 this::setUnidentifiedDeliveryIndicators
),
1013 new DbusProperty
<>("TypingIndicators",
1014 this::getTypingIndicators
,
1015 this::setTypingIndicators
),
1016 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1021 public String
getObjectPath() {
1022 return getConfigurationObjectPath(objectPath
);
1025 public void setReadReceipts(Boolean readReceipts
) {
1026 setConfiguration(readReceipts
, null, null, null);
1029 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1030 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1033 public void setTypingIndicators(Boolean typingIndicators
) {
1034 setConfiguration(null, null, typingIndicators
, null);
1037 public void setLinkPreviews(Boolean linkPreviews
) {
1038 setConfiguration(null, null, null, linkPreviews
);
1041 private void setConfiguration(
1042 Boolean readReceipts
,
1043 Boolean unidentifiedDeliveryIndicators
,
1044 Boolean typingIndicators
,
1045 Boolean linkPreviews
1048 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1049 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1050 Optional
.ofNullable(typingIndicators
),
1051 Optional
.ofNullable(linkPreviews
)));
1052 } catch (IOException e
) {
1053 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1054 } catch (NotMasterDeviceException e
) {
1055 throw new Error
.Failure("This command doesn't work on linked devices.");
1059 private boolean getReadReceipts() {
1060 return m
.getConfiguration().readReceipts().orElse(false);
1063 private boolean getUnidentifiedDeliveryIndicators() {
1064 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1067 private boolean getTypingIndicators() {
1068 return m
.getConfiguration().typingIndicators().orElse(false);
1071 private boolean getLinkPreviews() {
1072 return m
.getConfiguration().linkPreviews().orElse(false);
1076 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1078 private final GroupId groupId
;
1080 public DbusSignalGroupImpl(final GroupId groupId
) {
1081 this.groupId
= groupId
;
1082 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1083 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1084 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1085 new DbusProperty
<>("Description",
1086 () -> emptyIfNull(getGroup().description()),
1087 this::setGroupDescription
),
1088 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1089 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1090 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1091 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1092 new DbusProperty
<>("MessageExpirationTimer",
1093 () -> getGroup().messageExpirationTimer(),
1094 this::setMessageExpirationTime
),
1095 new DbusProperty
<>("Members",
1096 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1097 new DbusProperty
<>("PendingMembers",
1098 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1099 new DbusProperty
<>("RequestingMembers",
1100 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1101 new DbusProperty
<>("Admins",
1102 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1103 new DbusProperty
<>("PermissionAddMember",
1104 () -> getGroup().permissionAddMember().name(),
1105 this::setGroupPermissionAddMember
),
1106 new DbusProperty
<>("PermissionEditDetails",
1107 () -> getGroup().permissionEditDetails().name(),
1108 this::setGroupPermissionEditDetails
),
1109 new DbusProperty
<>("PermissionSendMessage",
1110 () -> getGroup().permissionSendMessage().name(),
1111 this::setGroupPermissionSendMessage
),
1112 new DbusProperty
<>("GroupInviteLink", () -> {
1113 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1114 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1119 public String
getObjectPath() {
1120 return getGroupObjectPath(objectPath
, groupId
.serialize());
1124 public void quitGroup() throws Error
.Failure
{
1126 m
.quitGroup(groupId
, Set
.of());
1127 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1128 throw new Error
.GroupNotFound(e
.getMessage());
1129 } catch (IOException e
) {
1130 throw new Error
.Failure(e
.getMessage());
1131 } catch (LastGroupAdminException e
) {
1132 throw new Error
.LastGroupAdmin(e
.getMessage());
1137 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1138 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1139 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1143 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1144 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1145 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1149 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1150 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1151 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1155 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1156 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1157 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1161 public void resetLink() throws Error
.Failure
{
1162 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1166 public void disableLink() throws Error
.Failure
{
1167 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1171 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1172 updateGroup(UpdateGroup
.newBuilder()
1173 .withGroupLinkState(requiresApproval
1174 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1175 : GroupLinkState
.ENABLED
)
1179 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1180 return m
.getGroup(groupId
);
1183 private void setGroupName(final String name
) {
1184 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1187 private void setGroupDescription(final String description
) {
1188 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1191 private void setGroupAvatar(final String avatar
) {
1192 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1195 private void setMessageExpirationTime(final int expirationTime
) {
1196 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1199 private void setGroupPermissionAddMember(final String permission
) {
1200 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1203 private void setGroupPermissionEditDetails(final String permission
) {
1204 updateGroup(UpdateGroup
.newBuilder()
1205 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1209 private void setGroupPermissionSendMessage(final String permission
) {
1210 updateGroup(UpdateGroup
.newBuilder()
1211 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1215 private void setIsBlocked(final boolean isBlocked
) {
1217 m
.setGroupBlocked(groupId
, isBlocked
);
1218 } catch (NotMasterDeviceException e
) {
1219 throw new Error
.Failure("This command doesn't work on linked devices.");
1220 } catch (GroupNotFoundException e
) {
1221 throw new Error
.GroupNotFound(e
.getMessage());
1222 } catch (IOException e
) {
1223 throw new Error
.Failure(e
.getMessage());
1227 private void updateGroup(final UpdateGroup updateGroup
) {
1229 m
.updateGroup(groupId
, updateGroup
);
1230 } catch (IOException e
) {
1231 throw new Error
.Failure(e
.getMessage());
1232 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1233 throw new Error
.GroupNotFound(e
.getMessage());
1234 } catch (AttachmentInvalidException e
) {
1235 throw new Error
.AttachmentInvalid(e
.getMessage());