1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.BaseConfig
;
5 import org
.asamk
.signal
.manager
.Manager
;
6 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
7 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
8 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
9 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
10 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
11 import org
.asamk
.signal
.manager
.api
.Message
;
12 import org
.asamk
.signal
.manager
.api
.NotMasterDeviceException
;
13 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
14 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
15 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
16 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
17 import org
.asamk
.signal
.manager
.api
.TypingAction
;
18 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
19 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
20 import org
.asamk
.signal
.manager
.api
.UserStatus
;
21 import org
.asamk
.signal
.manager
.groups
.GroupId
;
22 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
23 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
24 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
25 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
26 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
27 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
28 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
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
.stream
.Collectors
;
56 public class DbusSignalImpl
implements Signal
{
58 private final Manager m
;
59 private final DBusConnection connection
;
60 private final String objectPath
;
61 private final boolean noReceiveOnStart
;
63 private DBusPath thisDevice
;
64 private final List
<StructDevice
> devices
= new ArrayList
<>();
65 private final List
<StructGroup
> groups
= new ArrayList
<>();
66 private DbusReceiveMessageHandler dbusMessageHandler
;
67 private int subscriberCount
;
69 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
71 public DbusSignalImpl(
72 final Manager m
, DBusConnection connection
, final String objectPath
, final boolean noReceiveOnStart
75 this.connection
= connection
;
76 this.objectPath
= objectPath
;
77 this.noReceiveOnStart
= noReceiveOnStart
;
79 m
.addAddressChangedListener(() -> {
85 public void initObjects() {
87 if (!noReceiveOnStart
) {
92 private void exportObjects() {
97 updateConfiguration();
100 public void close() {
101 if (dbusMessageHandler
!= null) {
102 m
.removeReceiveHandler(dbusMessageHandler
);
103 dbusMessageHandler
= null;
108 private void unExportObjects() {
111 unExportConfiguration();
112 connection
.unExportObject(this.objectPath
);
116 public String
getObjectPath() {
121 public String
getSelfNumber() {
122 return m
.getSelfNumber();
126 public void subscribeReceive() {
127 if (dbusMessageHandler
== null) {
128 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
129 m
.addReceiveHandler(dbusMessageHandler
);
135 public void unsubscribeReceive() {
136 subscriberCount
= Math
.max(0, subscriberCount
- 1);
137 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
138 m
.removeReceiveHandler(dbusMessageHandler
);
139 dbusMessageHandler
= null;
144 public void submitRateLimitChallenge(String challenge
, String captcha
) {
146 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
147 } catch (IOException e
) {
148 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
154 public void unregister() throws Error
.Failure
{
157 } catch (IOException e
) {
158 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
163 public void deleteAccount() throws Error
.Failure
{
166 } catch (IOException e
) {
167 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
172 public void addDevice(String uri
) {
174 m
.addDeviceLink(new URI(uri
));
175 } catch (IOException
| InvalidDeviceLinkException e
) {
176 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
177 } catch (URISyntaxException e
) {
178 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
179 + " Device link uri has invalid format: "
185 public DBusPath
getDevice(long deviceId
) {
187 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
188 if (deviceOptional
.isEmpty()) {
189 throw new Error
.DeviceNotFound("Device not found");
191 return deviceOptional
.get().getObjectPath();
195 public List
<StructDevice
> listDevices() {
201 public DBusPath
getThisDevice() {
207 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
208 return sendMessage(message
, attachments
, List
.of(recipient
));
212 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
214 final var results
= m
.sendMessage(new Message(message
,
219 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
220 .map(RecipientIdentifier
.class::cast
)
221 .collect(Collectors
.toSet()));
223 checkSendMessageResults(results
);
224 return results
.timestamp();
225 } catch (AttachmentInvalidException e
) {
226 throw new Error
.AttachmentInvalid(e
.getMessage());
227 } catch (IOException
| InvalidStickerException e
) {
228 throw new Error
.Failure(e
);
229 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
230 throw new Error
.GroupNotFound(e
.getMessage());
231 } catch (UnregisteredRecipientException e
) {
232 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
237 public long sendRemoteDeleteMessage(
238 final long targetSentTimestamp
, final String recipient
240 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
244 public long sendRemoteDeleteMessage(
245 final long targetSentTimestamp
, final List
<String
> recipients
248 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
249 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
250 .map(RecipientIdentifier
.class::cast
)
251 .collect(Collectors
.toSet()));
252 checkSendMessageResults(results
);
253 return results
.timestamp();
254 } catch (IOException e
) {
255 throw new Error
.Failure(e
.getMessage());
256 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
257 throw new Error
.GroupNotFound(e
.getMessage());
262 public long sendMessageReaction(
264 final boolean remove
,
265 final String targetAuthor
,
266 final long targetSentTimestamp
,
267 final String recipient
269 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
273 public long sendMessageReaction(
275 final boolean remove
,
276 final String targetAuthor
,
277 final long targetSentTimestamp
,
278 final List
<String
> recipients
281 final var results
= m
.sendMessageReaction(emoji
,
283 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
285 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
286 .map(RecipientIdentifier
.class::cast
)
287 .collect(Collectors
.toSet()));
288 checkSendMessageResults(results
);
289 return results
.timestamp();
290 } catch (IOException e
) {
291 throw new Error
.Failure(e
.getMessage());
292 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
293 throw new Error
.GroupNotFound(e
.getMessage());
294 } catch (UnregisteredRecipientException e
) {
295 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
300 public void sendTyping(
301 final String recipient
, final boolean stop
302 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
304 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
305 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
306 .map(RecipientIdentifier
.class::cast
)
307 .collect(Collectors
.toSet()));
308 checkSendMessageResults(results
);
309 } catch (IOException e
) {
310 throw new Error
.Failure(e
.getMessage());
311 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
312 throw new Error
.GroupNotFound(e
.getMessage());
317 public void sendReadReceipt(
318 final String recipient
, final List
<Long
> messageIds
319 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
321 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
323 checkSendMessageResults(results
);
324 } catch (IOException e
) {
325 throw new Error
.Failure(e
.getMessage());
330 public void sendViewedReceipt(
331 final String recipient
, final List
<Long
> messageIds
332 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
334 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
336 checkSendMessageResults(results
);
337 } catch (IOException e
) {
338 throw new Error
.Failure(e
.getMessage());
343 public void sendContacts() {
346 } catch (IOException e
) {
347 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
352 public void sendSyncRequest() {
354 m
.requestAllSyncData();
355 } catch (IOException e
) {
356 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
361 public long sendNoteToSelfMessage(
362 final String message
, final List
<String
> attachments
363 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
365 final var results
= m
.sendMessage(new Message(message
,
369 Optional
.empty()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
370 checkSendMessageResults(results
);
371 return results
.timestamp();
372 } catch (AttachmentInvalidException e
) {
373 throw new Error
.AttachmentInvalid(e
.getMessage());
374 } catch (IOException
| InvalidStickerException e
) {
375 throw new Error
.Failure(e
.getMessage());
376 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
377 throw new Error
.GroupNotFound(e
.getMessage());
378 } catch (UnregisteredRecipientException e
) {
379 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
384 public void sendEndSessionMessage(final List
<String
> recipients
) {
386 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
387 checkSendMessageResults(results
);
388 } catch (IOException e
) {
389 throw new Error
.Failure(e
.getMessage());
394 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
395 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
399 public void deleteContact(final String recipient
) throws Error
.Failure
{
400 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
404 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
406 var results
= m
.sendMessage(new Message(message
,
410 Optional
.empty()), Set
.of(getGroupRecipientIdentifier(groupId
)));
411 checkSendMessageResults(results
);
412 return results
.timestamp();
413 } catch (IOException
| InvalidStickerException e
) {
414 throw new Error
.Failure(e
.getMessage());
415 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
416 throw new Error
.GroupNotFound(e
.getMessage());
417 } catch (AttachmentInvalidException e
) {
418 throw new Error
.AttachmentInvalid(e
.getMessage());
419 } catch (UnregisteredRecipientException e
) {
420 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
425 public void sendGroupTyping(
426 final byte[] groupId
, final boolean stop
427 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
429 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
430 Set
.of(getGroupRecipientIdentifier(groupId
)));
431 checkSendMessageResults(results
);
432 } catch (IOException e
) {
433 throw new Error
.Failure(e
.getMessage());
434 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
435 throw new Error
.GroupNotFound(e
.getMessage());
440 public long sendGroupRemoteDeleteMessage(
441 final long targetSentTimestamp
, final byte[] groupId
444 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
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());
456 public long sendGroupMessageReaction(
458 final boolean remove
,
459 final String targetAuthor
,
460 final long targetSentTimestamp
,
464 final var results
= m
.sendMessageReaction(emoji
,
466 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
468 Set
.of(getGroupRecipientIdentifier(groupId
)));
469 checkSendMessageResults(results
);
470 return results
.timestamp();
471 } catch (IOException e
) {
472 throw new Error
.Failure(e
.getMessage());
473 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
474 throw new Error
.GroupNotFound(e
.getMessage());
475 } catch (UnregisteredRecipientException e
) {
476 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
480 // Since contact names might be empty if not defined, also potentially return
483 public String
getContactName(final String number
) {
484 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
485 return name
== null ?
"" : name
;
489 public void setContactName(final String number
, final String name
) {
491 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
492 } catch (NotMasterDeviceException e
) {
493 throw new Error
.Failure("This command doesn't work on linked devices.");
494 } catch (IOException e
) {
495 throw new Error
.Failure("Contact is not registered.");
496 } catch (UnregisteredRecipientException e
) {
497 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
502 public void setExpirationTimer(final String number
, final int expiration
) {
504 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
505 } catch (IOException e
) {
506 throw new Error
.Failure(e
.getMessage());
507 } catch (UnregisteredRecipientException e
) {
508 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
513 public void setContactBlocked(final String number
, final boolean blocked
) {
515 m
.setContactsBlocked(List
.of(getSingleRecipientIdentifier(number
, m
.getSelfNumber())), blocked
);
516 } catch (NotMasterDeviceException e
) {
517 throw new Error
.Failure("This command doesn't work on linked devices.");
518 } catch (IOException e
) {
519 throw new Error
.Failure(e
.getMessage());
520 } catch (UnregisteredRecipientException e
) {
521 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
526 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
528 m
.setGroupsBlocked(List
.of(getGroupId(groupId
)), blocked
);
529 } catch (NotMasterDeviceException e
) {
530 throw new Error
.Failure("This command doesn't work on linked devices.");
531 } catch (GroupNotFoundException e
) {
532 throw new Error
.GroupNotFound(e
.getMessage());
533 } catch (IOException e
) {
534 throw new Error
.Failure(e
.getMessage());
539 public List
<byte[]> getGroupIds() {
540 var groups
= m
.getGroups();
541 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
545 public DBusPath
getGroup(final byte[] groupId
) {
547 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
548 if (groupOptional
.isEmpty()) {
549 throw new Error
.GroupNotFound("Group not found");
551 return groupOptional
.get().getObjectPath();
555 public List
<StructGroup
> listGroups() {
561 public String
getGroupName(final byte[] groupId
) {
562 var group
= m
.getGroup(getGroupId(groupId
));
563 if (group
== null || group
.title() == null) {
566 return group
.title();
571 public List
<String
> getGroupMembers(final byte[] groupId
) {
572 var group
= m
.getGroup(getGroupId(groupId
));
576 final var members
= group
.members();
577 return getRecipientStrings(members
);
582 public byte[] createGroup(
583 final String name
, final List
<String
> members
, final String avatar
584 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
585 return updateGroup(new byte[0], name
, members
, avatar
);
589 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
591 groupId
= nullIfEmpty(groupId
);
592 name
= nullIfEmpty(name
);
593 avatar
= nullIfEmpty(avatar
);
594 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
595 if (groupId
== null) {
596 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
598 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
599 return results
.first().serialize();
601 final var results
= m
.updateGroup(getGroupId(groupId
),
602 UpdateGroup
.newBuilder()
604 .withMembers(memberIdentifiers
)
605 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
607 if (results
!= null) {
608 checkGroupSendMessageResults(results
.timestamp(), results
.results());
612 } catch (IOException e
) {
613 throw new Error
.Failure(e
.getMessage());
614 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
615 throw new Error
.GroupNotFound(e
.getMessage());
616 } catch (AttachmentInvalidException e
) {
617 throw new Error
.AttachmentInvalid(e
.getMessage());
618 } catch (UnregisteredRecipientException e
) {
619 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
624 public boolean isRegistered() {
629 public boolean isRegistered(String number
) {
630 var result
= isRegistered(List
.of(number
));
631 return result
.get(0);
635 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
636 if (numbers
.isEmpty()) {
640 Map
<String
, UserStatus
> registered
;
642 registered
= m
.getUserStatus(new HashSet
<>(numbers
));
643 } catch (IOException e
) {
644 throw new Error
.Failure(e
.getMessage());
647 return numbers
.stream().map(number
-> registered
.get(number
).uuid() != null).toList();
651 public void updateProfile(
657 final boolean removeAvatar
660 givenName
= nullIfEmpty(givenName
);
661 familyName
= nullIfEmpty(familyName
);
662 about
= nullIfEmpty(about
);
663 aboutEmoji
= nullIfEmpty(aboutEmoji
);
664 avatarPath
= nullIfEmpty(avatarPath
);
665 Optional
<File
> avatarFile
= removeAvatar
667 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
668 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
669 } catch (IOException e
) {
670 throw new Error
.Failure(e
.getMessage());
675 public void updateProfile(
678 final String aboutEmoji
,
680 final boolean removeAvatar
682 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
686 public void removePin() {
688 m
.setRegistrationLockPin(Optional
.empty());
689 } catch (IOException e
) {
690 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
691 } catch (NotMasterDeviceException e
) {
692 throw new Error
.Failure("This command doesn't work on linked devices.");
697 public void setPin(String registrationLockPin
) {
699 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
700 } catch (IOException e
) {
701 throw new Error
.Failure("Set pin error: " + e
.getMessage());
702 } catch (NotMasterDeviceException e
) {
703 throw new Error
.Failure("This command doesn't work on linked devices.");
707 // Provide option to query a version string in order to react on potential
708 // future interface changes
710 public String
version() {
711 return BaseConfig
.PROJECT_VERSION
;
714 // Create a unique list of Numbers from Identities and Contacts to really get
715 // all numbers the system knows
717 public List
<String
> listNumbers() {
718 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.empty())
720 .map(r
-> r
.getAddress().number().orElse(null))
721 .filter(Objects
::nonNull
)
727 public List
<String
> getContactNumber(final String name
) {
728 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.of(name
))
730 .map(r
-> r
.getAddress().getLegacyIdentifier())
735 public void quitGroup(final byte[] groupId
) {
736 var group
= getGroupId(groupId
);
738 m
.quitGroup(group
, Set
.of());
739 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
740 throw new Error
.GroupNotFound(e
.getMessage());
741 } catch (IOException
| LastGroupAdminException e
) {
742 throw new Error
.Failure(e
.getMessage());
743 } catch (UnregisteredRecipientException e
) {
744 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
749 public byte[] joinGroup(final String groupLink
) {
751 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
752 if (linkUrl
== null) {
753 throw new Error
.Failure("Group link is invalid:");
755 final var result
= m
.joinGroup(linkUrl
);
756 return result
.first().serialize();
757 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
758 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
759 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
760 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
761 } catch (IOException e
) {
762 throw new Error
.Failure(e
.getMessage());
767 public boolean isContactBlocked(final String number
) {
768 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
772 public boolean isGroupBlocked(final byte[] groupId
) {
773 var group
= m
.getGroup(getGroupId(groupId
));
777 return group
.isBlocked();
782 public boolean isMember(final byte[] groupId
) {
783 var group
= m
.getGroup(getGroupId(groupId
));
787 return group
.isMember();
792 public String
uploadStickerPack(String stickerPackPath
) {
793 File path
= new File(stickerPackPath
);
795 return m
.uploadStickerPack(path
).toString();
796 } catch (IOException e
) {
797 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
798 } catch (StickerPackInvalidException e
) {
799 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
803 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
804 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
810 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
812 if (result
.isIdentityFailure()) {
813 throw new Error
.UntrustedIdentity(message
);
815 throw new Error
.Failure(message
);
819 private void checkSendMessageResults(final SendMessageResults results
) {
820 final var sendMessageResults
= results
.results().values().stream().findFirst();
821 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
822 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
826 if (results
.hasSuccess()) {
830 var message
= new StringBuilder();
831 message
.append("Failed to send messages:\n");
832 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
833 for (var error
: errors
) {
834 message
.append(error
).append('\n');
836 message
.append(results
.timestamp());
838 throw new Error
.Failure(message
.toString());
841 private static void checkGroupSendMessageResults(
842 long timestamp
, Collection
<SendMessageResult
> results
843 ) throws DBusExecutionException
{
844 if (results
.size() == 1) {
845 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
849 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
850 if (errors
.size() == 0 || errors
.size() < results
.size()) {
854 var message
= new StringBuilder();
855 message
.append("Failed to send message:\n");
856 for (var error
: errors
) {
857 message
.append(error
).append('\n');
859 message
.append(timestamp
);
861 throw new Error
.Failure(message
.toString());
864 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
865 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
868 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
869 final Collection
<String
> recipientStrings
, final String localNumber
870 ) throws DBusExecutionException
{
871 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
872 for (var recipientString
: recipientStrings
) {
873 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
878 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
879 final String recipientString
, final String localNumber
880 ) throws DBusExecutionException
{
882 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
883 } catch (InvalidNumberException e
) {
884 throw new Error
.InvalidNumber(e
.getMessage());
888 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
889 return new RecipientIdentifier
.Group(getGroupId(groupId
));
892 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
894 return GroupId
.unknownVersion(groupId
);
895 } catch (Throwable e
) {
896 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
900 private byte[] nullIfEmpty(final byte[] array
) {
901 return array
.length
== 0 ?
null : array
;
904 private String
nullIfEmpty(final String name
) {
905 return name
.isEmpty() ?
null : name
;
908 private String
emptyIfNull(final String string
) {
909 return string
== null ?
"" : string
;
912 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
913 return basePath
+ "/Devices/" + deviceId
;
916 private void updateDevices() {
917 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
919 linkedDevices
= m
.getLinkedDevices();
920 } catch (IOException e
) {
921 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
926 linkedDevices
.forEach(d
-> {
927 final var object
= new DbusSignalDeviceImpl(d
);
928 final var deviceObjectPath
= object
.getObjectPath();
929 exportObject(object
);
930 if (d
.isThisDevice()) {
931 thisDevice
= new DBusPath(deviceObjectPath
);
933 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
937 private void unExportDevices() {
938 this.devices
.stream()
939 .map(StructDevice
::getObjectPath
)
940 .map(DBusPath
::getPath
)
941 .forEach(connection
::unExportObject
);
942 this.devices
.clear();
945 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
946 return basePath
+ "/Groups/" + Base64
.getEncoder()
947 .encodeToString(groupId
)
953 private void updateGroups() {
954 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
955 groups
= m
.getGroups();
959 groups
.forEach(g
-> {
960 final var object
= new DbusSignalGroupImpl(g
.groupId());
961 exportObject(object
);
962 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
963 g
.groupId().serialize(),
964 emptyIfNull(g
.title())));
968 private void unExportGroups() {
969 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
973 private static String
getConfigurationObjectPath(String basePath
) {
974 return basePath
+ "/Configuration";
977 private void updateConfiguration() {
978 unExportConfiguration();
979 final var object
= new DbusSignalConfigurationImpl();
980 exportObject(object
);
983 private void unExportConfiguration() {
984 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
985 connection
.unExportObject(objectPath
);
988 private void exportObject(final DBusInterface object
) {
990 connection
.exportObject(object
);
991 logger
.debug("Exported dbus object: " + object
.getObjectPath());
992 } catch (DBusException e
) {
997 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
999 private final org
.asamk
.signal
.manager
.api
.Device device
;
1001 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1002 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1003 List
.of(new DbusProperty
<>("Id", device
::id
),
1004 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1005 new DbusProperty
<>("Created", device
::created
),
1006 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1007 this.device
= device
;
1011 public String
getObjectPath() {
1012 return getDeviceObjectPath(objectPath
, device
.id());
1016 public void removeDevice() throws Error
.Failure
{
1018 m
.removeLinkedDevices(device
.id());
1020 } catch (IOException e
) {
1021 throw new Error
.Failure(e
.getMessage());
1025 private void setDeviceName(String name
) {
1026 if (!device
.isThisDevice()) {
1027 throw new Error
.Failure("Only the name of this device can be changed");
1030 m
.updateAccountAttributes(name
);
1031 // update device list
1033 } catch (IOException e
) {
1034 throw new Error
.Failure(e
.getMessage());
1039 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1041 public DbusSignalConfigurationImpl(
1043 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1044 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1045 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1046 this::getUnidentifiedDeliveryIndicators
,
1047 this::setUnidentifiedDeliveryIndicators
),
1048 new DbusProperty
<>("TypingIndicators",
1049 this::getTypingIndicators
,
1050 this::setTypingIndicators
),
1051 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1056 public String
getObjectPath() {
1057 return getConfigurationObjectPath(objectPath
);
1060 public void setReadReceipts(Boolean readReceipts
) {
1061 setConfiguration(readReceipts
, null, null, null);
1064 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1065 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1068 public void setTypingIndicators(Boolean typingIndicators
) {
1069 setConfiguration(null, null, typingIndicators
, null);
1072 public void setLinkPreviews(Boolean linkPreviews
) {
1073 setConfiguration(null, null, null, linkPreviews
);
1076 private void setConfiguration(
1077 Boolean readReceipts
,
1078 Boolean unidentifiedDeliveryIndicators
,
1079 Boolean typingIndicators
,
1080 Boolean linkPreviews
1083 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1084 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1085 Optional
.ofNullable(typingIndicators
),
1086 Optional
.ofNullable(linkPreviews
)));
1087 } catch (IOException e
) {
1088 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1089 } catch (NotMasterDeviceException e
) {
1090 throw new Error
.Failure("This command doesn't work on linked devices.");
1094 private boolean getReadReceipts() {
1095 return m
.getConfiguration().readReceipts().orElse(false);
1098 private boolean getUnidentifiedDeliveryIndicators() {
1099 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1102 private boolean getTypingIndicators() {
1103 return m
.getConfiguration().typingIndicators().orElse(false);
1106 private boolean getLinkPreviews() {
1107 return m
.getConfiguration().linkPreviews().orElse(false);
1111 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1113 private final GroupId groupId
;
1115 public DbusSignalGroupImpl(final GroupId groupId
) {
1116 this.groupId
= groupId
;
1117 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1118 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1119 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1120 new DbusProperty
<>("Description",
1121 () -> emptyIfNull(getGroup().description()),
1122 this::setGroupDescription
),
1123 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1124 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1125 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1126 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1127 new DbusProperty
<>("MessageExpirationTimer",
1128 () -> getGroup().messageExpirationTimer(),
1129 this::setMessageExpirationTime
),
1130 new DbusProperty
<>("Members",
1131 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1132 new DbusProperty
<>("PendingMembers",
1133 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1134 new DbusProperty
<>("RequestingMembers",
1135 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1136 new DbusProperty
<>("Admins",
1137 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1138 new DbusProperty
<>("Banned",
1139 () -> new Variant
<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
1140 new DbusProperty
<>("PermissionAddMember",
1141 () -> getGroup().permissionAddMember().name(),
1142 this::setGroupPermissionAddMember
),
1143 new DbusProperty
<>("PermissionEditDetails",
1144 () -> getGroup().permissionEditDetails().name(),
1145 this::setGroupPermissionEditDetails
),
1146 new DbusProperty
<>("PermissionSendMessage",
1147 () -> getGroup().permissionSendMessage().name(),
1148 this::setGroupPermissionSendMessage
),
1149 new DbusProperty
<>("GroupInviteLink", () -> {
1150 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1151 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1156 public String
getObjectPath() {
1157 return getGroupObjectPath(objectPath
, groupId
.serialize());
1161 public void quitGroup() throws Error
.Failure
{
1163 m
.quitGroup(groupId
, Set
.of());
1164 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1165 throw new Error
.GroupNotFound(e
.getMessage());
1166 } catch (IOException e
) {
1167 throw new Error
.Failure(e
.getMessage());
1168 } catch (LastGroupAdminException e
) {
1169 throw new Error
.LastGroupAdmin(e
.getMessage());
1170 } catch (UnregisteredRecipientException e
) {
1171 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1176 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1178 m
.deleteGroup(groupId
);
1179 } catch (IOException e
) {
1180 throw new Error
.Failure(e
.getMessage());
1186 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1187 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1188 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1192 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1193 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1194 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1198 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1199 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1200 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1204 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1205 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1206 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1210 public void resetLink() throws Error
.Failure
{
1211 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1215 public void disableLink() throws Error
.Failure
{
1216 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1220 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1221 updateGroup(UpdateGroup
.newBuilder()
1222 .withGroupLinkState(requiresApproval
1223 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1224 : GroupLinkState
.ENABLED
)
1228 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1229 return m
.getGroup(groupId
);
1232 private void setGroupName(final String name
) {
1233 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1236 private void setGroupDescription(final String description
) {
1237 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1240 private void setGroupAvatar(final String avatar
) {
1241 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1244 private void setMessageExpirationTime(final int expirationTime
) {
1245 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1248 private void setGroupPermissionAddMember(final String permission
) {
1249 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1252 private void setGroupPermissionEditDetails(final String permission
) {
1253 updateGroup(UpdateGroup
.newBuilder()
1254 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1258 private void setGroupPermissionSendMessage(final String permission
) {
1259 updateGroup(UpdateGroup
.newBuilder()
1260 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1264 private void setIsBlocked(final boolean isBlocked
) {
1266 m
.setGroupsBlocked(List
.of(groupId
), isBlocked
);
1267 } catch (NotMasterDeviceException e
) {
1268 throw new Error
.Failure("This command doesn't work on linked devices.");
1269 } catch (GroupNotFoundException e
) {
1270 throw new Error
.GroupNotFound(e
.getMessage());
1271 } catch (IOException e
) {
1272 throw new Error
.Failure(e
.getMessage());
1276 private void updateGroup(final UpdateGroup updateGroup
) {
1278 m
.updateGroup(groupId
, updateGroup
);
1279 } catch (IOException e
) {
1280 throw new Error
.Failure(e
.getMessage());
1281 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1282 throw new Error
.GroupNotFound(e
.getMessage());
1283 } catch (AttachmentInvalidException e
) {
1284 throw new Error
.AttachmentInvalid(e
.getMessage());
1285 } catch (UnregisteredRecipientException e
) {
1286 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");