1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.BaseConfig
;
5 import org
.asamk
.signal
.manager
.AttachmentInvalidException
;
6 import org
.asamk
.signal
.manager
.Manager
;
7 import org
.asamk
.signal
.manager
.NotMasterDeviceException
;
8 import org
.asamk
.signal
.manager
.StickerPackInvalidException
;
9 import org
.asamk
.signal
.manager
.api
.Identity
;
10 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
11 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
12 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
13 import org
.asamk
.signal
.manager
.api
.Message
;
14 import org
.asamk
.signal
.manager
.api
.Pair
;
15 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
16 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
17 import org
.asamk
.signal
.manager
.api
.TypingAction
;
18 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
19 import org
.asamk
.signal
.manager
.groups
.GroupId
;
20 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
21 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
22 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
23 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
24 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
25 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
26 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
27 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
29 import org
.asamk
.signal
.util
.ErrorUtils
;
30 import org
.freedesktop
.dbus
.DBusPath
;
31 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
32 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
33 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
34 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
35 import org
.freedesktop
.dbus
.types
.Variant
;
36 import org
.slf4j
.Logger
;
37 import org
.slf4j
.LoggerFactory
;
40 import java
.io
.IOException
;
42 import java
.net
.URISyntaxException
;
43 import java
.util
.ArrayList
;
44 import java
.util
.Arrays
;
45 import java
.util
.Base64
;
46 import java
.util
.Collection
;
47 import java
.util
.HashSet
;
48 import java
.util
.List
;
50 import java
.util
.Objects
;
51 import java
.util
.Optional
;
53 import java
.util
.UUID
;
54 import java
.util
.stream
.Collectors
;
55 import java
.util
.stream
.Stream
;
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
;
81 public void initObjects() {
82 if (!noReceiveOnStart
) {
88 updateConfiguration();
92 if (dbusMessageHandler
!= null) {
93 m
.removeReceiveHandler(dbusMessageHandler
);
94 dbusMessageHandler
= null;
98 unExportConfiguration();
102 public String
getObjectPath() {
107 public String
getSelfNumber() {
108 return m
.getSelfNumber();
112 public void subscribeReceive() {
113 if (dbusMessageHandler
== null) {
114 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
115 m
.addReceiveHandler(dbusMessageHandler
);
121 public void unsubscribeReceive() {
122 subscriberCount
= Math
.max(0, subscriberCount
- 1);
123 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
124 m
.removeReceiveHandler(dbusMessageHandler
);
125 dbusMessageHandler
= null;
130 public void submitRateLimitChallenge(String challenge
, String captcha
) {
132 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
133 } catch (IOException e
) {
134 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
140 public void unregister() throws Error
.Failure
{
143 } catch (IOException e
) {
144 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
149 public void deleteAccount() throws Error
.Failure
{
152 } catch (IOException e
) {
153 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
158 public void addDevice(String uri
) {
160 m
.addDeviceLink(new URI(uri
));
161 } catch (IOException
| InvalidDeviceLinkException e
) {
162 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
163 } catch (URISyntaxException e
) {
164 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
165 + " Device link uri has invalid format: "
171 public DBusPath
getDevice(long deviceId
) {
173 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
174 if (deviceOptional
.isEmpty()) {
175 throw new Error
.DeviceNotFound("Device not found");
177 return deviceOptional
.get().getObjectPath();
181 public List
<StructDevice
> listDevices() {
187 public DBusPath
getThisDevice() {
193 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
194 var recipients
= new ArrayList
<String
>(1);
195 recipients
.add(recipient
);
196 return sendMessage(message
, attachments
, recipients
);
200 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
202 final var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
203 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
204 .map(RecipientIdentifier
.class::cast
)
205 .collect(Collectors
.toSet()));
207 checkSendMessageResults(results
.timestamp(), results
.results());
208 return results
.timestamp();
209 } catch (AttachmentInvalidException e
) {
210 throw new Error
.AttachmentInvalid(e
.getMessage());
211 } catch (IOException e
) {
212 throw new Error
.Failure(e
);
213 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
214 throw new Error
.GroupNotFound(e
.getMessage());
219 public long sendRemoteDeleteMessage(
220 final long targetSentTimestamp
, final String recipient
222 var recipients
= new ArrayList
<String
>(1);
223 recipients
.add(recipient
);
224 return sendRemoteDeleteMessage(targetSentTimestamp
, recipients
);
228 public long sendRemoteDeleteMessage(
229 final long targetSentTimestamp
, final List
<String
> recipients
232 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
233 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
234 .map(RecipientIdentifier
.class::cast
)
235 .collect(Collectors
.toSet()));
236 checkSendMessageResults(results
.timestamp(), results
.results());
237 return results
.timestamp();
238 } catch (IOException e
) {
239 throw new Error
.Failure(e
.getMessage());
240 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
241 throw new Error
.GroupNotFound(e
.getMessage());
246 public long sendGroupRemoteDeleteMessage(
247 final long targetSentTimestamp
, final byte[] groupId
250 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
251 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
252 checkSendMessageResults(results
.timestamp(), results
.results());
253 return results
.timestamp();
254 } catch (IOException e
) {
255 throw new Error
.Failure(e
.getMessage());
256 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
257 throw new Error
.GroupNotFound(e
.getMessage());
262 public long sendMessageReaction(
264 final boolean remove
,
265 final String targetAuthor
,
266 final long targetSentTimestamp
,
267 final String recipient
269 var recipients
= new ArrayList
<String
>(1);
270 recipients
.add(recipient
);
271 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, recipients
);
275 public long sendMessageReaction(
277 final boolean remove
,
278 final String targetAuthor
,
279 final long targetSentTimestamp
,
280 final List
<String
> recipients
283 final var results
= m
.sendMessageReaction(emoji
,
285 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
287 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
288 .map(RecipientIdentifier
.class::cast
)
289 .collect(Collectors
.toSet()));
290 checkSendMessageResults(results
.timestamp(), results
.results());
291 return results
.timestamp();
292 } catch (IOException e
) {
293 throw new Error
.Failure(e
.getMessage());
294 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
295 throw new Error
.GroupNotFound(e
.getMessage());
300 public void sendTyping(
301 final String recipient
, final boolean stop
302 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
304 var recipients
= new ArrayList
<String
>(1);
305 recipients
.add(recipient
);
306 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
307 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
308 .map(RecipientIdentifier
.class::cast
)
309 .collect(Collectors
.toSet()));
310 checkSendMessageResults(results
.timestamp(), results
.results());
311 } catch (IOException e
) {
312 throw new Error
.Failure(e
.getMessage());
313 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
314 throw new Error
.GroupNotFound(e
.getMessage());
319 public void sendReadReceipt(
320 final String recipient
, final List
<Long
> messageIds
321 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
323 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
325 checkSendMessageResults(results
.timestamp(), results
.results());
326 } catch (IOException e
) {
327 throw new Error
.Failure(e
.getMessage());
332 public void sendViewedReceipt(
333 final String recipient
, final List
<Long
> messageIds
334 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
336 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
338 checkSendMessageResults(results
.timestamp(), results
.results());
339 } catch (IOException e
) {
340 throw new Error
.Failure(e
.getMessage());
345 public void sendContacts() {
348 } catch (IOException e
) {
349 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
354 public void sendSyncRequest() {
356 m
.requestAllSyncData();
357 } catch (IOException e
) {
358 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
363 public long sendNoteToSelfMessage(
364 final String message
, final List
<String
> attachments
365 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
367 final var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
368 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
369 checkSendMessageResults(results
.timestamp(), results
.results());
370 return results
.timestamp();
371 } catch (AttachmentInvalidException e
) {
372 throw new Error
.AttachmentInvalid(e
.getMessage());
373 } catch (IOException e
) {
374 throw new Error
.Failure(e
.getMessage());
375 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
376 throw new Error
.GroupNotFound(e
.getMessage());
381 public void sendEndSessionMessage(final List
<String
> recipients
) {
383 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
384 checkSendMessageResults(results
.timestamp(), results
.results());
385 } catch (IOException e
) {
386 throw new Error
.Failure(e
.getMessage());
391 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
393 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
394 } catch (IOException e
) {
395 throw new Error
.Failure("Recipient not found");
400 public void deleteContact(final String recipient
) throws Error
.Failure
{
402 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
403 } catch (IOException e
) {
404 throw new Error
.Failure("Contact not found");
409 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
411 var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
412 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
413 checkSendMessageResults(results
.timestamp(), results
.results());
414 return results
.timestamp();
415 } catch (IOException e
) {
416 throw new Error
.Failure(e
.getMessage());
417 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
418 throw new Error
.GroupNotFound(e
.getMessage());
419 } catch (AttachmentInvalidException e
) {
420 throw new Error
.AttachmentInvalid(e
.getMessage());
425 public long sendGroupMessageReaction(
427 final boolean remove
,
428 final String targetAuthor
,
429 final long targetSentTimestamp
,
433 final var results
= m
.sendMessageReaction(emoji
,
435 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
437 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
438 checkSendMessageResults(results
.timestamp(), results
.results());
439 return results
.timestamp();
440 } catch (IOException e
) {
441 throw new Error
.Failure(e
.getMessage());
442 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
443 throw new Error
.GroupNotFound(e
.getMessage());
447 // Since contact names might be empty if not defined, also potentially return
450 public String
getContactName(final String number
) {
451 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
452 return name
== null ?
"" : name
;
456 public void setContactName(final String number
, final String name
) {
458 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
459 } catch (NotMasterDeviceException e
) {
460 throw new Error
.Failure("This command doesn't work on linked devices.");
461 } catch (IOException e
) {
462 throw new Error
.Failure("Contact is not registered.");
467 public void setExpirationTimer(final String number
, final int expiration
) {
469 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
470 } catch (IOException e
) {
471 throw new Error
.Failure(e
.getMessage());
476 public void setContactBlocked(final String number
, final boolean blocked
) {
478 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
479 } catch (NotMasterDeviceException e
) {
480 throw new Error
.Failure("This command doesn't work on linked devices.");
481 } catch (IOException e
) {
482 throw new Error
.Failure(e
.getMessage());
487 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
489 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
490 } catch (NotMasterDeviceException e
) {
491 throw new Error
.Failure("This command doesn't work on linked devices.");
492 } catch (GroupNotFoundException e
) {
493 throw new Error
.GroupNotFound(e
.getMessage());
494 } catch (IOException e
) {
495 throw new Error
.Failure(e
.getMessage());
500 public List
<byte[]> getGroupIds() {
501 var groups
= m
.getGroups();
502 var ids
= new ArrayList
<byte[]>(groups
.size());
503 for (var group
: groups
) {
504 ids
.add(group
.groupId().serialize());
510 public DBusPath
getGroup(final byte[] groupId
) {
512 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
513 if (groupOptional
.isEmpty()) {
514 throw new Error
.GroupNotFound("Group not found");
516 return groupOptional
.get().getObjectPath();
520 public List
<StructGroup
> listGroups() {
526 public String
getGroupName(final byte[] groupId
) {
527 var group
= m
.getGroup(getGroupId(groupId
));
528 if (group
== null || group
.title() == null) {
531 return group
.title();
536 public List
<String
> getGroupMembers(final byte[] groupId
) {
537 var group
= m
.getGroup(getGroupId(groupId
));
541 final var members
= group
.members();
542 return getRecipientStrings(members
);
547 public byte[] createGroup(
548 final String name
, final List
<String
> members
, final String avatar
549 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
550 return updateGroup(new byte[0], name
, members
, avatar
);
554 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
556 groupId
= nullIfEmpty(groupId
);
557 name
= nullIfEmpty(name
);
558 avatar
= nullIfEmpty(avatar
);
559 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
560 if (groupId
== null) {
561 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
562 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
563 return results
.first().serialize();
565 final var results
= m
.updateGroup(getGroupId(groupId
),
566 UpdateGroup
.newBuilder()
568 .withMembers(memberIdentifiers
)
569 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
571 if (results
!= null) {
572 checkSendMessageResults(results
.timestamp(), results
.results());
576 } catch (IOException e
) {
577 throw new Error
.Failure(e
.getMessage());
578 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
579 throw new Error
.GroupNotFound(e
.getMessage());
580 } catch (AttachmentInvalidException e
) {
581 throw new Error
.AttachmentInvalid(e
.getMessage());
586 public boolean isRegistered() {
591 public boolean isRegistered(String number
) {
592 var result
= isRegistered(List
.of(number
));
593 return result
.get(0);
597 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
598 var results
= new ArrayList
<Boolean
>();
599 if (numbers
.isEmpty()) {
603 Map
<String
, Pair
<String
, UUID
>> registered
;
605 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
606 } catch (IOException e
) {
607 throw new Error
.Failure(e
.getMessage());
610 return numbers
.stream().map(number
-> {
611 var uuid
= registered
.get(number
).second();
613 }).collect(Collectors
.toList());
617 public void updateProfile(
623 final boolean removeAvatar
626 givenName
= nullIfEmpty(givenName
);
627 familyName
= nullIfEmpty(familyName
);
628 about
= nullIfEmpty(about
);
629 aboutEmoji
= nullIfEmpty(aboutEmoji
);
630 avatarPath
= nullIfEmpty(avatarPath
);
631 Optional
<File
> avatarFile
= removeAvatar
633 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
634 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
635 } catch (IOException e
) {
636 throw new Error
.Failure(e
.getMessage());
641 public void updateProfile(
644 final String aboutEmoji
,
646 final boolean removeAvatar
648 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
652 public void removePin() {
654 m
.setRegistrationLockPin(Optional
.empty());
655 } catch (IOException e
) {
656 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
661 public void setPin(String registrationLockPin
) {
663 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
664 } catch (IOException e
) {
665 throw new Error
.Failure("Set pin error: " + e
.getMessage());
669 // Provide option to query a version string in order to react on potential
670 // future interface changes
672 public String
version() {
673 return BaseConfig
.PROJECT_VERSION
;
676 // Create a unique list of Numbers from Identities and Contacts to really get
677 // all numbers the system knows
679 public List
<String
> listNumbers() {
680 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
681 m
.getContacts().stream().map(Pair
::first
))
682 .map(a
-> a
.number().orElse(null))
683 .filter(Objects
::nonNull
)
685 .collect(Collectors
.toList());
689 public List
<String
> getContactNumber(final String name
) {
690 // Contact names have precedence.
691 var numbers
= new ArrayList
<String
>();
692 var contacts
= m
.getContacts();
693 for (var c
: contacts
) {
694 if (name
.equals(c
.second().getName())) {
695 numbers
.add(c
.first().getLegacyIdentifier());
698 // Try profiles if no contact name was found
699 for (var identity
: m
.getIdentities()) {
700 final var address
= identity
.recipient();
701 var number
= address
.number().orElse(null);
702 if (number
!= null) {
703 Profile profile
= null;
705 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
706 } catch (IOException ignored
) {
708 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
717 public void quitGroup(final byte[] groupId
) {
718 var group
= getGroupId(groupId
);
720 m
.quitGroup(group
, Set
.of());
721 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
722 throw new Error
.GroupNotFound(e
.getMessage());
723 } catch (IOException
| LastGroupAdminException e
) {
724 throw new Error
.Failure(e
.getMessage());
729 public byte[] joinGroup(final String groupLink
) {
731 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
732 if (linkUrl
== null) {
733 throw new Error
.Failure("Group link is invalid:");
735 final var result
= m
.joinGroup(linkUrl
);
736 return result
.first().serialize();
737 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
738 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
739 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
740 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
741 } catch (IOException e
) {
742 throw new Error
.Failure(e
.getMessage());
747 public boolean isContactBlocked(final String number
) {
748 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
752 public boolean isGroupBlocked(final byte[] groupId
) {
753 var group
= m
.getGroup(getGroupId(groupId
));
757 return group
.isBlocked();
762 public boolean isMember(final byte[] groupId
) {
763 var group
= m
.getGroup(getGroupId(groupId
));
767 return group
.isMember();
772 public String
uploadStickerPack(String stickerPackPath
) {
773 File path
= new File(stickerPackPath
);
775 return m
.uploadStickerPack(path
).toString();
776 } catch (IOException e
) {
777 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
778 } catch (StickerPackInvalidException e
) {
779 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
783 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
784 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
790 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
792 if (result
.isIdentityFailure()) {
793 throw new Error
.UntrustedIdentity(message
);
795 throw new Error
.Failure(message
);
799 private static void checkSendMessageResults(
800 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
801 ) throws DBusExecutionException
{
802 final var sendMessageResults
= results
.values().stream().findFirst();
803 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
804 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
808 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
809 if (errors
.size() == 0) {
813 var message
= new StringBuilder();
814 message
.append(timestamp
).append('\n');
815 message
.append("Failed to send (some) messages:\n");
816 for (var error
: errors
) {
817 message
.append(error
).append('\n');
820 throw new Error
.Failure(message
.toString());
823 private static void checkSendMessageResults(
824 long timestamp
, Collection
<SendMessageResult
> results
825 ) throws DBusExecutionException
{
826 if (results
.size() == 1) {
827 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
831 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
832 if (errors
.size() == 0) {
836 var message
= new StringBuilder();
837 message
.append(timestamp
).append('\n');
838 message
.append("Failed to send (some) messages:\n");
839 for (var error
: errors
) {
840 message
.append(error
).append('\n');
843 throw new Error
.Failure(message
.toString());
846 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
847 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).collect(Collectors
.toList());
850 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
851 final Collection
<String
> recipientStrings
, final String localNumber
852 ) throws DBusExecutionException
{
853 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
854 for (var recipientString
: recipientStrings
) {
855 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
860 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
861 final String recipientString
, final String localNumber
862 ) throws DBusExecutionException
{
864 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
865 } catch (InvalidNumberException e
) {
866 throw new Error
.InvalidNumber(e
.getMessage());
870 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
872 return GroupId
.unknownVersion(groupId
);
873 } catch (Throwable e
) {
874 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
878 private byte[] nullIfEmpty(final byte[] array
) {
879 return array
.length
== 0 ?
null : array
;
882 private String
nullIfEmpty(final String name
) {
883 return name
.isEmpty() ?
null : name
;
886 private String
emptyIfNull(final String string
) {
887 return string
== null ?
"" : string
;
890 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
891 return basePath
+ "/Devices/" + deviceId
;
894 private void updateDevices() {
895 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
897 linkedDevices
= m
.getLinkedDevices();
898 } catch (IOException e
) {
899 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
904 linkedDevices
.forEach(d
-> {
905 final var object
= new DbusSignalDeviceImpl(d
);
906 final var deviceObjectPath
= object
.getObjectPath();
907 exportObject(object
);
908 if (d
.isThisDevice()) {
909 thisDevice
= new DBusPath(deviceObjectPath
);
911 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
915 private void unExportDevices() {
916 this.devices
.stream()
917 .map(StructDevice
::getObjectPath
)
918 .map(DBusPath
::getPath
)
919 .forEach(connection
::unExportObject
);
920 this.devices
.clear();
923 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
924 return basePath
+ "/Groups/" + Base64
.getEncoder()
925 .encodeToString(groupId
)
931 private void updateGroups() {
932 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
933 groups
= m
.getGroups();
937 groups
.forEach(g
-> {
938 final var object
= new DbusSignalGroupImpl(g
.groupId());
939 exportObject(object
);
940 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
941 g
.groupId().serialize(),
942 emptyIfNull(g
.title())));
946 private void unExportGroups() {
947 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
951 private static String
getConfigurationObjectPath(String basePath
) {
952 return basePath
+ "/Configuration";
955 private void updateConfiguration() {
956 unExportConfiguration();
957 final var object
= new DbusSignalConfigurationImpl();
958 exportObject(object
);
961 private void unExportConfiguration() {
962 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
963 connection
.unExportObject(objectPath
);
966 private void exportObject(final DBusInterface object
) {
968 connection
.exportObject(object
);
969 logger
.debug("Exported dbus object: " + object
.getObjectPath());
970 } catch (DBusException e
) {
975 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
977 private final org
.asamk
.signal
.manager
.api
.Device device
;
979 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
980 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
981 List
.of(new DbusProperty
<>("Id", device
::id
),
982 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
983 new DbusProperty
<>("Created", device
::created
),
984 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
985 this.device
= device
;
989 public String
getObjectPath() {
990 return getDeviceObjectPath(objectPath
, device
.id());
994 public void removeDevice() throws Error
.Failure
{
996 m
.removeLinkedDevices(device
.id());
998 } catch (IOException e
) {
999 throw new Error
.Failure(e
.getMessage());
1003 private void setDeviceName(String name
) {
1004 if (!device
.isThisDevice()) {
1005 throw new Error
.Failure("Only the name of this device can be changed");
1008 m
.updateAccountAttributes(name
);
1009 // update device list
1011 } catch (IOException e
) {
1012 throw new Error
.Failure(e
.getMessage());
1017 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1019 public DbusSignalConfigurationImpl(
1021 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1022 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1023 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1024 this::getUnidentifiedDeliveryIndicators
,
1025 this::setUnidentifiedDeliveryIndicators
),
1026 new DbusProperty
<>("TypingIndicators",
1027 this::getTypingIndicators
,
1028 this::setTypingIndicators
),
1029 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1034 public String
getObjectPath() {
1035 return getConfigurationObjectPath(objectPath
);
1038 public void setReadReceipts(Boolean readReceipts
) {
1039 setConfiguration(readReceipts
, null, null, null);
1042 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1043 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1046 public void setTypingIndicators(Boolean typingIndicators
) {
1047 setConfiguration(null, null, typingIndicators
, null);
1050 public void setLinkPreviews(Boolean linkPreviews
) {
1051 setConfiguration(null, null, null, linkPreviews
);
1054 private void setConfiguration(
1055 Boolean readReceipts
,
1056 Boolean unidentifiedDeliveryIndicators
,
1057 Boolean typingIndicators
,
1058 Boolean linkPreviews
1061 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1062 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1063 Optional
.ofNullable(typingIndicators
),
1064 Optional
.ofNullable(linkPreviews
)));
1065 } catch (IOException e
) {
1066 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1067 } catch (NotMasterDeviceException e
) {
1068 throw new Error
.Failure("This command doesn't work on linked devices.");
1072 private boolean getReadReceipts() {
1073 return m
.getConfiguration().readReceipts().orElse(false);
1076 private boolean getUnidentifiedDeliveryIndicators() {
1077 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1080 private boolean getTypingIndicators() {
1081 return m
.getConfiguration().typingIndicators().orElse(false);
1084 private boolean getLinkPreviews() {
1085 return m
.getConfiguration().linkPreviews().orElse(false);
1089 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1091 private final GroupId groupId
;
1093 public DbusSignalGroupImpl(final GroupId groupId
) {
1094 this.groupId
= groupId
;
1095 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1096 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1097 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1098 new DbusProperty
<>("Description",
1099 () -> emptyIfNull(getGroup().description()),
1100 this::setGroupDescription
),
1101 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1102 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1103 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1104 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1105 new DbusProperty
<>("MessageExpirationTimer",
1106 () -> getGroup().messageExpirationTimer(),
1107 this::setMessageExpirationTime
),
1108 new DbusProperty
<>("Members",
1109 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1110 new DbusProperty
<>("PendingMembers",
1111 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1112 new DbusProperty
<>("RequestingMembers",
1113 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1114 new DbusProperty
<>("Admins",
1115 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1116 new DbusProperty
<>("PermissionAddMember",
1117 () -> getGroup().permissionAddMember().name(),
1118 this::setGroupPermissionAddMember
),
1119 new DbusProperty
<>("PermissionEditDetails",
1120 () -> getGroup().permissionEditDetails().name(),
1121 this::setGroupPermissionEditDetails
),
1122 new DbusProperty
<>("PermissionSendMessage",
1123 () -> getGroup().permissionSendMessage().name(),
1124 this::setGroupPermissionSendMessage
),
1125 new DbusProperty
<>("GroupInviteLink", () -> {
1126 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1127 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1132 public String
getObjectPath() {
1133 return getGroupObjectPath(objectPath
, groupId
.serialize());
1137 public void quitGroup() throws Error
.Failure
{
1139 m
.quitGroup(groupId
, Set
.of());
1140 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1141 throw new Error
.GroupNotFound(e
.getMessage());
1142 } catch (IOException e
) {
1143 throw new Error
.Failure(e
.getMessage());
1144 } catch (LastGroupAdminException e
) {
1145 throw new Error
.LastGroupAdmin(e
.getMessage());
1150 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1151 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1152 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1156 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1157 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1158 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1162 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1163 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1164 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1168 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1169 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1170 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1174 public void resetLink() throws Error
.Failure
{
1175 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1179 public void disableLink() throws Error
.Failure
{
1180 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1184 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1185 updateGroup(UpdateGroup
.newBuilder()
1186 .withGroupLinkState(requiresApproval
1187 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1188 : GroupLinkState
.ENABLED
)
1192 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1193 return m
.getGroup(groupId
);
1196 private void setGroupName(final String name
) {
1197 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1200 private void setGroupDescription(final String description
) {
1201 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1204 private void setGroupAvatar(final String avatar
) {
1205 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1208 private void setMessageExpirationTime(final int expirationTime
) {
1209 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1212 private void setGroupPermissionAddMember(final String permission
) {
1213 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1216 private void setGroupPermissionEditDetails(final String permission
) {
1217 updateGroup(UpdateGroup
.newBuilder()
1218 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1222 private void setGroupPermissionSendMessage(final String permission
) {
1223 updateGroup(UpdateGroup
.newBuilder()
1224 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1228 private void setIsBlocked(final boolean isBlocked
) {
1230 m
.setGroupBlocked(groupId
, isBlocked
);
1231 } catch (NotMasterDeviceException e
) {
1232 throw new Error
.Failure("This command doesn't work on linked devices.");
1233 } catch (GroupNotFoundException e
) {
1234 throw new Error
.GroupNotFound(e
.getMessage());
1235 } catch (IOException e
) {
1236 throw new Error
.Failure(e
.getMessage());
1240 private void updateGroup(final UpdateGroup updateGroup
) {
1242 m
.updateGroup(groupId
, updateGroup
);
1243 } catch (IOException e
) {
1244 throw new Error
.Failure(e
.getMessage());
1245 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1246 throw new Error
.GroupNotFound(e
.getMessage());
1247 } catch (AttachmentInvalidException e
) {
1248 throw new Error
.AttachmentInvalid(e
.getMessage());