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()));
291 checkSendMessageResults(results
);
292 return results
.timestamp();
293 } catch (IOException e
) {
294 throw new Error
.Failure(e
.getMessage());
295 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
296 throw new Error
.GroupNotFound(e
.getMessage());
297 } catch (UnregisteredRecipientException e
) {
298 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
303 public long sendPaymentNotification(
304 final byte[] receipt
, final String note
, final String recipient
305 ) throws Error
.Failure
{
307 final var results
= m
.sendPaymentNotificationMessage(receipt
,
309 getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
310 checkSendMessageResults(results
);
311 return results
.timestamp();
312 } catch (IOException e
) {
313 throw new Error
.Failure(e
.getMessage());
318 public void sendTyping(
319 final String recipient
, final boolean stop
320 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
322 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
323 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
324 .map(RecipientIdentifier
.class::cast
)
325 .collect(Collectors
.toSet()));
326 checkSendMessageResults(results
);
327 } catch (IOException e
) {
328 throw new Error
.Failure(e
.getMessage());
329 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
330 throw new Error
.GroupNotFound(e
.getMessage());
335 public void sendReadReceipt(
336 final String recipient
, final List
<Long
> messageIds
337 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
339 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
341 checkSendMessageResults(results
);
342 } catch (IOException e
) {
343 throw new Error
.Failure(e
.getMessage());
348 public void sendViewedReceipt(
349 final String recipient
, final List
<Long
> messageIds
350 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
352 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
354 checkSendMessageResults(results
);
355 } catch (IOException e
) {
356 throw new Error
.Failure(e
.getMessage());
361 public void sendContacts() {
364 } catch (IOException e
) {
365 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
370 public void sendSyncRequest() {
372 m
.requestAllSyncData();
373 } catch (IOException e
) {
374 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
379 public long sendNoteToSelfMessage(
380 final String message
, final List
<String
> attachments
381 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
383 final var results
= m
.sendMessage(new Message(message
,
388 List
.of()), Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
389 checkSendMessageResults(results
);
390 return results
.timestamp();
391 } catch (AttachmentInvalidException e
) {
392 throw new Error
.AttachmentInvalid(e
.getMessage());
393 } catch (IOException
| InvalidStickerException e
) {
394 throw new Error
.Failure(e
.getMessage());
395 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
396 throw new Error
.GroupNotFound(e
.getMessage());
397 } catch (UnregisteredRecipientException e
) {
398 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
403 public void sendEndSessionMessage(final List
<String
> recipients
) {
405 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
406 checkSendMessageResults(results
);
407 } catch (IOException e
) {
408 throw new Error
.Failure(e
.getMessage());
413 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
414 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
418 public void deleteContact(final String recipient
) throws Error
.Failure
{
419 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
423 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
425 var results
= m
.sendMessage(new Message(message
,
430 List
.of()), Set
.of(getGroupRecipientIdentifier(groupId
)));
431 checkSendMessageResults(results
);
432 return results
.timestamp();
433 } catch (IOException
| InvalidStickerException e
) {
434 throw new Error
.Failure(e
.getMessage());
435 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
436 throw new Error
.GroupNotFound(e
.getMessage());
437 } catch (AttachmentInvalidException e
) {
438 throw new Error
.AttachmentInvalid(e
.getMessage());
439 } catch (UnregisteredRecipientException e
) {
440 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
445 public void sendGroupTyping(
446 final byte[] groupId
, final boolean stop
447 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
449 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
450 Set
.of(getGroupRecipientIdentifier(groupId
)));
451 checkSendMessageResults(results
);
452 } catch (IOException e
) {
453 throw new Error
.Failure(e
.getMessage());
454 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
455 throw new Error
.GroupNotFound(e
.getMessage());
460 public long sendGroupRemoteDeleteMessage(
461 final long targetSentTimestamp
, final byte[] groupId
464 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
465 Set
.of(getGroupRecipientIdentifier(groupId
)));
466 checkSendMessageResults(results
);
467 return results
.timestamp();
468 } catch (IOException e
) {
469 throw new Error
.Failure(e
.getMessage());
470 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
471 throw new Error
.GroupNotFound(e
.getMessage());
476 public long sendGroupMessageReaction(
478 final boolean remove
,
479 final String targetAuthor
,
480 final long targetSentTimestamp
,
484 final var results
= m
.sendMessageReaction(emoji
,
486 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
488 Set
.of(getGroupRecipientIdentifier(groupId
)));
489 checkSendMessageResults(results
);
490 return results
.timestamp();
491 } catch (IOException e
) {
492 throw new Error
.Failure(e
.getMessage());
493 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
494 throw new Error
.GroupNotFound(e
.getMessage());
495 } catch (UnregisteredRecipientException e
) {
496 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
500 // Since contact names might be empty if not defined, also potentially return
503 public String
getContactName(final String number
) {
504 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
505 return name
== null ?
"" : name
;
509 public void setContactName(final String number
, final String name
) {
511 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
, "");
512 } catch (NotPrimaryDeviceException e
) {
513 throw new Error
.Failure("This command doesn't work on linked devices.");
514 } catch (IOException e
) {
515 throw new Error
.Failure("Contact is not registered.");
516 } catch (UnregisteredRecipientException e
) {
517 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
522 public void setExpirationTimer(final String number
, final int expiration
) {
524 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
525 } catch (IOException e
) {
526 throw new Error
.Failure(e
.getMessage());
527 } catch (UnregisteredRecipientException e
) {
528 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
533 public void setContactBlocked(final String number
, final boolean blocked
) {
535 m
.setContactsBlocked(List
.of(getSingleRecipientIdentifier(number
, m
.getSelfNumber())), blocked
);
536 } catch (NotPrimaryDeviceException e
) {
537 throw new Error
.Failure("This command doesn't work on linked devices.");
538 } catch (IOException e
) {
539 throw new Error
.Failure(e
.getMessage());
540 } catch (UnregisteredRecipientException e
) {
541 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
546 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
548 m
.setGroupsBlocked(List
.of(getGroupId(groupId
)), blocked
);
549 } catch (NotPrimaryDeviceException e
) {
550 throw new Error
.Failure("This command doesn't work on linked devices.");
551 } catch (GroupNotFoundException e
) {
552 throw new Error
.GroupNotFound(e
.getMessage());
553 } catch (IOException e
) {
554 throw new Error
.Failure(e
.getMessage());
559 public List
<byte[]> getGroupIds() {
560 var groups
= m
.getGroups();
561 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
565 public DBusPath
getGroup(final byte[] groupId
) {
567 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
568 if (groupOptional
.isEmpty()) {
569 throw new Error
.GroupNotFound("Group not found");
571 return groupOptional
.get().getObjectPath();
575 public List
<StructGroup
> listGroups() {
581 public String
getGroupName(final byte[] groupId
) {
582 var group
= m
.getGroup(getGroupId(groupId
));
583 if (group
== null || group
.title() == null) {
586 return group
.title();
591 public List
<String
> getGroupMembers(final byte[] groupId
) {
592 var group
= m
.getGroup(getGroupId(groupId
));
596 final var members
= group
.members();
597 return getRecipientStrings(members
);
602 public byte[] createGroup(
603 final String name
, final List
<String
> members
, final String avatar
604 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
605 return updateGroup(new byte[0], name
, members
, avatar
);
609 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
611 groupId
= nullIfEmpty(groupId
);
612 name
= nullIfEmpty(name
);
613 avatar
= nullIfEmpty(avatar
);
614 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
615 if (groupId
== null) {
616 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
618 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
619 return results
.first().serialize();
621 final var results
= m
.updateGroup(getGroupId(groupId
),
622 UpdateGroup
.newBuilder()
624 .withMembers(memberIdentifiers
)
625 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
627 if (results
!= null) {
628 checkGroupSendMessageResults(results
.timestamp(), results
.results());
632 } catch (IOException e
) {
633 throw new Error
.Failure(e
.getMessage());
634 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
635 throw new Error
.GroupNotFound(e
.getMessage());
636 } catch (AttachmentInvalidException e
) {
637 throw new Error
.AttachmentInvalid(e
.getMessage());
638 } catch (UnregisteredRecipientException e
) {
639 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
644 public boolean isRegistered() {
649 public boolean isRegistered(String number
) {
650 var result
= isRegistered(List
.of(number
));
651 return result
.get(0);
655 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
656 if (numbers
.isEmpty()) {
660 Map
<String
, UserStatus
> registered
;
662 registered
= m
.getUserStatus(new HashSet
<>(numbers
));
663 } catch (IOException e
) {
664 throw new Error
.Failure(e
.getMessage());
667 return numbers
.stream().map(number
-> registered
.get(number
).uuid() != null).toList();
671 public void updateProfile(
677 final boolean removeAvatar
680 givenName
= nullIfEmpty(givenName
);
681 familyName
= nullIfEmpty(familyName
);
682 about
= nullIfEmpty(about
);
683 aboutEmoji
= nullIfEmpty(aboutEmoji
);
684 avatarPath
= nullIfEmpty(avatarPath
);
685 File avatarFile
= removeAvatar
|| avatarPath
== null ?
null : new File(avatarPath
);
686 m
.updateProfile(UpdateProfile
.newBuilder()
687 .withGivenName(givenName
)
688 .withFamilyName(familyName
)
690 .withAboutEmoji(aboutEmoji
)
691 .withAvatar(avatarFile
)
692 .withDeleteAvatar(removeAvatar
)
694 } catch (IOException e
) {
695 throw new Error
.Failure(e
.getMessage());
700 public void updateProfile(
703 final String aboutEmoji
,
705 final boolean removeAvatar
707 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
711 public void removePin() {
713 m
.setRegistrationLockPin(Optional
.empty());
714 } catch (IOException e
) {
715 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
716 } catch (NotPrimaryDeviceException e
) {
717 throw new Error
.Failure("This command doesn't work on linked devices.");
722 public void setPin(String registrationLockPin
) {
724 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
725 } catch (IOException e
) {
726 throw new Error
.Failure("Set pin error: " + e
.getMessage());
727 } catch (NotPrimaryDeviceException e
) {
728 throw new Error
.Failure("This command doesn't work on linked devices.");
732 // Provide option to query a version string in order to react on potential
733 // future interface changes
735 public String
version() {
736 return BaseConfig
.PROJECT_VERSION
;
739 // Create a unique list of Numbers from Identities and Contacts to really get
740 // all numbers the system knows
742 public List
<String
> listNumbers() {
743 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.empty())
745 .map(r
-> r
.getAddress().number().orElse(null))
746 .filter(Objects
::nonNull
)
752 public List
<String
> getContactNumber(final String name
) {
753 return m
.getRecipients(false, Optional
.empty(), Set
.of(), Optional
.of(name
))
755 .map(r
-> r
.getAddress().getLegacyIdentifier())
760 public void quitGroup(final byte[] groupId
) {
761 var group
= getGroupId(groupId
);
763 m
.quitGroup(group
, Set
.of());
764 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
765 throw new Error
.GroupNotFound(e
.getMessage());
766 } catch (IOException
| LastGroupAdminException e
) {
767 throw new Error
.Failure(e
.getMessage());
768 } catch (UnregisteredRecipientException e
) {
769 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
774 public byte[] joinGroup(final String groupLink
) {
776 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
777 if (linkUrl
== null) {
778 throw new Error
.Failure("Group link is invalid:");
780 final var result
= m
.joinGroup(linkUrl
);
781 return result
.first().serialize();
782 } catch (PendingAdminApprovalException e
) {
783 throw new Error
.Failure("Pending admin approval: " + e
.getMessage());
784 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
785 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
786 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
787 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
788 } catch (IOException e
) {
789 throw new Error
.Failure(e
.getMessage());
794 public boolean isContactBlocked(final String number
) {
795 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
799 public boolean isGroupBlocked(final byte[] groupId
) {
800 var group
= m
.getGroup(getGroupId(groupId
));
804 return group
.isBlocked();
809 public boolean isMember(final byte[] groupId
) {
810 var group
= m
.getGroup(getGroupId(groupId
));
814 return group
.isMember();
819 public String
uploadStickerPack(String stickerPackPath
) {
820 File path
= new File(stickerPackPath
);
822 return m
.uploadStickerPack(path
).toString();
823 } catch (IOException e
) {
824 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
825 } catch (StickerPackInvalidException e
) {
826 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
830 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
831 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
837 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
839 if (result
.isIdentityFailure()) {
840 throw new Error
.UntrustedIdentity(message
);
842 throw new Error
.Failure(message
);
846 private void checkSendMessageResults(final SendMessageResults results
) {
847 final var sendMessageResults
= results
.results().values().stream().findFirst();
848 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
849 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
853 if (results
.hasSuccess()) {
857 var message
= new StringBuilder();
858 message
.append("Failed to send messages:\n");
859 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
860 for (var error
: errors
) {
861 message
.append(error
).append('\n');
863 message
.append(results
.timestamp());
865 throw new Error
.Failure(message
.toString());
868 private static void checkGroupSendMessageResults(
869 long timestamp
, Collection
<SendMessageResult
> results
870 ) throws DBusExecutionException
{
871 if (results
.size() == 1) {
872 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
876 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
877 if (errors
.size() == 0 || errors
.size() < results
.size()) {
881 var message
= new StringBuilder();
882 message
.append("Failed to send message:\n");
883 for (var error
: errors
) {
884 message
.append(error
).append('\n');
886 message
.append(timestamp
);
888 throw new Error
.Failure(message
.toString());
891 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
892 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
895 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
896 final Collection
<String
> recipientStrings
, final String localNumber
897 ) throws DBusExecutionException
{
898 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
899 for (var recipientString
: recipientStrings
) {
900 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
905 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
906 final String recipientString
, final String localNumber
907 ) throws DBusExecutionException
{
909 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
910 } catch (InvalidNumberException e
) {
911 throw new Error
.InvalidNumber(e
.getMessage());
915 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
916 return new RecipientIdentifier
.Group(getGroupId(groupId
));
919 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
921 return GroupId
.unknownVersion(groupId
);
922 } catch (Throwable e
) {
923 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
927 private byte[] nullIfEmpty(final byte[] array
) {
928 return array
.length
== 0 ?
null : array
;
931 private String
nullIfEmpty(final String name
) {
932 return name
.isEmpty() ?
null : name
;
935 private String
emptyIfNull(final String string
) {
936 return string
== null ?
"" : string
;
939 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
940 return basePath
+ "/Devices/" + deviceId
;
943 private void updateDevices() {
944 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
946 linkedDevices
= m
.getLinkedDevices();
947 } catch (IOException e
) {
948 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
953 linkedDevices
.forEach(d
-> {
954 final var object
= new DbusSignalDeviceImpl(d
);
955 final var deviceObjectPath
= object
.getObjectPath();
956 exportObject(object
);
957 if (d
.isThisDevice()) {
958 thisDevice
= new DBusPath(deviceObjectPath
);
960 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), (long) d
.id(), emptyIfNull(d
.name())));
964 private void unExportDevices() {
965 this.devices
.stream()
966 .map(StructDevice
::getObjectPath
)
967 .map(DBusPath
::getPath
)
968 .forEach(connection
::unExportObject
);
969 this.devices
.clear();
972 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
973 return basePath
+ "/Groups/" + Base64
.getEncoder()
974 .encodeToString(groupId
)
980 private void updateGroups() {
981 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
982 groups
= m
.getGroups();
986 groups
.forEach(g
-> {
987 final var object
= new DbusSignalGroupImpl(g
.groupId());
988 exportObject(object
);
989 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
990 g
.groupId().serialize(),
991 emptyIfNull(g
.title())));
995 private void unExportGroups() {
996 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
1000 private static String
getConfigurationObjectPath(String basePath
) {
1001 return basePath
+ "/Configuration";
1004 private void updateConfiguration() {
1005 unExportConfiguration();
1006 final var object
= new DbusSignalConfigurationImpl();
1007 exportObject(object
);
1010 private void unExportConfiguration() {
1011 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
1012 connection
.unExportObject(objectPath
);
1015 private void exportObject(final DBusInterface object
) {
1017 connection
.exportObject(object
);
1018 logger
.debug("Exported dbus object: " + object
.getObjectPath());
1019 } catch (DBusException e
) {
1020 e
.printStackTrace();
1024 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
1026 private final org
.asamk
.signal
.manager
.api
.Device device
;
1028 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
1029 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1030 List
.of(new DbusProperty
<>("Id", device
::id
),
1031 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1032 new DbusProperty
<>("Created", device
::created
),
1033 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1034 this.device
= device
;
1038 public String
getObjectPath() {
1039 return getDeviceObjectPath(objectPath
, device
.id());
1043 public void removeDevice() throws Error
.Failure
{
1045 m
.removeLinkedDevices(device
.id());
1047 } catch (IOException e
) {
1048 throw new Error
.Failure(e
.getMessage());
1052 private void setDeviceName(String name
) {
1053 if (!device
.isThisDevice()) {
1054 throw new Error
.Failure("Only the name of this device can be changed");
1057 m
.updateAccountAttributes(name
);
1058 // update device list
1060 } catch (IOException e
) {
1061 throw new Error
.Failure(e
.getMessage());
1066 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1068 public DbusSignalConfigurationImpl(
1070 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1071 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1072 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1073 this::getUnidentifiedDeliveryIndicators
,
1074 this::setUnidentifiedDeliveryIndicators
),
1075 new DbusProperty
<>("TypingIndicators",
1076 this::getTypingIndicators
,
1077 this::setTypingIndicators
),
1078 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1083 public String
getObjectPath() {
1084 return getConfigurationObjectPath(objectPath
);
1087 public void setReadReceipts(Boolean readReceipts
) {
1088 setConfiguration(readReceipts
, null, null, null);
1091 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1092 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1095 public void setTypingIndicators(Boolean typingIndicators
) {
1096 setConfiguration(null, null, typingIndicators
, null);
1099 public void setLinkPreviews(Boolean linkPreviews
) {
1100 setConfiguration(null, null, null, linkPreviews
);
1103 private void setConfiguration(
1104 Boolean readReceipts
,
1105 Boolean unidentifiedDeliveryIndicators
,
1106 Boolean typingIndicators
,
1107 Boolean linkPreviews
1110 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1111 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1112 Optional
.ofNullable(typingIndicators
),
1113 Optional
.ofNullable(linkPreviews
)));
1114 } catch (IOException e
) {
1115 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1116 } catch (NotPrimaryDeviceException e
) {
1117 throw new Error
.Failure("This command doesn't work on linked devices.");
1121 private boolean getReadReceipts() {
1122 return m
.getConfiguration().readReceipts().orElse(false);
1125 private boolean getUnidentifiedDeliveryIndicators() {
1126 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1129 private boolean getTypingIndicators() {
1130 return m
.getConfiguration().typingIndicators().orElse(false);
1133 private boolean getLinkPreviews() {
1134 return m
.getConfiguration().linkPreviews().orElse(false);
1138 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1140 private final GroupId groupId
;
1142 public DbusSignalGroupImpl(final GroupId groupId
) {
1143 this.groupId
= groupId
;
1144 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1145 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1146 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1147 new DbusProperty
<>("Description",
1148 () -> emptyIfNull(getGroup().description()),
1149 this::setGroupDescription
),
1150 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1151 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1152 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1153 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1154 new DbusProperty
<>("MessageExpirationTimer",
1155 () -> getGroup().messageExpirationTimer(),
1156 this::setMessageExpirationTime
),
1157 new DbusProperty
<>("Members",
1158 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1159 new DbusProperty
<>("PendingMembers",
1160 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1161 new DbusProperty
<>("RequestingMembers",
1162 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1163 new DbusProperty
<>("Admins",
1164 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1165 new DbusProperty
<>("Banned",
1166 () -> new Variant
<>(getRecipientStrings(getGroup().bannedMembers()), "as")),
1167 new DbusProperty
<>("PermissionAddMember",
1168 () -> getGroup().permissionAddMember().name(),
1169 this::setGroupPermissionAddMember
),
1170 new DbusProperty
<>("PermissionEditDetails",
1171 () -> getGroup().permissionEditDetails().name(),
1172 this::setGroupPermissionEditDetails
),
1173 new DbusProperty
<>("PermissionSendMessage",
1174 () -> getGroup().permissionSendMessage().name(),
1175 this::setGroupPermissionSendMessage
),
1176 new DbusProperty
<>("GroupInviteLink", () -> {
1177 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1178 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1183 public String
getObjectPath() {
1184 return getGroupObjectPath(objectPath
, groupId
.serialize());
1188 public void quitGroup() throws Error
.Failure
{
1190 m
.quitGroup(groupId
, Set
.of());
1191 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1192 throw new Error
.GroupNotFound(e
.getMessage());
1193 } catch (IOException e
) {
1194 throw new Error
.Failure(e
.getMessage());
1195 } catch (LastGroupAdminException e
) {
1196 throw new Error
.LastGroupAdmin(e
.getMessage());
1197 } catch (UnregisteredRecipientException e
) {
1198 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1203 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1205 m
.deleteGroup(groupId
);
1206 } catch (IOException e
) {
1207 throw new Error
.Failure(e
.getMessage());
1213 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1214 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1215 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1219 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1220 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1221 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1225 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1226 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1227 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1231 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1232 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1233 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1237 public void resetLink() throws Error
.Failure
{
1238 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1242 public void disableLink() throws Error
.Failure
{
1243 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1247 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1248 updateGroup(UpdateGroup
.newBuilder()
1249 .withGroupLinkState(requiresApproval
1250 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1251 : GroupLinkState
.ENABLED
)
1255 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1256 return m
.getGroup(groupId
);
1259 private void setGroupName(final String name
) {
1260 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1263 private void setGroupDescription(final String description
) {
1264 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1267 private void setGroupAvatar(final String avatar
) {
1268 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1271 private void setMessageExpirationTime(final int expirationTime
) {
1272 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1275 private void setGroupPermissionAddMember(final String permission
) {
1276 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1279 private void setGroupPermissionEditDetails(final String permission
) {
1280 updateGroup(UpdateGroup
.newBuilder()
1281 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1285 private void setGroupPermissionSendMessage(final String permission
) {
1286 updateGroup(UpdateGroup
.newBuilder()
1287 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1291 private void setIsBlocked(final boolean isBlocked
) {
1293 m
.setGroupsBlocked(List
.of(groupId
), isBlocked
);
1294 } catch (NotPrimaryDeviceException e
) {
1295 throw new Error
.Failure("This command doesn't work on linked devices.");
1296 } catch (GroupNotFoundException e
) {
1297 throw new Error
.GroupNotFound(e
.getMessage());
1298 } catch (IOException e
) {
1299 throw new Error
.Failure(e
.getMessage());
1303 private void updateGroup(final UpdateGroup updateGroup
) {
1305 m
.updateGroup(groupId
, updateGroup
);
1306 } catch (IOException e
) {
1307 throw new Error
.Failure(e
.getMessage());
1308 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1309 throw new Error
.GroupNotFound(e
.getMessage());
1310 } catch (AttachmentInvalidException e
) {
1311 throw new Error
.AttachmentInvalid(e
.getMessage());
1312 } catch (UnregisteredRecipientException e
) {
1313 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");