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
.SendMessageResults
;
18 import org
.asamk
.signal
.manager
.api
.TypingAction
;
19 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
20 import org
.asamk
.signal
.manager
.groups
.GroupId
;
21 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
22 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
23 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
24 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
25 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
26 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
27 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
29 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
30 import org
.asamk
.signal
.util
.SendMessageResultUtils
;
31 import org
.freedesktop
.dbus
.DBusPath
;
32 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
33 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
35 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
36 import org
.freedesktop
.dbus
.types
.Variant
;
37 import org
.slf4j
.Logger
;
38 import org
.slf4j
.LoggerFactory
;
41 import java
.io
.IOException
;
43 import java
.net
.URISyntaxException
;
44 import java
.util
.ArrayList
;
45 import java
.util
.Arrays
;
46 import java
.util
.Base64
;
47 import java
.util
.Collection
;
48 import java
.util
.HashSet
;
49 import java
.util
.List
;
51 import java
.util
.Objects
;
52 import java
.util
.Optional
;
54 import java
.util
.UUID
;
55 import java
.util
.stream
.Collectors
;
56 import java
.util
.stream
.Stream
;
58 public class DbusSignalImpl
implements Signal
{
60 private final Manager m
;
61 private final DBusConnection connection
;
62 private final String objectPath
;
63 private final boolean noReceiveOnStart
;
65 private DBusPath thisDevice
;
66 private final List
<StructDevice
> devices
= new ArrayList
<>();
67 private final List
<StructGroup
> groups
= new ArrayList
<>();
68 private DbusReceiveMessageHandler dbusMessageHandler
;
69 private int subscriberCount
;
71 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
73 public DbusSignalImpl(
74 final Manager m
, DBusConnection connection
, final String objectPath
, final boolean noReceiveOnStart
77 this.connection
= connection
;
78 this.objectPath
= objectPath
;
79 this.noReceiveOnStart
= noReceiveOnStart
;
82 public void initObjects() {
83 if (!noReceiveOnStart
) {
89 updateConfiguration();
93 if (dbusMessageHandler
!= null) {
94 m
.removeReceiveHandler(dbusMessageHandler
);
95 dbusMessageHandler
= null;
99 unExportConfiguration();
103 public String
getObjectPath() {
108 public String
getSelfNumber() {
109 return m
.getSelfNumber();
113 public void subscribeReceive() {
114 if (dbusMessageHandler
== null) {
115 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
116 m
.addReceiveHandler(dbusMessageHandler
);
122 public void unsubscribeReceive() {
123 subscriberCount
= Math
.max(0, subscriberCount
- 1);
124 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
125 m
.removeReceiveHandler(dbusMessageHandler
);
126 dbusMessageHandler
= null;
131 public void submitRateLimitChallenge(String challenge
, String captcha
) {
133 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
134 } catch (IOException e
) {
135 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
141 public void unregister() throws Error
.Failure
{
144 } catch (IOException e
) {
145 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
150 public void deleteAccount() throws Error
.Failure
{
153 } catch (IOException e
) {
154 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
159 public void addDevice(String uri
) {
161 m
.addDeviceLink(new URI(uri
));
162 } catch (IOException
| InvalidDeviceLinkException e
) {
163 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
164 } catch (URISyntaxException e
) {
165 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
166 + " Device link uri has invalid format: "
172 public DBusPath
getDevice(long deviceId
) {
174 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
175 if (deviceOptional
.isEmpty()) {
176 throw new Error
.DeviceNotFound("Device not found");
178 return deviceOptional
.get().getObjectPath();
182 public List
<StructDevice
> listDevices() {
188 public DBusPath
getThisDevice() {
194 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
195 return sendMessage(message
, attachments
, List
.of(recipient
));
199 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
201 final var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
202 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
203 .map(RecipientIdentifier
.class::cast
)
204 .collect(Collectors
.toSet()));
206 checkSendMessageResults(results
);
207 return results
.timestamp();
208 } catch (AttachmentInvalidException e
) {
209 throw new Error
.AttachmentInvalid(e
.getMessage());
210 } catch (IOException e
) {
211 throw new Error
.Failure(e
);
212 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
213 throw new Error
.GroupNotFound(e
.getMessage());
218 public long sendRemoteDeleteMessage(
219 final long targetSentTimestamp
, final String recipient
221 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
225 public long sendRemoteDeleteMessage(
226 final long targetSentTimestamp
, final List
<String
> recipients
229 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
230 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
231 .map(RecipientIdentifier
.class::cast
)
232 .collect(Collectors
.toSet()));
233 checkSendMessageResults(results
);
234 return results
.timestamp();
235 } catch (IOException e
) {
236 throw new Error
.Failure(e
.getMessage());
237 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
238 throw new Error
.GroupNotFound(e
.getMessage());
243 public long sendMessageReaction(
245 final boolean remove
,
246 final String targetAuthor
,
247 final long targetSentTimestamp
,
248 final String recipient
250 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
254 public long sendMessageReaction(
256 final boolean remove
,
257 final String targetAuthor
,
258 final long targetSentTimestamp
,
259 final List
<String
> recipients
262 final var results
= m
.sendMessageReaction(emoji
,
264 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
266 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
267 .map(RecipientIdentifier
.class::cast
)
268 .collect(Collectors
.toSet()));
269 checkSendMessageResults(results
);
270 return results
.timestamp();
271 } catch (IOException e
) {
272 throw new Error
.Failure(e
.getMessage());
273 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
274 throw new Error
.GroupNotFound(e
.getMessage());
279 public void sendTyping(
280 final String recipient
, final boolean stop
281 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
283 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
284 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
285 .map(RecipientIdentifier
.class::cast
)
286 .collect(Collectors
.toSet()));
287 checkSendMessageResults(results
);
288 } catch (IOException e
) {
289 throw new Error
.Failure(e
.getMessage());
290 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
291 throw new Error
.GroupNotFound(e
.getMessage());
296 public void sendReadReceipt(
297 final String recipient
, final List
<Long
> messageIds
298 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
300 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
302 checkSendMessageResults(results
);
303 } catch (IOException e
) {
304 throw new Error
.Failure(e
.getMessage());
309 public void sendViewedReceipt(
310 final String recipient
, final List
<Long
> messageIds
311 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
313 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
315 checkSendMessageResults(results
);
316 } catch (IOException e
) {
317 throw new Error
.Failure(e
.getMessage());
322 public void sendContacts() {
325 } catch (IOException e
) {
326 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
331 public void sendSyncRequest() {
333 m
.requestAllSyncData();
334 } catch (IOException e
) {
335 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
340 public long sendNoteToSelfMessage(
341 final String message
, final List
<String
> attachments
342 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
344 final var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
345 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
346 checkSendMessageResults(results
);
347 return results
.timestamp();
348 } catch (AttachmentInvalidException e
) {
349 throw new Error
.AttachmentInvalid(e
.getMessage());
350 } catch (IOException e
) {
351 throw new Error
.Failure(e
.getMessage());
352 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
353 throw new Error
.GroupNotFound(e
.getMessage());
358 public void sendEndSessionMessage(final List
<String
> recipients
) {
360 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
361 checkSendMessageResults(results
);
362 } catch (IOException e
) {
363 throw new Error
.Failure(e
.getMessage());
368 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
370 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
371 } catch (IOException e
) {
372 throw new Error
.Failure("Recipient not found");
377 public void deleteContact(final String recipient
) throws Error
.Failure
{
379 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
380 } catch (IOException e
) {
381 throw new Error
.Failure("Contact not found");
386 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
388 var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
389 Set
.of(getGroupRecipientIdentifier(groupId
)));
390 checkSendMessageResults(results
);
391 return results
.timestamp();
392 } catch (IOException e
) {
393 throw new Error
.Failure(e
.getMessage());
394 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
395 throw new Error
.GroupNotFound(e
.getMessage());
396 } catch (AttachmentInvalidException e
) {
397 throw new Error
.AttachmentInvalid(e
.getMessage());
402 public void sendGroupTyping(
403 final byte[] groupId
, final boolean stop
404 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
406 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
407 Set
.of(getGroupRecipientIdentifier(groupId
)));
408 checkSendMessageResults(results
);
409 } catch (IOException e
) {
410 throw new Error
.Failure(e
.getMessage());
411 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
412 throw new Error
.GroupNotFound(e
.getMessage());
417 public long sendGroupRemoteDeleteMessage(
418 final long targetSentTimestamp
, final byte[] groupId
421 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
422 Set
.of(getGroupRecipientIdentifier(groupId
)));
423 checkSendMessageResults(results
);
424 return results
.timestamp();
425 } catch (IOException e
) {
426 throw new Error
.Failure(e
.getMessage());
427 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
428 throw new Error
.GroupNotFound(e
.getMessage());
433 public long sendGroupMessageReaction(
435 final boolean remove
,
436 final String targetAuthor
,
437 final long targetSentTimestamp
,
441 final var results
= m
.sendMessageReaction(emoji
,
443 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
445 Set
.of(getGroupRecipientIdentifier(groupId
)));
446 checkSendMessageResults(results
);
447 return results
.timestamp();
448 } catch (IOException e
) {
449 throw new Error
.Failure(e
.getMessage());
450 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
451 throw new Error
.GroupNotFound(e
.getMessage());
455 // Since contact names might be empty if not defined, also potentially return
458 public String
getContactName(final String number
) {
459 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
460 return name
== null ?
"" : name
;
464 public void setContactName(final String number
, final String name
) {
466 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
467 } catch (NotMasterDeviceException e
) {
468 throw new Error
.Failure("This command doesn't work on linked devices.");
469 } catch (IOException e
) {
470 throw new Error
.Failure("Contact is not registered.");
475 public void setExpirationTimer(final String number
, final int expiration
) {
477 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
478 } catch (IOException e
) {
479 throw new Error
.Failure(e
.getMessage());
484 public void setContactBlocked(final String number
, final boolean blocked
) {
486 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
487 } catch (NotMasterDeviceException e
) {
488 throw new Error
.Failure("This command doesn't work on linked devices.");
489 } catch (IOException e
) {
490 throw new Error
.Failure(e
.getMessage());
495 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
497 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
498 } catch (NotMasterDeviceException e
) {
499 throw new Error
.Failure("This command doesn't work on linked devices.");
500 } catch (GroupNotFoundException e
) {
501 throw new Error
.GroupNotFound(e
.getMessage());
502 } catch (IOException e
) {
503 throw new Error
.Failure(e
.getMessage());
508 public List
<byte[]> getGroupIds() {
509 var groups
= m
.getGroups();
510 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
514 public DBusPath
getGroup(final byte[] groupId
) {
516 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
517 if (groupOptional
.isEmpty()) {
518 throw new Error
.GroupNotFound("Group not found");
520 return groupOptional
.get().getObjectPath();
524 public List
<StructGroup
> listGroups() {
530 public String
getGroupName(final byte[] groupId
) {
531 var group
= m
.getGroup(getGroupId(groupId
));
532 if (group
== null || group
.title() == null) {
535 return group
.title();
540 public List
<String
> getGroupMembers(final byte[] groupId
) {
541 var group
= m
.getGroup(getGroupId(groupId
));
545 final var members
= group
.members();
546 return getRecipientStrings(members
);
551 public byte[] createGroup(
552 final String name
, final List
<String
> members
, final String avatar
553 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
554 return updateGroup(new byte[0], name
, members
, avatar
);
558 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
560 groupId
= nullIfEmpty(groupId
);
561 name
= nullIfEmpty(name
);
562 avatar
= nullIfEmpty(avatar
);
563 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
564 if (groupId
== null) {
565 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
567 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
568 return results
.first().serialize();
570 final var results
= m
.updateGroup(getGroupId(groupId
),
571 UpdateGroup
.newBuilder()
573 .withMembers(memberIdentifiers
)
574 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
576 if (results
!= null) {
577 checkGroupSendMessageResults(results
.timestamp(), results
.results());
581 } catch (IOException e
) {
582 throw new Error
.Failure(e
.getMessage());
583 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
584 throw new Error
.GroupNotFound(e
.getMessage());
585 } catch (AttachmentInvalidException e
) {
586 throw new Error
.AttachmentInvalid(e
.getMessage());
591 public boolean isRegistered() {
596 public boolean isRegistered(String number
) {
597 var result
= isRegistered(List
.of(number
));
598 return result
.get(0);
602 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
603 if (numbers
.isEmpty()) {
607 Map
<String
, Pair
<String
, UUID
>> registered
;
609 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
610 } catch (IOException e
) {
611 throw new Error
.Failure(e
.getMessage());
614 return numbers
.stream().map(number
-> {
615 var uuid
= registered
.get(number
).second();
621 public void updateProfile(
627 final boolean removeAvatar
630 givenName
= nullIfEmpty(givenName
);
631 familyName
= nullIfEmpty(familyName
);
632 about
= nullIfEmpty(about
);
633 aboutEmoji
= nullIfEmpty(aboutEmoji
);
634 avatarPath
= nullIfEmpty(avatarPath
);
635 Optional
<File
> avatarFile
= removeAvatar
637 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
638 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
639 } catch (IOException e
) {
640 throw new Error
.Failure(e
.getMessage());
645 public void updateProfile(
648 final String aboutEmoji
,
650 final boolean removeAvatar
652 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
656 public void removePin() {
658 m
.setRegistrationLockPin(Optional
.empty());
659 } catch (IOException e
) {
660 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
665 public void setPin(String registrationLockPin
) {
667 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
668 } catch (IOException e
) {
669 throw new Error
.Failure("Set pin error: " + e
.getMessage());
673 // Provide option to query a version string in order to react on potential
674 // future interface changes
676 public String
version() {
677 return BaseConfig
.PROJECT_VERSION
;
680 // Create a unique list of Numbers from Identities and Contacts to really get
681 // all numbers the system knows
683 public List
<String
> listNumbers() {
684 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
685 m
.getContacts().stream().map(Pair
::first
))
686 .map(a
-> a
.number().orElse(null))
687 .filter(Objects
::nonNull
)
693 public List
<String
> getContactNumber(final String name
) {
694 // Contact names have precedence.
695 var numbers
= new ArrayList
<String
>();
696 var contacts
= m
.getContacts();
697 for (var c
: contacts
) {
698 if (name
.equals(c
.second().getName())) {
699 numbers
.add(c
.first().getLegacyIdentifier());
702 // Try profiles if no contact name was found
703 for (var identity
: m
.getIdentities()) {
704 final var address
= identity
.recipient();
705 var number
= address
.number().orElse(null);
706 if (number
!= null) {
707 Profile profile
= null;
709 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
710 } catch (IOException ignored
) {
712 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
721 public void quitGroup(final byte[] groupId
) {
722 var group
= getGroupId(groupId
);
724 m
.quitGroup(group
, Set
.of());
725 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
726 throw new Error
.GroupNotFound(e
.getMessage());
727 } catch (IOException
| LastGroupAdminException e
) {
728 throw new Error
.Failure(e
.getMessage());
733 public byte[] joinGroup(final String groupLink
) {
735 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
736 if (linkUrl
== null) {
737 throw new Error
.Failure("Group link is invalid:");
739 final var result
= m
.joinGroup(linkUrl
);
740 return result
.first().serialize();
741 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
742 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
743 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
744 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
745 } catch (IOException e
) {
746 throw new Error
.Failure(e
.getMessage());
751 public boolean isContactBlocked(final String number
) {
752 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
756 public boolean isGroupBlocked(final byte[] groupId
) {
757 var group
= m
.getGroup(getGroupId(groupId
));
761 return group
.isBlocked();
766 public boolean isMember(final byte[] groupId
) {
767 var group
= m
.getGroup(getGroupId(groupId
));
771 return group
.isMember();
776 public String
uploadStickerPack(String stickerPackPath
) {
777 File path
= new File(stickerPackPath
);
779 return m
.uploadStickerPack(path
).toString();
780 } catch (IOException e
) {
781 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
782 } catch (StickerPackInvalidException e
) {
783 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
787 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
788 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
794 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
796 if (result
.isIdentityFailure()) {
797 throw new Error
.UntrustedIdentity(message
);
799 throw new Error
.Failure(message
);
803 private void checkSendMessageResults(final SendMessageResults results
) {
804 final var sendMessageResults
= results
.results().values().stream().findFirst();
805 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
806 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
810 if (results
.hasSuccess()) {
814 var message
= new StringBuilder();
815 message
.append("Failed to send messages:\n");
816 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
817 for (var error
: errors
) {
818 message
.append(error
).append('\n');
820 message
.append(results
.timestamp());
822 throw new Error
.Failure(message
.toString());
825 private static void checkGroupSendMessageResults(
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() < results
.size()) {
838 var message
= new StringBuilder();
839 message
.append("Failed to send message:\n");
840 for (var error
: errors
) {
841 message
.append(error
).append('\n');
843 message
.append(timestamp
);
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 deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1158 m
.deleteGroup(groupId
);
1159 } catch (IOException e
) {
1160 throw new Error
.Failure(e
.getMessage());
1166 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1167 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1168 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1172 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1173 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1174 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1178 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1179 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1180 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1184 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1185 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1186 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1190 public void resetLink() throws Error
.Failure
{
1191 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1195 public void disableLink() throws Error
.Failure
{
1196 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1200 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1201 updateGroup(UpdateGroup
.newBuilder()
1202 .withGroupLinkState(requiresApproval
1203 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1204 : GroupLinkState
.ENABLED
)
1208 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1209 return m
.getGroup(groupId
);
1212 private void setGroupName(final String name
) {
1213 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1216 private void setGroupDescription(final String description
) {
1217 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1220 private void setGroupAvatar(final String avatar
) {
1221 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1224 private void setMessageExpirationTime(final int expirationTime
) {
1225 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1228 private void setGroupPermissionAddMember(final String permission
) {
1229 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1232 private void setGroupPermissionEditDetails(final String permission
) {
1233 updateGroup(UpdateGroup
.newBuilder()
1234 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1238 private void setGroupPermissionSendMessage(final String permission
) {
1239 updateGroup(UpdateGroup
.newBuilder()
1240 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1244 private void setIsBlocked(final boolean isBlocked
) {
1246 m
.setGroupBlocked(groupId
, isBlocked
);
1247 } catch (NotMasterDeviceException e
) {
1248 throw new Error
.Failure("This command doesn't work on linked devices.");
1249 } catch (GroupNotFoundException e
) {
1250 throw new Error
.GroupNotFound(e
.getMessage());
1251 } catch (IOException e
) {
1252 throw new Error
.Failure(e
.getMessage());
1256 private void updateGroup(final UpdateGroup updateGroup
) {
1258 m
.updateGroup(groupId
, updateGroup
);
1259 } catch (IOException e
) {
1260 throw new Error
.Failure(e
.getMessage());
1261 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1262 throw new Error
.GroupNotFound(e
.getMessage());
1263 } catch (AttachmentInvalidException e
) {
1264 throw new Error
.AttachmentInvalid(e
.getMessage());