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
.PendingAdminApprovalException
;
14 import org
.asamk
.signal
.manager
.api
.RecipientAddress
;
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
.StickerPackInvalidException
;
19 import org
.asamk
.signal
.manager
.api
.TypingAction
;
20 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
21 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
22 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
23 import org
.asamk
.signal
.manager
.api
.UserStatus
;
24 import org
.asamk
.signal
.manager
.groups
.GroupId
;
25 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
26 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
27 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
28 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
29 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
30 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
31 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
32 import org
.asamk
.signal
.util
.SendMessageResultUtils
;
33 import org
.freedesktop
.dbus
.DBusPath
;
34 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
35 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
36 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
37 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
38 import org
.freedesktop
.dbus
.types
.Variant
;
39 import org
.slf4j
.Logger
;
40 import org
.slf4j
.LoggerFactory
;
43 import java
.io
.IOException
;
45 import java
.net
.URISyntaxException
;
46 import java
.util
.ArrayList
;
47 import java
.util
.Arrays
;
48 import java
.util
.Base64
;
49 import java
.util
.Collection
;
50 import java
.util
.HashSet
;
51 import java
.util
.List
;
53 import java
.util
.Objects
;
54 import java
.util
.Optional
;
56 import java
.util
.stream
.Collectors
;
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
;
81 m
.addAddressChangedListener(() -> {
87 public void initObjects() {
89 if (!noReceiveOnStart
) {
94 private void exportObjects() {
99 updateConfiguration();
102 public void close() {
103 if (dbusMessageHandler
!= null) {
104 m
.removeReceiveHandler(dbusMessageHandler
);
105 dbusMessageHandler
= null;
110 private void unExportObjects() {
113 unExportConfiguration();
114 connection
.unExportObject(this.objectPath
);
118 public String
getObjectPath() {
123 public String
getSelfNumber() {
124 return m
.getSelfNumber();
128 public void subscribeReceive() {
129 if (dbusMessageHandler
== null) {
130 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
131 m
.addReceiveHandler(dbusMessageHandler
);
137 public void unsubscribeReceive() {
138 subscriberCount
= Math
.max(0, subscriberCount
- 1);
139 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
140 m
.removeReceiveHandler(dbusMessageHandler
);
141 dbusMessageHandler
= null;
146 public void submitRateLimitChallenge(String challenge
, String captcha
) {
148 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
149 } catch (IOException e
) {
150 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
156 public void unregister() throws Error
.Failure
{
159 } catch (IOException e
) {
160 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
165 public void deleteAccount() throws Error
.Failure
{
168 } catch (IOException e
) {
169 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
174 public void addDevice(String uri
) {
176 m
.addDeviceLink(new URI(uri
));
177 } catch (IOException
| InvalidDeviceLinkException e
) {
178 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
179 } catch (URISyntaxException e
) {
180 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
181 + " Device link uri has invalid format: "
187 public DBusPath
getDevice(long deviceId
) {
189 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
190 if (deviceOptional
.isEmpty()) {
191 throw new Error
.DeviceNotFound("Device not found");
193 return deviceOptional
.get().getObjectPath();
197 public List
<StructDevice
> listDevices() {
203 public DBusPath
getThisDevice() {
209 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
210 return sendMessage(message
, attachments
, List
.of(recipient
));
214 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
216 final var results
= m
.sendMessage(new Message(message
,
222 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
223 .map(RecipientIdentifier
.class::cast
)
224 .collect(Collectors
.toSet()));
226 checkSendMessageResults(results
);
227 return results
.timestamp();
228 } catch (AttachmentInvalidException e
) {
229 throw new Error
.AttachmentInvalid(e
.getMessage());
230 } catch (IOException
| InvalidStickerException e
) {
231 throw new Error
.Failure(e
);
232 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
233 throw new Error
.GroupNotFound(e
.getMessage());
234 } catch (UnregisteredRecipientException e
) {
235 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
240 public long sendRemoteDeleteMessage(
241 final long targetSentTimestamp
, final String recipient
243 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
247 public long sendRemoteDeleteMessage(
248 final long targetSentTimestamp
, final List
<String
> recipients
251 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
252 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
253 .map(RecipientIdentifier
.class::cast
)
254 .collect(Collectors
.toSet()));
255 checkSendMessageResults(results
);
256 return results
.timestamp();
257 } catch (IOException e
) {
258 throw new Error
.Failure(e
.getMessage());
259 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
260 throw new Error
.GroupNotFound(e
.getMessage());
265 public long sendMessageReaction(
267 final boolean remove
,
268 final String targetAuthor
,
269 final long targetSentTimestamp
,
270 final String recipient
272 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
276 public long sendMessageReaction(
278 final boolean remove
,
279 final String targetAuthor
,
280 final long targetSentTimestamp
,
281 final List
<String
> recipients
284 final var results
= m
.sendMessageReaction(emoji
,
286 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
288 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
289 .map(RecipientIdentifier
.class::cast
)
290 .collect(Collectors
.toSet()),
292 checkSendMessageResults(results
);
293 return results
.timestamp();
294 } catch (IOException e
) {
295 throw new Error
.Failure(e
.getMessage());
296 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
297 throw new Error
.GroupNotFound(e
.getMessage());
298 } catch (UnregisteredRecipientException e
) {
299 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
304 public long sendPaymentNotification(
305 final byte[] receipt
, final String note
, final String recipient
306 ) throws Error
.Failure
{
308 final var results
= m
.sendPaymentNotificationMessage(receipt
,
310 getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
311 checkSendMessageResults(results
);
312 return results
.timestamp();
313 } catch (IOException e
) {
314 throw new Error
.Failure(e
.getMessage());
319 public void sendTyping(
320 final String recipient
, final boolean stop
321 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
323 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
324 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
325 .map(RecipientIdentifier
.class::cast
)
326 .collect(Collectors
.toSet()));
327 checkSendMessageResults(results
);
328 } catch (IOException e
) {
329 throw new Error
.Failure(e
.getMessage());
330 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
331 throw new Error
.GroupNotFound(e
.getMessage());
336 public void sendReadReceipt(
337 final String recipient
, final List
<Long
> messageIds
338 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
340 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
342 checkSendMessageResults(results
);
343 } catch (IOException e
) {
344 throw new Error
.Failure(e
.getMessage());
349 public void sendViewedReceipt(
350 final String recipient
, final List
<Long
> messageIds
351 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
353 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
355 checkSendMessageResults(results
);
356 } catch (IOException e
) {
357 throw new Error
.Failure(e
.getMessage());
362 public void sendContacts() {
365 } catch (IOException e
) {
366 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
371 public void sendSyncRequest() {
373 m
.requestAllSyncData();
374 } catch (IOException e
) {
375 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
380 public long sendNoteToSelfMessage(
381 final String message
, final List
<String
> attachments
382 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
384 final var results
= m
.sendMessage(new Message(message
,
389 List
.of()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
390 checkSendMessageResults(results
);
391 return results
.timestamp();
392 } catch (AttachmentInvalidException e
) {
393 throw new Error
.AttachmentInvalid(e
.getMessage());
394 } catch (IOException
| InvalidStickerException e
) {
395 throw new Error
.Failure(e
.getMessage());
396 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
397 throw new Error
.GroupNotFound(e
.getMessage());
398 } catch (UnregisteredRecipientException e
) {
399 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
404 public void sendEndSessionMessage(final List
<String
> recipients
) {
406 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
407 checkSendMessageResults(results
);
408 } catch (IOException e
) {
409 throw new Error
.Failure(e
.getMessage());
414 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
415 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
419 public void deleteContact(final String recipient
) throws Error
.Failure
{
420 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
424 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
426 var results
= m
.sendMessage(new Message(message
,
431 List
.of()), Set
.of(getGroupRecipientIdentifier(groupId
)));
432 checkSendMessageResults(results
);
433 return results
.timestamp();
434 } catch (IOException
| InvalidStickerException e
) {
435 throw new Error
.Failure(e
.getMessage());
436 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
437 throw new Error
.GroupNotFound(e
.getMessage());
438 } catch (AttachmentInvalidException e
) {
439 throw new Error
.AttachmentInvalid(e
.getMessage());
440 } catch (UnregisteredRecipientException e
) {
441 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
446 public void sendGroupTyping(
447 final byte[] groupId
, final boolean stop
448 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
450 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
451 Set
.of(getGroupRecipientIdentifier(groupId
)));
452 checkSendMessageResults(results
);
453 } catch (IOException e
) {
454 throw new Error
.Failure(e
.getMessage());
455 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
456 throw new Error
.GroupNotFound(e
.getMessage());
461 public long sendGroupRemoteDeleteMessage(
462 final long targetSentTimestamp
, final byte[] groupId
465 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
466 Set
.of(getGroupRecipientIdentifier(groupId
)));
467 checkSendMessageResults(results
);
468 return results
.timestamp();
469 } catch (IOException e
) {
470 throw new Error
.Failure(e
.getMessage());
471 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
472 throw new Error
.GroupNotFound(e
.getMessage());
477 public long sendGroupMessageReaction(
479 final boolean remove
,
480 final String targetAuthor
,
481 final long targetSentTimestamp
,
485 final var results
= m
.sendMessageReaction(emoji
,
487 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
489 Set
.of(getGroupRecipientIdentifier(groupId
)),
491 checkSendMessageResults(results
);
492 return results
.timestamp();
493 } catch (IOException e
) {
494 throw new Error
.Failure(e
.getMessage());
495 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
496 throw new Error
.GroupNotFound(e
.getMessage());
497 } catch (UnregisteredRecipientException e
) {
498 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
502 // Since contact names might be empty if not defined, also potentially return
505 public String
getContactName(final String number
) {
506 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
507 return name
== null ?
"" : name
;
511 public void setContactName(final String number
, final String name
) {
513 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
, "");
514 } catch (NotPrimaryDeviceException e
) {
515 throw new Error
.Failure("This command doesn't work on linked devices.");
516 } catch (IOException e
) {
517 throw new Error
.Failure("Contact is not registered.");
518 } catch (UnregisteredRecipientException e
) {
519 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
524 public void setExpirationTimer(final String number
, final int expiration
) {
526 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
527 } catch (IOException e
) {
528 throw new Error
.Failure(e
.getMessage());
529 } catch (UnregisteredRecipientException e
) {
530 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
535 public void setContactBlocked(final String number
, final boolean blocked
) {
537 m
.setContactsBlocked(List
.of(getSingleRecipientIdentifier(number
, m
.getSelfNumber())), blocked
);
538 } catch (NotPrimaryDeviceException e
) {
539 throw new Error
.Failure("This command doesn't work on linked devices.");
540 } catch (IOException e
) {
541 throw new Error
.Failure(e
.getMessage());
542 } catch (UnregisteredRecipientException e
) {
543 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
548 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
550 m
.setGroupsBlocked(List
.of(getGroupId(groupId
)), blocked
);
551 } catch (NotPrimaryDeviceException e
) {
552 throw new Error
.Failure("This command doesn't work on linked devices.");
553 } catch (GroupNotFoundException e
) {
554 throw new Error
.GroupNotFound(e
.getMessage());
555 } catch (IOException e
) {
556 throw new Error
.Failure(e
.getMessage());
561 public List
<byte[]> getGroupIds() {
562 var groups
= m
.getGroups();
563 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
567 public DBusPath
getGroup(final byte[] groupId
) {
569 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
570 if (groupOptional
.isEmpty()) {
571 throw new Error
.GroupNotFound("Group not found");
573 return groupOptional
.get().getObjectPath();
577 public List
<StructGroup
> listGroups() {
583 public String
getGroupName(final byte[] groupId
) {
584 var group
= m
.getGroup(getGroupId(groupId
));
585 if (group
== null || group
.title() == null) {
588 return group
.title();
593 public List
<String
> getGroupMembers(final byte[] groupId
) {
594 var group
= m
.getGroup(getGroupId(groupId
));
598 final var members
= group
.members();
599 return getRecipientStrings(members
);
604 public byte[] createGroup(
605 final String name
, final List
<String
> members
, final String avatar
606 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
607 return updateGroup(new byte[0], name
, members
, avatar
);
611 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
613 groupId
= nullIfEmpty(groupId
);
614 name
= nullIfEmpty(name
);
615 avatar
= nullIfEmpty(avatar
);
616 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
617 if (groupId
== null) {
618 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
620 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
621 return results
.first().serialize();
623 final var results
= m
.updateGroup(getGroupId(groupId
),
624 UpdateGroup
.newBuilder()
626 .withMembers(memberIdentifiers
)
627 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
629 if (results
!= null) {
630 checkGroupSendMessageResults(results
.timestamp(), results
.results());
634 } catch (IOException e
) {
635 throw new Error
.Failure(e
.getMessage());
636 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
637 throw new Error
.GroupNotFound(e
.getMessage());
638 } catch (AttachmentInvalidException e
) {
639 throw new Error
.AttachmentInvalid(e
.getMessage());
640 } catch (UnregisteredRecipientException e
) {
641 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
646 public boolean isRegistered() {
651 public boolean isRegistered(String number
) {
652 var result
= isRegistered(List
.of(number
));
653 return result
.get(0);
657 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
658 if (numbers
.isEmpty()) {
662 Map
<String
, UserStatus
> registered
;
664 registered
= m
.getUserStatus(new HashSet
<>(numbers
));
665 } catch (IOException e
) {
666 throw new Error
.Failure(e
.getMessage());
669 return numbers
.stream().map(number
-> registered
.get(number
).uuid() != null).toList();
673 public void updateProfile(
679 final boolean removeAvatar
682 givenName
= nullIfEmpty(givenName
);
683 familyName
= nullIfEmpty(familyName
);
684 about
= nullIfEmpty(about
);
685 aboutEmoji
= nullIfEmpty(aboutEmoji
);
686 avatarPath
= nullIfEmpty(avatarPath
);
687 File avatarFile
= removeAvatar
|| avatarPath
== null ?
null : new File(avatarPath
);
688 m
.updateProfile(UpdateProfile
.newBuilder()
689 .withGivenName(givenName
)
690 .withFamilyName(familyName
)
692 .withAboutEmoji(aboutEmoji
)
693 .withAvatar(avatarFile
)
694 .withDeleteAvatar(removeAvatar
)
696 } catch (IOException e
) {
697 throw new Error
.Failure(e
.getMessage());
702 public void updateProfile(
705 final String aboutEmoji
,
707 final boolean removeAvatar
709 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
713 public void removePin() {
715 m
.setRegistrationLockPin(Optional
.empty());
716 } catch (IOException e
) {
717 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
718 } catch (NotPrimaryDeviceException e
) {
719 throw new Error
.Failure("This command doesn't work on linked devices.");
724 public void setPin(String registrationLockPin
) {
726 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
727 } catch (IOException e
) {
728 throw new Error
.Failure("Set pin error: " + e
.getMessage());
729 } catch (NotPrimaryDeviceException e
) {
730 throw new Error
.Failure("This command doesn't work on linked devices.");
734 // Provide option to query a version string in order to react on potential
735 // future interface changes
737 public String
version() {
738 return BaseConfig
.PROJECT_VERSION
;
741 // Create a unique list of Numbers from Identities and Contacts to really get
742 // all numbers the system knows
744 public List
<String
> listNumbers() {
745 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.empty())
747 .map(r
-> r
.getAddress().number().orElse(null))
748 .filter(Objects
::nonNull
)
754 public List
<String
> getContactNumber(final String name
) {
755 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.of(name
))
757 .map(r
-> r
.getAddress().getLegacyIdentifier())
762 public void quitGroup(final byte[] groupId
) {
763 var group
= getGroupId(groupId
);
765 m
.quitGroup(group
, Set
.of());
766 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
767 throw new Error
.GroupNotFound(e
.getMessage());
768 } catch (IOException
| LastGroupAdminException e
) {
769 throw new Error
.Failure(e
.getMessage());
770 } catch (UnregisteredRecipientException e
) {
771 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
776 public byte[] joinGroup(final String groupLink
) {
778 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
779 if (linkUrl
== null) {
780 throw new Error
.Failure("Group link is invalid:");
782 final var result
= m
.joinGroup(linkUrl
);
783 return result
.first().serialize();
784 } catch (PendingAdminApprovalException e
) {
785 throw new Error
.Failure("Pending admin approval: " + e
.getMessage());
786 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
787 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
788 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
789 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
790 } catch (IOException e
) {
791 throw new Error
.Failure(e
.getMessage());
796 public boolean isContactBlocked(final String number
) {
797 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
801 public boolean isGroupBlocked(final byte[] groupId
) {
802 var group
= m
.getGroup(getGroupId(groupId
));
806 return group
.isBlocked();
811 public boolean isMember(final byte[] groupId
) {
812 var group
= m
.getGroup(getGroupId(groupId
));
816 return group
.isMember();
821 public String
uploadStickerPack(String stickerPackPath
) {
822 File path
= new File(stickerPackPath
);
824 return m
.uploadStickerPack(path
).toString();
825 } catch (IOException e
) {
826 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
827 } catch (StickerPackInvalidException e
) {
828 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
832 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
833 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
839 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
841 if (result
.isIdentityFailure()) {
842 throw new Error
.UntrustedIdentity(message
);
844 throw new Error
.Failure(message
);
848 private void checkSendMessageResults(final SendMessageResults results
) {
849 final var sendMessageResults
= results
.results().values().stream().findFirst();
850 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
851 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
855 if (results
.hasSuccess()) {
859 var message
= new StringBuilder();
860 message
.append("Failed to send messages:\n");
861 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
862 for (var error
: errors
) {
863 message
.append(error
).append('\n');
865 message
.append(results
.timestamp());
867 throw new Error
.Failure(message
.toString());
870 private static void checkGroupSendMessageResults(
871 long timestamp
, Collection
<SendMessageResult
> results
872 ) throws DBusExecutionException
{
873 if (results
.size() == 1) {
874 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
878 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
879 if (errors
.size() == 0 || errors
.size() < results
.size()) {
883 var message
= new StringBuilder();
884 message
.append("Failed to send message:\n");
885 for (var error
: errors
) {
886 message
.append(error
).append('\n');
888 message
.append(timestamp
);
890 throw new Error
.Failure(message
.toString());
893 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
894 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
897 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
898 final Collection
<String
> recipientStrings
, final String localNumber
899 ) throws DBusExecutionException
{
900 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
901 for (var recipientString
: recipientStrings
) {
902 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
907 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
908 final String recipientString
, final String localNumber
909 ) throws DBusExecutionException
{
911 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
912 } catch (InvalidNumberException e
) {
913 throw new Error
.InvalidNumber(e
.getMessage());
917 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
918 return new RecipientIdentifier
.Group(getGroupId(groupId
));
921 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
923 return GroupId
.unknownVersion(groupId
);
924 } catch (Throwable e
) {
925 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
929 private byte[] nullIfEmpty(final byte[] array
) {
930 return array
.length
== 0 ?
null : array
;
933 private String
nullIfEmpty(final String name
) {
934 return name
.isEmpty() ?
null : name
;
937 private String
emptyIfNull(final String string
) {
938 return string
== null ?
"" : string
;
941 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
942 return basePath
+ "/Devices/" + deviceId
;
945 private void updateDevices() {
946 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
948 linkedDevices
= m
.getLinkedDevices();
949 } catch (IOException e
) {
950 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
955 linkedDevices
.forEach(d
-> {
956 final var object
= new DbusSignalDeviceImpl(d
);
957 final var deviceObjectPath
= object
.getObjectPath();
958 exportObject(object
);
959 if (d
.isThisDevice()) {
960 thisDevice
= new DBusPath(deviceObjectPath
);
962 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
966 private void unExportDevices() {
967 this.devices
.stream()
968 .map(StructDevice
::getObjectPath
)
969 .map(DBusPath
::getPath
)
970 .forEach(connection
::unExportObject
);
971 this.devices
.clear();
974 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
975 return basePath
+ "/Groups/" + Base64
.getEncoder()
976 .encodeToString(groupId
)
982 private void updateGroups() {
983 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
984 groups
= m
.getGroups();
988 groups
.forEach(g
-> {
989 final var object
= new DbusSignalGroupImpl(g
.groupId());
990 exportObject(object
);
991 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
992 g
.groupId().serialize(),
993 emptyIfNull(g
.title())));
997 private void unExportGroups() {
998 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
1002 private static String
getConfigurationObjectPath(String basePath
) {
1003 return basePath
+ "/Configuration";
1006 private void updateConfiguration() {
1007 unExportConfiguration();
1008 final var object
= new DbusSignalConfigurationImpl();
1009 exportObject(object
);
1012 private void unExportConfiguration() {
1013 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
1014 connection
.unExportObject(objectPath
);
1017 private void exportObject(final DBusInterface object
) {
1019 connection
.exportObject(object
);
1020 logger
.debug("Exported dbus object: " + object
.getObjectPath());
1021 } catch (DBusException e
) {
1022 e
.printStackTrace();
1026 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
1028 private final org
.asamk
.signal
.manager
.api
.Device device
;
1030 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1031 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1032 List
.of(new DbusProperty
<>("Id", device
::id
),
1033 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1034 new DbusProperty
<>("Created", device
::created
),
1035 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1036 this.device
= device
;
1040 public String
getObjectPath() {
1041 return getDeviceObjectPath(objectPath
, device
.id());
1045 public void removeDevice() throws Error
.Failure
{
1047 m
.removeLinkedDevices(device
.id());
1049 } catch (IOException e
) {
1050 throw new Error
.Failure(e
.getMessage());
1054 private void setDeviceName(String name
) {
1055 if (!device
.isThisDevice()) {
1056 throw new Error
.Failure("Only the name of this device can be changed");
1059 m
.updateAccountAttributes(name
);
1060 // update device list
1062 } catch (IOException e
) {
1063 throw new Error
.Failure(e
.getMessage());
1068 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1070 public DbusSignalConfigurationImpl(
1072 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1073 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1074 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1075 this::getUnidentifiedDeliveryIndicators
,
1076 this::setUnidentifiedDeliveryIndicators
),
1077 new DbusProperty
<>("TypingIndicators",
1078 this::getTypingIndicators
,
1079 this::setTypingIndicators
),
1080 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1085 public String
getObjectPath() {
1086 return getConfigurationObjectPath(objectPath
);
1089 public void setReadReceipts(Boolean readReceipts
) {
1090 setConfiguration(readReceipts
, null, null, null);
1093 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1094 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1097 public void setTypingIndicators(Boolean typingIndicators
) {
1098 setConfiguration(null, null, typingIndicators
, null);
1101 public void setLinkPreviews(Boolean linkPreviews
) {
1102 setConfiguration(null, null, null, linkPreviews
);
1105 private void setConfiguration(
1106 Boolean readReceipts
,
1107 Boolean unidentifiedDeliveryIndicators
,
1108 Boolean typingIndicators
,
1109 Boolean linkPreviews
1112 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1113 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1114 Optional
.ofNullable(typingIndicators
),
1115 Optional
.ofNullable(linkPreviews
)));
1116 } catch (IOException e
) {
1117 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1118 } catch (NotPrimaryDeviceException e
) {
1119 throw new Error
.Failure("This command doesn't work on linked devices.");
1123 private boolean getReadReceipts() {
1124 return m
.getConfiguration().readReceipts().orElse(false);
1127 private boolean getUnidentifiedDeliveryIndicators() {
1128 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1131 private boolean getTypingIndicators() {
1132 return m
.getConfiguration().typingIndicators().orElse(false);
1135 private boolean getLinkPreviews() {
1136 return m
.getConfiguration().linkPreviews().orElse(false);
1140 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1142 private final GroupId groupId
;
1144 public DbusSignalGroupImpl(final GroupId groupId
) {
1145 this.groupId
= groupId
;
1146 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1147 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1148 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1149 new DbusProperty
<>("Description",
1150 () -> emptyIfNull(getGroup().description()),
1151 this::setGroupDescription
),
1152 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1153 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1154 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1155 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1156 new DbusProperty
<>("MessageExpirationTimer",
1157 () -> getGroup().messageExpirationTimer(),
1158 this::setMessageExpirationTime
),
1159 new DbusProperty
<>("Members",
1160 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1161 new DbusProperty
<>("PendingMembers",
1162 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1163 new DbusProperty
<>("RequestingMembers",
1164 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1165 new DbusProperty
<>("Admins",
1166 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1167 new DbusProperty
<>("Banned",
1168 () -> new Variant
<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
1169 new DbusProperty
<>("PermissionAddMember",
1170 () -> getGroup().permissionAddMember().name(),
1171 this::setGroupPermissionAddMember
),
1172 new DbusProperty
<>("PermissionEditDetails",
1173 () -> getGroup().permissionEditDetails().name(),
1174 this::setGroupPermissionEditDetails
),
1175 new DbusProperty
<>("PermissionSendMessage",
1176 () -> getGroup().permissionSendMessage().name(),
1177 this::setGroupPermissionSendMessage
),
1178 new DbusProperty
<>("GroupInviteLink", () -> {
1179 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1180 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1185 public String
getObjectPath() {
1186 return getGroupObjectPath(objectPath
, groupId
.serialize());
1190 public void quitGroup() throws Error
.Failure
{
1192 m
.quitGroup(groupId
, Set
.of());
1193 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1194 throw new Error
.GroupNotFound(e
.getMessage());
1195 } catch (IOException e
) {
1196 throw new Error
.Failure(e
.getMessage());
1197 } catch (LastGroupAdminException e
) {
1198 throw new Error
.LastGroupAdmin(e
.getMessage());
1199 } catch (UnregisteredRecipientException e
) {
1200 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1205 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1207 m
.deleteGroup(groupId
);
1208 } catch (IOException e
) {
1209 throw new Error
.Failure(e
.getMessage());
1215 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1216 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1217 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1221 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1222 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1223 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1227 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1228 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1229 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1233 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1234 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1235 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1239 public void resetLink() throws Error
.Failure
{
1240 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1244 public void disableLink() throws Error
.Failure
{
1245 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1249 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1250 updateGroup(UpdateGroup
.newBuilder()
1251 .withGroupLinkState(requiresApproval
1252 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1253 : GroupLinkState
.ENABLED
)
1257 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1258 return m
.getGroup(groupId
);
1261 private void setGroupName(final String name
) {
1262 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1265 private void setGroupDescription(final String description
) {
1266 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1269 private void setGroupAvatar(final String avatar
) {
1270 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1273 private void setMessageExpirationTime(final int expirationTime
) {
1274 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1277 private void setGroupPermissionAddMember(final String permission
) {
1278 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1281 private void setGroupPermissionEditDetails(final String permission
) {
1282 updateGroup(UpdateGroup
.newBuilder()
1283 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1287 private void setGroupPermissionSendMessage(final String permission
) {
1288 updateGroup(UpdateGroup
.newBuilder()
1289 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1293 private void setIsBlocked(final boolean isBlocked
) {
1295 m
.setGroupsBlocked(List
.of(groupId
), isBlocked
);
1296 } catch (NotPrimaryDeviceException e
) {
1297 throw new Error
.Failure("This command doesn't work on linked devices.");
1298 } catch (GroupNotFoundException e
) {
1299 throw new Error
.GroupNotFound(e
.getMessage());
1300 } catch (IOException e
) {
1301 throw new Error
.Failure(e
.getMessage());
1305 private void updateGroup(final UpdateGroup updateGroup
) {
1307 m
.updateGroup(groupId
, updateGroup
);
1308 } catch (IOException e
) {
1309 throw new Error
.Failure(e
.getMessage());
1310 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1311 throw new Error
.GroupNotFound(e
.getMessage());
1312 } catch (AttachmentInvalidException e
) {
1313 throw new Error
.AttachmentInvalid(e
.getMessage());
1314 } catch (UnregisteredRecipientException e
) {
1315 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");