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
.NotPrimaryDeviceException
;
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
.UpdateProfile
;
21 import org
.asamk
.signal
.manager
.api
.UserStatus
;
22 import org
.asamk
.signal
.manager
.groups
.GroupId
;
23 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
24 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
25 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
26 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
27 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
28 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
29 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
30 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
31 import org
.asamk
.signal
.util
.SendMessageResultUtils
;
32 import org
.freedesktop
.dbus
.DBusPath
;
33 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
35 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
36 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
37 import org
.freedesktop
.dbus
.types
.Variant
;
38 import org
.slf4j
.Logger
;
39 import org
.slf4j
.LoggerFactory
;
42 import java
.io
.IOException
;
44 import java
.net
.URISyntaxException
;
45 import java
.util
.ArrayList
;
46 import java
.util
.Arrays
;
47 import java
.util
.Base64
;
48 import java
.util
.Collection
;
49 import java
.util
.HashSet
;
50 import java
.util
.List
;
52 import java
.util
.Objects
;
53 import java
.util
.Optional
;
55 import java
.util
.stream
.Collectors
;
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
;
80 m
.addAddressChangedListener(() -> {
86 public void initObjects() {
88 if (!noReceiveOnStart
) {
93 private void exportObjects() {
98 updateConfiguration();
101 public void close() {
102 if (dbusMessageHandler
!= null) {
103 m
.removeReceiveHandler(dbusMessageHandler
);
104 dbusMessageHandler
= null;
109 private void unExportObjects() {
112 unExportConfiguration();
113 connection
.unExportObject(this.objectPath
);
117 public String
getObjectPath() {
122 public String
getSelfNumber() {
123 return m
.getSelfNumber();
127 public void subscribeReceive() {
128 if (dbusMessageHandler
== null) {
129 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
130 m
.addReceiveHandler(dbusMessageHandler
);
136 public void unsubscribeReceive() {
137 subscriberCount
= Math
.max(0, subscriberCount
- 1);
138 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
139 m
.removeReceiveHandler(dbusMessageHandler
);
140 dbusMessageHandler
= null;
145 public void submitRateLimitChallenge(String challenge
, String captcha
) {
147 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
148 } catch (IOException e
) {
149 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
155 public void unregister() throws Error
.Failure
{
158 } catch (IOException e
) {
159 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
164 public void deleteAccount() throws Error
.Failure
{
167 } catch (IOException e
) {
168 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
173 public void addDevice(String uri
) {
175 m
.addDeviceLink(new URI(uri
));
176 } catch (IOException
| InvalidDeviceLinkException e
) {
177 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
178 } catch (URISyntaxException e
) {
179 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
180 + " Device link uri has invalid format: "
186 public DBusPath
getDevice(long deviceId
) {
188 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
189 if (deviceOptional
.isEmpty()) {
190 throw new Error
.DeviceNotFound("Device not found");
192 return deviceOptional
.get().getObjectPath();
196 public List
<StructDevice
> listDevices() {
202 public DBusPath
getThisDevice() {
208 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
209 return sendMessage(message
, attachments
, List
.of(recipient
));
213 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
215 final var results
= m
.sendMessage(new Message(message
,
220 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
221 .map(RecipientIdentifier
.class::cast
)
222 .collect(Collectors
.toSet()));
224 checkSendMessageResults(results
);
225 return results
.timestamp();
226 } catch (AttachmentInvalidException e
) {
227 throw new Error
.AttachmentInvalid(e
.getMessage());
228 } catch (IOException
| InvalidStickerException e
) {
229 throw new Error
.Failure(e
);
230 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
231 throw new Error
.GroupNotFound(e
.getMessage());
232 } catch (UnregisteredRecipientException e
) {
233 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
238 public long sendRemoteDeleteMessage(
239 final long targetSentTimestamp
, final String recipient
241 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
245 public long sendRemoteDeleteMessage(
246 final long targetSentTimestamp
, final List
<String
> recipients
249 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
250 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
251 .map(RecipientIdentifier
.class::cast
)
252 .collect(Collectors
.toSet()));
253 checkSendMessageResults(results
);
254 return results
.timestamp();
255 } catch (IOException e
) {
256 throw new Error
.Failure(e
.getMessage());
257 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
258 throw new Error
.GroupNotFound(e
.getMessage());
263 public long sendMessageReaction(
265 final boolean remove
,
266 final String targetAuthor
,
267 final long targetSentTimestamp
,
268 final String recipient
270 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
274 public long sendMessageReaction(
276 final boolean remove
,
277 final String targetAuthor
,
278 final long targetSentTimestamp
,
279 final List
<String
> recipients
282 final var results
= m
.sendMessageReaction(emoji
,
284 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
286 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
287 .map(RecipientIdentifier
.class::cast
)
288 .collect(Collectors
.toSet()));
289 checkSendMessageResults(results
);
290 return results
.timestamp();
291 } catch (IOException e
) {
292 throw new Error
.Failure(e
.getMessage());
293 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
294 throw new Error
.GroupNotFound(e
.getMessage());
295 } catch (UnregisteredRecipientException e
) {
296 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
301 public void sendTyping(
302 final String recipient
, final boolean stop
303 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
305 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
306 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
307 .map(RecipientIdentifier
.class::cast
)
308 .collect(Collectors
.toSet()));
309 checkSendMessageResults(results
);
310 } catch (IOException e
) {
311 throw new Error
.Failure(e
.getMessage());
312 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
313 throw new Error
.GroupNotFound(e
.getMessage());
318 public void sendReadReceipt(
319 final String recipient
, final List
<Long
> messageIds
320 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
322 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
324 checkSendMessageResults(results
);
325 } catch (IOException e
) {
326 throw new Error
.Failure(e
.getMessage());
331 public void sendViewedReceipt(
332 final String recipient
, final List
<Long
> messageIds
333 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
335 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
337 checkSendMessageResults(results
);
338 } catch (IOException e
) {
339 throw new Error
.Failure(e
.getMessage());
344 public void sendContacts() {
347 } catch (IOException e
) {
348 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
353 public void sendSyncRequest() {
355 m
.requestAllSyncData();
356 } catch (IOException e
) {
357 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
362 public long sendNoteToSelfMessage(
363 final String message
, final List
<String
> attachments
364 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
366 final var results
= m
.sendMessage(new Message(message
,
370 Optional
.empty()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
371 checkSendMessageResults(results
);
372 return results
.timestamp();
373 } catch (AttachmentInvalidException e
) {
374 throw new Error
.AttachmentInvalid(e
.getMessage());
375 } catch (IOException
| InvalidStickerException e
) {
376 throw new Error
.Failure(e
.getMessage());
377 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
378 throw new Error
.GroupNotFound(e
.getMessage());
379 } catch (UnregisteredRecipientException e
) {
380 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
385 public void sendEndSessionMessage(final List
<String
> recipients
) {
387 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
388 checkSendMessageResults(results
);
389 } catch (IOException e
) {
390 throw new Error
.Failure(e
.getMessage());
395 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
396 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
400 public void deleteContact(final String recipient
) throws Error
.Failure
{
401 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
405 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
407 var results
= m
.sendMessage(new Message(message
,
411 Optional
.empty()), Set
.of(getGroupRecipientIdentifier(groupId
)));
412 checkSendMessageResults(results
);
413 return results
.timestamp();
414 } catch (IOException
| InvalidStickerException e
) {
415 throw new Error
.Failure(e
.getMessage());
416 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
417 throw new Error
.GroupNotFound(e
.getMessage());
418 } catch (AttachmentInvalidException e
) {
419 throw new Error
.AttachmentInvalid(e
.getMessage());
420 } catch (UnregisteredRecipientException e
) {
421 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
426 public void sendGroupTyping(
427 final byte[] groupId
, final boolean stop
428 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
430 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
431 Set
.of(getGroupRecipientIdentifier(groupId
)));
432 checkSendMessageResults(results
);
433 } catch (IOException e
) {
434 throw new Error
.Failure(e
.getMessage());
435 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
436 throw new Error
.GroupNotFound(e
.getMessage());
441 public long sendGroupRemoteDeleteMessage(
442 final long targetSentTimestamp
, final byte[] groupId
445 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
446 Set
.of(getGroupRecipientIdentifier(groupId
)));
447 checkSendMessageResults(results
);
448 return results
.timestamp();
449 } catch (IOException e
) {
450 throw new Error
.Failure(e
.getMessage());
451 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
452 throw new Error
.GroupNotFound(e
.getMessage());
457 public long sendGroupMessageReaction(
459 final boolean remove
,
460 final String targetAuthor
,
461 final long targetSentTimestamp
,
465 final var results
= m
.sendMessageReaction(emoji
,
467 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
469 Set
.of(getGroupRecipientIdentifier(groupId
)));
470 checkSendMessageResults(results
);
471 return results
.timestamp();
472 } catch (IOException e
) {
473 throw new Error
.Failure(e
.getMessage());
474 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
475 throw new Error
.GroupNotFound(e
.getMessage());
476 } catch (UnregisteredRecipientException e
) {
477 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
481 // Since contact names might be empty if not defined, also potentially return
484 public String
getContactName(final String number
) {
485 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
486 return name
== null ?
"" : name
;
490 public void setContactName(final String number
, final String name
) {
492 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
493 } catch (NotPrimaryDeviceException e
) {
494 throw new Error
.Failure("This command doesn't work on linked devices.");
495 } catch (IOException e
) {
496 throw new Error
.Failure("Contact is not registered.");
497 } catch (UnregisteredRecipientException e
) {
498 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
503 public void setExpirationTimer(final String number
, final int expiration
) {
505 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
506 } catch (IOException e
) {
507 throw new Error
.Failure(e
.getMessage());
508 } catch (UnregisteredRecipientException e
) {
509 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
514 public void setContactBlocked(final String number
, final boolean blocked
) {
516 m
.setContactsBlocked(List
.of(getSingleRecipientIdentifier(number
, m
.getSelfNumber())), blocked
);
517 } catch (NotPrimaryDeviceException e
) {
518 throw new Error
.Failure("This command doesn't work on linked devices.");
519 } catch (IOException e
) {
520 throw new Error
.Failure(e
.getMessage());
521 } catch (UnregisteredRecipientException e
) {
522 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
527 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
529 m
.setGroupsBlocked(List
.of(getGroupId(groupId
)), blocked
);
530 } catch (NotPrimaryDeviceException e
) {
531 throw new Error
.Failure("This command doesn't work on linked devices.");
532 } catch (GroupNotFoundException e
) {
533 throw new Error
.GroupNotFound(e
.getMessage());
534 } catch (IOException e
) {
535 throw new Error
.Failure(e
.getMessage());
540 public List
<byte[]> getGroupIds() {
541 var groups
= m
.getGroups();
542 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
546 public DBusPath
getGroup(final byte[] groupId
) {
548 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
549 if (groupOptional
.isEmpty()) {
550 throw new Error
.GroupNotFound("Group not found");
552 return groupOptional
.get().getObjectPath();
556 public List
<StructGroup
> listGroups() {
562 public String
getGroupName(final byte[] groupId
) {
563 var group
= m
.getGroup(getGroupId(groupId
));
564 if (group
== null || group
.title() == null) {
567 return group
.title();
572 public List
<String
> getGroupMembers(final byte[] groupId
) {
573 var group
= m
.getGroup(getGroupId(groupId
));
577 final var members
= group
.members();
578 return getRecipientStrings(members
);
583 public byte[] createGroup(
584 final String name
, final List
<String
> members
, final String avatar
585 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
586 return updateGroup(new byte[0], name
, members
, avatar
);
590 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
592 groupId
= nullIfEmpty(groupId
);
593 name
= nullIfEmpty(name
);
594 avatar
= nullIfEmpty(avatar
);
595 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
596 if (groupId
== null) {
597 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
599 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
600 return results
.first().serialize();
602 final var results
= m
.updateGroup(getGroupId(groupId
),
603 UpdateGroup
.newBuilder()
605 .withMembers(memberIdentifiers
)
606 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
608 if (results
!= null) {
609 checkGroupSendMessageResults(results
.timestamp(), results
.results());
613 } catch (IOException e
) {
614 throw new Error
.Failure(e
.getMessage());
615 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
616 throw new Error
.GroupNotFound(e
.getMessage());
617 } catch (AttachmentInvalidException e
) {
618 throw new Error
.AttachmentInvalid(e
.getMessage());
619 } catch (UnregisteredRecipientException e
) {
620 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
625 public boolean isRegistered() {
630 public boolean isRegistered(String number
) {
631 var result
= isRegistered(List
.of(number
));
632 return result
.get(0);
636 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
637 if (numbers
.isEmpty()) {
641 Map
<String
, UserStatus
> registered
;
643 registered
= m
.getUserStatus(new HashSet
<>(numbers
));
644 } catch (IOException e
) {
645 throw new Error
.Failure(e
.getMessage());
648 return numbers
.stream().map(number
-> registered
.get(number
).uuid() != null).toList();
652 public void updateProfile(
658 final boolean removeAvatar
661 givenName
= nullIfEmpty(givenName
);
662 familyName
= nullIfEmpty(familyName
);
663 about
= nullIfEmpty(about
);
664 aboutEmoji
= nullIfEmpty(aboutEmoji
);
665 avatarPath
= nullIfEmpty(avatarPath
);
666 File avatarFile
= removeAvatar
|| avatarPath
== null ?
null : new File(avatarPath
);
667 m
.updateProfile(UpdateProfile
.newBuilder()
668 .withGivenName(givenName
)
669 .withFamilyName(familyName
)
671 .withAboutEmoji(aboutEmoji
)
672 .withAvatar(avatarFile
)
673 .withDeleteAvatar(removeAvatar
)
675 } catch (IOException e
) {
676 throw new Error
.Failure(e
.getMessage());
681 public void updateProfile(
684 final String aboutEmoji
,
686 final boolean removeAvatar
688 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
692 public void removePin() {
694 m
.setRegistrationLockPin(Optional
.empty());
695 } catch (IOException e
) {
696 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
697 } catch (NotPrimaryDeviceException e
) {
698 throw new Error
.Failure("This command doesn't work on linked devices.");
703 public void setPin(String registrationLockPin
) {
705 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
706 } catch (IOException e
) {
707 throw new Error
.Failure("Set pin error: " + e
.getMessage());
708 } catch (NotPrimaryDeviceException e
) {
709 throw new Error
.Failure("This command doesn't work on linked devices.");
713 // Provide option to query a version string in order to react on potential
714 // future interface changes
716 public String
version() {
717 return BaseConfig
.PROJECT_VERSION
;
720 // Create a unique list of Numbers from Identities and Contacts to really get
721 // all numbers the system knows
723 public List
<String
> listNumbers() {
724 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.empty())
726 .map(r
-> r
.getAddress().number().orElse(null))
727 .filter(Objects
::nonNull
)
733 public List
<String
> getContactNumber(final String name
) {
734 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.of(name
))
736 .map(r
-> r
.getAddress().getLegacyIdentifier())
741 public void quitGroup(final byte[] groupId
) {
742 var group
= getGroupId(groupId
);
744 m
.quitGroup(group
, Set
.of());
745 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
746 throw new Error
.GroupNotFound(e
.getMessage());
747 } catch (IOException
| LastGroupAdminException e
) {
748 throw new Error
.Failure(e
.getMessage());
749 } catch (UnregisteredRecipientException e
) {
750 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
755 public byte[] joinGroup(final String groupLink
) {
757 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
758 if (linkUrl
== null) {
759 throw new Error
.Failure("Group link is invalid:");
761 final var result
= m
.joinGroup(linkUrl
);
762 return result
.first().serialize();
763 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
764 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
765 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
766 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
767 } catch (IOException e
) {
768 throw new Error
.Failure(e
.getMessage());
773 public boolean isContactBlocked(final String number
) {
774 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
778 public boolean isGroupBlocked(final byte[] groupId
) {
779 var group
= m
.getGroup(getGroupId(groupId
));
783 return group
.isBlocked();
788 public boolean isMember(final byte[] groupId
) {
789 var group
= m
.getGroup(getGroupId(groupId
));
793 return group
.isMember();
798 public String
uploadStickerPack(String stickerPackPath
) {
799 File path
= new File(stickerPackPath
);
801 return m
.uploadStickerPack(path
).toString();
802 } catch (IOException e
) {
803 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
804 } catch (StickerPackInvalidException e
) {
805 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
809 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
810 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
816 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
818 if (result
.isIdentityFailure()) {
819 throw new Error
.UntrustedIdentity(message
);
821 throw new Error
.Failure(message
);
825 private void checkSendMessageResults(final SendMessageResults results
) {
826 final var sendMessageResults
= results
.results().values().stream().findFirst();
827 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
828 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
832 if (results
.hasSuccess()) {
836 var message
= new StringBuilder();
837 message
.append("Failed to send messages:\n");
838 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
839 for (var error
: errors
) {
840 message
.append(error
).append('\n');
842 message
.append(results
.timestamp());
844 throw new Error
.Failure(message
.toString());
847 private static void checkGroupSendMessageResults(
848 long timestamp
, Collection
<SendMessageResult
> results
849 ) throws DBusExecutionException
{
850 if (results
.size() == 1) {
851 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
855 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
856 if (errors
.size() == 0 || errors
.size() < results
.size()) {
860 var message
= new StringBuilder();
861 message
.append("Failed to send message:\n");
862 for (var error
: errors
) {
863 message
.append(error
).append('\n');
865 message
.append(timestamp
);
867 throw new Error
.Failure(message
.toString());
870 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
871 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
874 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
875 final Collection
<String
> recipientStrings
, final String localNumber
876 ) throws DBusExecutionException
{
877 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
878 for (var recipientString
: recipientStrings
) {
879 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
884 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
885 final String recipientString
, final String localNumber
886 ) throws DBusExecutionException
{
888 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
889 } catch (InvalidNumberException e
) {
890 throw new Error
.InvalidNumber(e
.getMessage());
894 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
895 return new RecipientIdentifier
.Group(getGroupId(groupId
));
898 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
900 return GroupId
.unknownVersion(groupId
);
901 } catch (Throwable e
) {
902 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
906 private byte[] nullIfEmpty(final byte[] array
) {
907 return array
.length
== 0 ?
null : array
;
910 private String
nullIfEmpty(final String name
) {
911 return name
.isEmpty() ?
null : name
;
914 private String
emptyIfNull(final String string
) {
915 return string
== null ?
"" : string
;
918 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
919 return basePath
+ "/Devices/" + deviceId
;
922 private void updateDevices() {
923 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
925 linkedDevices
= m
.getLinkedDevices();
926 } catch (IOException e
) {
927 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
932 linkedDevices
.forEach(d
-> {
933 final var object
= new DbusSignalDeviceImpl(d
);
934 final var deviceObjectPath
= object
.getObjectPath();
935 exportObject(object
);
936 if (d
.isThisDevice()) {
937 thisDevice
= new DBusPath(deviceObjectPath
);
939 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
943 private void unExportDevices() {
944 this.devices
.stream()
945 .map(StructDevice
::getObjectPath
)
946 .map(DBusPath
::getPath
)
947 .forEach(connection
::unExportObject
);
948 this.devices
.clear();
951 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
952 return basePath
+ "/Groups/" + Base64
.getEncoder()
953 .encodeToString(groupId
)
959 private void updateGroups() {
960 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
961 groups
= m
.getGroups();
965 groups
.forEach(g
-> {
966 final var object
= new DbusSignalGroupImpl(g
.groupId());
967 exportObject(object
);
968 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
969 g
.groupId().serialize(),
970 emptyIfNull(g
.title())));
974 private void unExportGroups() {
975 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
979 private static String
getConfigurationObjectPath(String basePath
) {
980 return basePath
+ "/Configuration";
983 private void updateConfiguration() {
984 unExportConfiguration();
985 final var object
= new DbusSignalConfigurationImpl();
986 exportObject(object
);
989 private void unExportConfiguration() {
990 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
991 connection
.unExportObject(objectPath
);
994 private void exportObject(final DBusInterface object
) {
996 connection
.exportObject(object
);
997 logger
.debug("Exported dbus object: " + object
.getObjectPath());
998 } catch (DBusException e
) {
1003 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
1005 private final org
.asamk
.signal
.manager
.api
.Device device
;
1007 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1008 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1009 List
.of(new DbusProperty
<>("Id", device
::id
),
1010 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1011 new DbusProperty
<>("Created", device
::created
),
1012 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1013 this.device
= device
;
1017 public String
getObjectPath() {
1018 return getDeviceObjectPath(objectPath
, device
.id());
1022 public void removeDevice() throws Error
.Failure
{
1024 m
.removeLinkedDevices(device
.id());
1026 } catch (IOException e
) {
1027 throw new Error
.Failure(e
.getMessage());
1031 private void setDeviceName(String name
) {
1032 if (!device
.isThisDevice()) {
1033 throw new Error
.Failure("Only the name of this device can be changed");
1036 m
.updateAccountAttributes(name
);
1037 // update device list
1039 } catch (IOException e
) {
1040 throw new Error
.Failure(e
.getMessage());
1045 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1047 public DbusSignalConfigurationImpl(
1049 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1050 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1051 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1052 this::getUnidentifiedDeliveryIndicators
,
1053 this::setUnidentifiedDeliveryIndicators
),
1054 new DbusProperty
<>("TypingIndicators",
1055 this::getTypingIndicators
,
1056 this::setTypingIndicators
),
1057 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1062 public String
getObjectPath() {
1063 return getConfigurationObjectPath(objectPath
);
1066 public void setReadReceipts(Boolean readReceipts
) {
1067 setConfiguration(readReceipts
, null, null, null);
1070 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1071 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1074 public void setTypingIndicators(Boolean typingIndicators
) {
1075 setConfiguration(null, null, typingIndicators
, null);
1078 public void setLinkPreviews(Boolean linkPreviews
) {
1079 setConfiguration(null, null, null, linkPreviews
);
1082 private void setConfiguration(
1083 Boolean readReceipts
,
1084 Boolean unidentifiedDeliveryIndicators
,
1085 Boolean typingIndicators
,
1086 Boolean linkPreviews
1089 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1090 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1091 Optional
.ofNullable(typingIndicators
),
1092 Optional
.ofNullable(linkPreviews
)));
1093 } catch (IOException e
) {
1094 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1095 } catch (NotPrimaryDeviceException e
) {
1096 throw new Error
.Failure("This command doesn't work on linked devices.");
1100 private boolean getReadReceipts() {
1101 return m
.getConfiguration().readReceipts().orElse(false);
1104 private boolean getUnidentifiedDeliveryIndicators() {
1105 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1108 private boolean getTypingIndicators() {
1109 return m
.getConfiguration().typingIndicators().orElse(false);
1112 private boolean getLinkPreviews() {
1113 return m
.getConfiguration().linkPreviews().orElse(false);
1117 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1119 private final GroupId groupId
;
1121 public DbusSignalGroupImpl(final GroupId groupId
) {
1122 this.groupId
= groupId
;
1123 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1124 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1125 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1126 new DbusProperty
<>("Description",
1127 () -> emptyIfNull(getGroup().description()),
1128 this::setGroupDescription
),
1129 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1130 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1131 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1132 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1133 new DbusProperty
<>("MessageExpirationTimer",
1134 () -> getGroup().messageExpirationTimer(),
1135 this::setMessageExpirationTime
),
1136 new DbusProperty
<>("Members",
1137 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1138 new DbusProperty
<>("PendingMembers",
1139 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1140 new DbusProperty
<>("RequestingMembers",
1141 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1142 new DbusProperty
<>("Admins",
1143 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1144 new DbusProperty
<>("Banned",
1145 () -> new Variant
<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
1146 new DbusProperty
<>("PermissionAddMember",
1147 () -> getGroup().permissionAddMember().name(),
1148 this::setGroupPermissionAddMember
),
1149 new DbusProperty
<>("PermissionEditDetails",
1150 () -> getGroup().permissionEditDetails().name(),
1151 this::setGroupPermissionEditDetails
),
1152 new DbusProperty
<>("PermissionSendMessage",
1153 () -> getGroup().permissionSendMessage().name(),
1154 this::setGroupPermissionSendMessage
),
1155 new DbusProperty
<>("GroupInviteLink", () -> {
1156 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1157 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1162 public String
getObjectPath() {
1163 return getGroupObjectPath(objectPath
, groupId
.serialize());
1167 public void quitGroup() throws Error
.Failure
{
1169 m
.quitGroup(groupId
, Set
.of());
1170 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1171 throw new Error
.GroupNotFound(e
.getMessage());
1172 } catch (IOException e
) {
1173 throw new Error
.Failure(e
.getMessage());
1174 } catch (LastGroupAdminException e
) {
1175 throw new Error
.LastGroupAdmin(e
.getMessage());
1176 } catch (UnregisteredRecipientException e
) {
1177 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1182 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1184 m
.deleteGroup(groupId
);
1185 } catch (IOException e
) {
1186 throw new Error
.Failure(e
.getMessage());
1192 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1193 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1194 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1198 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1199 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1200 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1204 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1205 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1206 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1210 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1211 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1212 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1216 public void resetLink() throws Error
.Failure
{
1217 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1221 public void disableLink() throws Error
.Failure
{
1222 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1226 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1227 updateGroup(UpdateGroup
.newBuilder()
1228 .withGroupLinkState(requiresApproval
1229 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1230 : GroupLinkState
.ENABLED
)
1234 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1235 return m
.getGroup(groupId
);
1238 private void setGroupName(final String name
) {
1239 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1242 private void setGroupDescription(final String description
) {
1243 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1246 private void setGroupAvatar(final String avatar
) {
1247 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1250 private void setMessageExpirationTime(final int expirationTime
) {
1251 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1254 private void setGroupPermissionAddMember(final String permission
) {
1255 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1258 private void setGroupPermissionEditDetails(final String permission
) {
1259 updateGroup(UpdateGroup
.newBuilder()
1260 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1264 private void setGroupPermissionSendMessage(final String permission
) {
1265 updateGroup(UpdateGroup
.newBuilder()
1266 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1270 private void setIsBlocked(final boolean isBlocked
) {
1272 m
.setGroupsBlocked(List
.of(groupId
), isBlocked
);
1273 } catch (NotPrimaryDeviceException e
) {
1274 throw new Error
.Failure("This command doesn't work on linked devices.");
1275 } catch (GroupNotFoundException e
) {
1276 throw new Error
.GroupNotFound(e
.getMessage());
1277 } catch (IOException e
) {
1278 throw new Error
.Failure(e
.getMessage());
1282 private void updateGroup(final UpdateGroup updateGroup
) {
1284 m
.updateGroup(groupId
, updateGroup
);
1285 } catch (IOException e
) {
1286 throw new Error
.Failure(e
.getMessage());
1287 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1288 throw new Error
.GroupNotFound(e
.getMessage());
1289 } catch (AttachmentInvalidException e
) {
1290 throw new Error
.AttachmentInvalid(e
.getMessage());
1291 } catch (UnregisteredRecipientException e
) {
1292 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");