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
.SendMessageResults
;
18 import org
.asamk
.signal
.manager
.api
.TypingAction
;
19 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
20 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
21 import org
.asamk
.signal
.manager
.groups
.GroupId
;
22 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
23 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
24 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
25 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
26 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
27 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
28 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
29 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
30 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
31 import org
.asamk
.signal
.util
.SendMessageResultUtils
;
32 import org
.freedesktop
.dbus
.DBusPath
;
33 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
35 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
36 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
37 import org
.freedesktop
.dbus
.types
.Variant
;
38 import org
.slf4j
.Logger
;
39 import org
.slf4j
.LoggerFactory
;
42 import java
.io
.IOException
;
44 import java
.net
.URISyntaxException
;
45 import java
.util
.ArrayList
;
46 import java
.util
.Arrays
;
47 import java
.util
.Base64
;
48 import java
.util
.Collection
;
49 import java
.util
.HashSet
;
50 import java
.util
.List
;
52 import java
.util
.Objects
;
53 import java
.util
.Optional
;
55 import java
.util
.UUID
;
56 import java
.util
.stream
.Collectors
;
57 import java
.util
.stream
.Stream
;
59 public class DbusSignalImpl
implements Signal
{
61 private final Manager m
;
62 private final DBusConnection connection
;
63 private final String objectPath
;
64 private final boolean noReceiveOnStart
;
66 private DBusPath thisDevice
;
67 private final List
<StructDevice
> devices
= new ArrayList
<>();
68 private final List
<StructGroup
> groups
= new ArrayList
<>();
69 private DbusReceiveMessageHandler dbusMessageHandler
;
70 private int subscriberCount
;
72 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
74 public DbusSignalImpl(
75 final Manager m
, DBusConnection connection
, final String objectPath
, final boolean noReceiveOnStart
78 this.connection
= connection
;
79 this.objectPath
= objectPath
;
80 this.noReceiveOnStart
= noReceiveOnStart
;
83 public void initObjects() {
84 if (!noReceiveOnStart
) {
90 updateConfiguration();
94 if (dbusMessageHandler
!= null) {
95 m
.removeReceiveHandler(dbusMessageHandler
);
96 dbusMessageHandler
= null;
100 unExportConfiguration();
104 public String
getObjectPath() {
109 public String
getSelfNumber() {
110 return m
.getSelfNumber();
114 public void subscribeReceive() {
115 if (dbusMessageHandler
== null) {
116 dbusMessageHandler
= new DbusReceiveMessageHandler(connection
, objectPath
);
117 m
.addReceiveHandler(dbusMessageHandler
);
123 public void unsubscribeReceive() {
124 subscriberCount
= Math
.max(0, subscriberCount
- 1);
125 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
126 m
.removeReceiveHandler(dbusMessageHandler
);
127 dbusMessageHandler
= null;
132 public void submitRateLimitChallenge(String challenge
, String captcha
) {
134 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
135 } catch (IOException e
) {
136 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
142 public void unregister() throws Error
.Failure
{
145 } catch (IOException e
) {
146 throw new Error
.Failure("Failed to unregister: " + e
.getMessage());
151 public void deleteAccount() throws Error
.Failure
{
154 } catch (IOException e
) {
155 throw new Error
.Failure("Failed to delete account: " + e
.getMessage());
160 public void addDevice(String uri
) {
162 m
.addDeviceLink(new URI(uri
));
163 } catch (IOException
| InvalidDeviceLinkException e
) {
164 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
165 } catch (URISyntaxException e
) {
166 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
167 + " Device link uri has invalid format: "
173 public DBusPath
getDevice(long deviceId
) {
175 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
176 if (deviceOptional
.isEmpty()) {
177 throw new Error
.DeviceNotFound("Device not found");
179 return deviceOptional
.get().getObjectPath();
183 public List
<StructDevice
> listDevices() {
189 public DBusPath
getThisDevice() {
195 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
196 return sendMessage(message
, attachments
, List
.of(recipient
));
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
);
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());
215 } catch (UnregisteredRecipientException e
) {
216 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
221 public long sendRemoteDeleteMessage(
222 final long targetSentTimestamp
, final String recipient
224 return sendRemoteDeleteMessage(targetSentTimestamp
, List
.of(recipient
));
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
);
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 sendMessageReaction(
248 final boolean remove
,
249 final String targetAuthor
,
250 final long targetSentTimestamp
,
251 final String recipient
253 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, List
.of(recipient
));
257 public long sendMessageReaction(
259 final boolean remove
,
260 final String targetAuthor
,
261 final long targetSentTimestamp
,
262 final List
<String
> recipients
265 final var results
= m
.sendMessageReaction(emoji
,
267 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
269 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
270 .map(RecipientIdentifier
.class::cast
)
271 .collect(Collectors
.toSet()));
272 checkSendMessageResults(results
);
273 return results
.timestamp();
274 } catch (IOException e
) {
275 throw new Error
.Failure(e
.getMessage());
276 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
277 throw new Error
.GroupNotFound(e
.getMessage());
278 } catch (UnregisteredRecipientException e
) {
279 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
284 public void sendTyping(
285 final String recipient
, final boolean stop
286 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
288 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
289 getSingleRecipientIdentifiers(List
.of(recipient
), m
.getSelfNumber()).stream()
290 .map(RecipientIdentifier
.class::cast
)
291 .collect(Collectors
.toSet()));
292 checkSendMessageResults(results
);
293 } catch (IOException e
) {
294 throw new Error
.Failure(e
.getMessage());
295 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
296 throw new Error
.GroupNotFound(e
.getMessage());
301 public void sendReadReceipt(
302 final String recipient
, final List
<Long
> messageIds
303 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
305 final var results
= m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
307 checkSendMessageResults(results
);
308 } catch (IOException e
) {
309 throw new Error
.Failure(e
.getMessage());
314 public void sendViewedReceipt(
315 final String recipient
, final List
<Long
> messageIds
316 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
318 final var results
= m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()),
320 checkSendMessageResults(results
);
321 } catch (IOException e
) {
322 throw new Error
.Failure(e
.getMessage());
327 public void sendContacts() {
330 } catch (IOException e
) {
331 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
336 public void sendSyncRequest() {
338 m
.requestAllSyncData();
339 } catch (IOException e
) {
340 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
345 public long sendNoteToSelfMessage(
346 final String message
, final List
<String
> attachments
347 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
349 final var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
350 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
351 checkSendMessageResults(results
);
352 return results
.timestamp();
353 } catch (AttachmentInvalidException e
) {
354 throw new Error
.AttachmentInvalid(e
.getMessage());
355 } catch (IOException e
) {
356 throw new Error
.Failure(e
.getMessage());
357 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
358 throw new Error
.GroupNotFound(e
.getMessage());
359 } catch (UnregisteredRecipientException e
) {
360 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
365 public void sendEndSessionMessage(final List
<String
> recipients
) {
367 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
368 checkSendMessageResults(results
);
369 } catch (IOException e
) {
370 throw new Error
.Failure(e
.getMessage());
375 public void deleteRecipient(final String recipient
) throws Error
.Failure
{
376 m
.deleteRecipient(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
380 public void deleteContact(final String recipient
) throws Error
.Failure
{
381 m
.deleteContact(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()));
385 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
387 var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
388 Set
.of(getGroupRecipientIdentifier(groupId
)));
389 checkSendMessageResults(results
);
390 return results
.timestamp();
391 } catch (IOException e
) {
392 throw new Error
.Failure(e
.getMessage());
393 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
394 throw new Error
.GroupNotFound(e
.getMessage());
395 } catch (AttachmentInvalidException e
) {
396 throw new Error
.AttachmentInvalid(e
.getMessage());
397 } catch (UnregisteredRecipientException e
) {
398 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
403 public void sendGroupTyping(
404 final byte[] groupId
, final boolean stop
405 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
407 final var results
= m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
408 Set
.of(getGroupRecipientIdentifier(groupId
)));
409 checkSendMessageResults(results
);
410 } catch (IOException e
) {
411 throw new Error
.Failure(e
.getMessage());
412 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
413 throw new Error
.GroupNotFound(e
.getMessage());
418 public long sendGroupRemoteDeleteMessage(
419 final long targetSentTimestamp
, final byte[] groupId
422 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
423 Set
.of(getGroupRecipientIdentifier(groupId
)));
424 checkSendMessageResults(results
);
425 return results
.timestamp();
426 } catch (IOException e
) {
427 throw new Error
.Failure(e
.getMessage());
428 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
429 throw new Error
.GroupNotFound(e
.getMessage());
434 public long sendGroupMessageReaction(
436 final boolean remove
,
437 final String targetAuthor
,
438 final long targetSentTimestamp
,
442 final var results
= m
.sendMessageReaction(emoji
,
444 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
446 Set
.of(getGroupRecipientIdentifier(groupId
)));
447 checkSendMessageResults(results
);
448 return results
.timestamp();
449 } catch (IOException e
) {
450 throw new Error
.Failure(e
.getMessage());
451 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
452 throw new Error
.GroupNotFound(e
.getMessage());
453 } catch (UnregisteredRecipientException e
) {
454 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
458 // Since contact names might be empty if not defined, also potentially return
461 public String
getContactName(final String number
) {
462 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
463 return name
== null ?
"" : name
;
467 public void setContactName(final String number
, final String name
) {
469 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
470 } catch (NotMasterDeviceException e
) {
471 throw new Error
.Failure("This command doesn't work on linked devices.");
472 } catch (IOException e
) {
473 throw new Error
.Failure("Contact is not registered.");
474 } catch (UnregisteredRecipientException e
) {
475 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
480 public void setExpirationTimer(final String number
, final int expiration
) {
482 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
483 } catch (IOException e
) {
484 throw new Error
.Failure(e
.getMessage());
485 } catch (UnregisteredRecipientException e
) {
486 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
491 public void setContactBlocked(final String number
, final boolean blocked
) {
493 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
494 } catch (NotMasterDeviceException e
) {
495 throw new Error
.Failure("This command doesn't work on linked devices.");
496 } catch (IOException e
) {
497 throw new Error
.Failure(e
.getMessage());
498 } catch (UnregisteredRecipientException e
) {
499 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
504 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
506 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
507 } catch (NotMasterDeviceException e
) {
508 throw new Error
.Failure("This command doesn't work on linked devices.");
509 } catch (GroupNotFoundException e
) {
510 throw new Error
.GroupNotFound(e
.getMessage());
511 } catch (IOException e
) {
512 throw new Error
.Failure(e
.getMessage());
517 public List
<byte[]> getGroupIds() {
518 var groups
= m
.getGroups();
519 return groups
.stream().map(g
-> g
.groupId().serialize()).toList();
523 public DBusPath
getGroup(final byte[] groupId
) {
525 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
526 if (groupOptional
.isEmpty()) {
527 throw new Error
.GroupNotFound("Group not found");
529 return groupOptional
.get().getObjectPath();
533 public List
<StructGroup
> listGroups() {
539 public String
getGroupName(final byte[] groupId
) {
540 var group
= m
.getGroup(getGroupId(groupId
));
541 if (group
== null || group
.title() == null) {
544 return group
.title();
549 public List
<String
> getGroupMembers(final byte[] groupId
) {
550 var group
= m
.getGroup(getGroupId(groupId
));
554 final var members
= group
.members();
555 return getRecipientStrings(members
);
560 public byte[] createGroup(
561 final String name
, final List
<String
> members
, final String avatar
562 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
563 return updateGroup(new byte[0], name
, members
, avatar
);
567 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
569 groupId
= nullIfEmpty(groupId
);
570 name
= nullIfEmpty(name
);
571 avatar
= nullIfEmpty(avatar
);
572 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
573 if (groupId
== null) {
574 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
576 checkGroupSendMessageResults(results
.second().timestamp(), results
.second().results());
577 return results
.first().serialize();
579 final var results
= m
.updateGroup(getGroupId(groupId
),
580 UpdateGroup
.newBuilder()
582 .withMembers(memberIdentifiers
)
583 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
585 if (results
!= null) {
586 checkGroupSendMessageResults(results
.timestamp(), results
.results());
590 } catch (IOException e
) {
591 throw new Error
.Failure(e
.getMessage());
592 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
593 throw new Error
.GroupNotFound(e
.getMessage());
594 } catch (AttachmentInvalidException e
) {
595 throw new Error
.AttachmentInvalid(e
.getMessage());
596 } catch (UnregisteredRecipientException e
) {
597 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
602 public boolean isRegistered() {
607 public boolean isRegistered(String number
) {
608 var result
= isRegistered(List
.of(number
));
609 return result
.get(0);
613 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
614 if (numbers
.isEmpty()) {
618 Map
<String
, Pair
<String
, UUID
>> registered
;
620 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
621 } catch (IOException e
) {
622 throw new Error
.Failure(e
.getMessage());
625 return numbers
.stream().map(number
-> {
626 var uuid
= registered
.get(number
).second();
632 public void updateProfile(
638 final boolean removeAvatar
641 givenName
= nullIfEmpty(givenName
);
642 familyName
= nullIfEmpty(familyName
);
643 about
= nullIfEmpty(about
);
644 aboutEmoji
= nullIfEmpty(aboutEmoji
);
645 avatarPath
= nullIfEmpty(avatarPath
);
646 Optional
<File
> avatarFile
= removeAvatar
648 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
649 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
650 } catch (IOException e
) {
651 throw new Error
.Failure(e
.getMessage());
656 public void updateProfile(
659 final String aboutEmoji
,
661 final boolean removeAvatar
663 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
667 public void removePin() {
669 m
.setRegistrationLockPin(Optional
.empty());
670 } catch (IOException e
) {
671 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
676 public void setPin(String registrationLockPin
) {
678 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
679 } catch (IOException e
) {
680 throw new Error
.Failure("Set pin error: " + e
.getMessage());
684 // Provide option to query a version string in order to react on potential
685 // future interface changes
687 public String
version() {
688 return BaseConfig
.PROJECT_VERSION
;
691 // Create a unique list of Numbers from Identities and Contacts to really get
692 // all numbers the system knows
694 public List
<String
> listNumbers() {
695 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
696 m
.getContacts().stream().map(Pair
::first
))
697 .map(a
-> a
.number().orElse(null))
698 .filter(Objects
::nonNull
)
704 public List
<String
> getContactNumber(final String name
) {
705 // Contact names have precedence.
706 var numbers
= new ArrayList
<String
>();
707 var contacts
= m
.getContacts();
708 for (var c
: contacts
) {
709 if (name
.equals(c
.second().getName())) {
710 numbers
.add(c
.first().getLegacyIdentifier());
713 // Try profiles if no contact name was found
714 for (var identity
: m
.getIdentities()) {
715 final var address
= identity
.recipient();
716 var number
= address
.number().orElse(null);
717 if (number
!= null) {
718 Profile profile
= null;
720 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
721 } catch (IOException
| UnregisteredRecipientException ignored
) {
723 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
732 public void quitGroup(final byte[] groupId
) {
733 var group
= getGroupId(groupId
);
735 m
.quitGroup(group
, Set
.of());
736 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
737 throw new Error
.GroupNotFound(e
.getMessage());
738 } catch (IOException
| LastGroupAdminException e
) {
739 throw new Error
.Failure(e
.getMessage());
740 } catch (UnregisteredRecipientException e
) {
741 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
746 public byte[] joinGroup(final String groupLink
) {
748 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
749 if (linkUrl
== null) {
750 throw new Error
.Failure("Group link is invalid:");
752 final var result
= m
.joinGroup(linkUrl
);
753 return result
.first().serialize();
754 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
755 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
756 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
757 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
758 } catch (IOException e
) {
759 throw new Error
.Failure(e
.getMessage());
764 public boolean isContactBlocked(final String number
) {
765 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
769 public boolean isGroupBlocked(final byte[] groupId
) {
770 var group
= m
.getGroup(getGroupId(groupId
));
774 return group
.isBlocked();
779 public boolean isMember(final byte[] groupId
) {
780 var group
= m
.getGroup(getGroupId(groupId
));
784 return group
.isMember();
789 public String
uploadStickerPack(String stickerPackPath
) {
790 File path
= new File(stickerPackPath
);
792 return m
.uploadStickerPack(path
).toString();
793 } catch (IOException e
) {
794 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
795 } catch (StickerPackInvalidException e
) {
796 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
800 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
801 var error
= SendMessageResultUtils
.getErrorMessageFromSendMessageResult(result
);
807 final var message
= "\nFailed to send message:\n" + error
+ '\n' + timestamp
;
809 if (result
.isIdentityFailure()) {
810 throw new Error
.UntrustedIdentity(message
);
812 throw new Error
.Failure(message
);
816 private void checkSendMessageResults(final SendMessageResults results
) {
817 final var sendMessageResults
= results
.results().values().stream().findFirst();
818 if (results
.results().size() == 1 && sendMessageResults
.get().size() == 1) {
819 checkSendMessageResult(results
.timestamp(), sendMessageResults
.get().stream().findFirst().get());
823 if (results
.hasSuccess()) {
827 var message
= new StringBuilder();
828 message
.append("Failed to send messages:\n");
829 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
.results());
830 for (var error
: errors
) {
831 message
.append(error
).append('\n');
833 message
.append(results
.timestamp());
835 throw new Error
.Failure(message
.toString());
838 private static void checkGroupSendMessageResults(
839 long timestamp
, Collection
<SendMessageResult
> results
840 ) throws DBusExecutionException
{
841 if (results
.size() == 1) {
842 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
846 var errors
= SendMessageResultUtils
.getErrorMessagesFromSendMessageResults(results
);
847 if (errors
.size() < results
.size()) {
851 var message
= new StringBuilder();
852 message
.append("Failed to send message:\n");
853 for (var error
: errors
) {
854 message
.append(error
).append('\n');
856 message
.append(timestamp
);
858 throw new Error
.Failure(message
.toString());
861 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
862 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).toList();
865 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
866 final Collection
<String
> recipientStrings
, final String localNumber
867 ) throws DBusExecutionException
{
868 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
869 for (var recipientString
: recipientStrings
) {
870 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
875 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
876 final String recipientString
, final String localNumber
877 ) throws DBusExecutionException
{
879 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
880 } catch (InvalidNumberException e
) {
881 throw new Error
.InvalidNumber(e
.getMessage());
885 private RecipientIdentifier
.Group
getGroupRecipientIdentifier(final byte[] groupId
) {
886 return new RecipientIdentifier
.Group(getGroupId(groupId
));
889 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
891 return GroupId
.unknownVersion(groupId
);
892 } catch (Throwable e
) {
893 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
897 private byte[] nullIfEmpty(final byte[] array
) {
898 return array
.length
== 0 ?
null : array
;
901 private String
nullIfEmpty(final String name
) {
902 return name
.isEmpty() ?
null : name
;
905 private String
emptyIfNull(final String string
) {
906 return string
== null ?
"" : string
;
909 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
910 return basePath
+ "/Devices/" + deviceId
;
913 private void updateDevices() {
914 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
916 linkedDevices
= m
.getLinkedDevices();
917 } catch (IOException e
) {
918 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
923 linkedDevices
.forEach(d
-> {
924 final var object
= new DbusSignalDeviceImpl(d
);
925 final var deviceObjectPath
= object
.getObjectPath();
926 exportObject(object
);
927 if (d
.isThisDevice()) {
928 thisDevice
= new DBusPath(deviceObjectPath
);
930 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
934 private void unExportDevices() {
935 this.devices
.stream()
936 .map(StructDevice
::getObjectPath
)
937 .map(DBusPath
::getPath
)
938 .forEach(connection
::unExportObject
);
939 this.devices
.clear();
942 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
943 return basePath
+ "/Groups/" + Base64
.getEncoder()
944 .encodeToString(groupId
)
950 private void updateGroups() {
951 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
952 groups
= m
.getGroups();
956 groups
.forEach(g
-> {
957 final var object
= new DbusSignalGroupImpl(g
.groupId());
958 exportObject(object
);
959 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
960 g
.groupId().serialize(),
961 emptyIfNull(g
.title())));
965 private void unExportGroups() {
966 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
970 private static String
getConfigurationObjectPath(String basePath
) {
971 return basePath
+ "/Configuration";
974 private void updateConfiguration() {
975 unExportConfiguration();
976 final var object
= new DbusSignalConfigurationImpl();
977 exportObject(object
);
980 private void unExportConfiguration() {
981 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
982 connection
.unExportObject(objectPath
);
985 private void exportObject(final DBusInterface object
) {
987 connection
.exportObject(object
);
988 logger
.debug("Exported dbus object: " + object
.getObjectPath());
989 } catch (DBusException e
) {
994 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
996 private final org
.asamk
.signal
.manager
.api
.Device device
;
998 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
999 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
1000 List
.of(new DbusProperty
<>("Id", device
::id
),
1001 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
1002 new DbusProperty
<>("Created", device
::created
),
1003 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
1004 this.device
= device
;
1008 public String
getObjectPath() {
1009 return getDeviceObjectPath(objectPath
, device
.id());
1013 public void removeDevice() throws Error
.Failure
{
1015 m
.removeLinkedDevices(device
.id());
1017 } catch (IOException e
) {
1018 throw new Error
.Failure(e
.getMessage());
1022 private void setDeviceName(String name
) {
1023 if (!device
.isThisDevice()) {
1024 throw new Error
.Failure("Only the name of this device can be changed");
1027 m
.updateAccountAttributes(name
);
1028 // update device list
1030 } catch (IOException e
) {
1031 throw new Error
.Failure(e
.getMessage());
1036 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1038 public DbusSignalConfigurationImpl(
1040 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1041 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1042 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1043 this::getUnidentifiedDeliveryIndicators
,
1044 this::setUnidentifiedDeliveryIndicators
),
1045 new DbusProperty
<>("TypingIndicators",
1046 this::getTypingIndicators
,
1047 this::setTypingIndicators
),
1048 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1053 public String
getObjectPath() {
1054 return getConfigurationObjectPath(objectPath
);
1057 public void setReadReceipts(Boolean readReceipts
) {
1058 setConfiguration(readReceipts
, null, null, null);
1061 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1062 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1065 public void setTypingIndicators(Boolean typingIndicators
) {
1066 setConfiguration(null, null, typingIndicators
, null);
1069 public void setLinkPreviews(Boolean linkPreviews
) {
1070 setConfiguration(null, null, null, linkPreviews
);
1073 private void setConfiguration(
1074 Boolean readReceipts
,
1075 Boolean unidentifiedDeliveryIndicators
,
1076 Boolean typingIndicators
,
1077 Boolean linkPreviews
1080 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1081 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1082 Optional
.ofNullable(typingIndicators
),
1083 Optional
.ofNullable(linkPreviews
)));
1084 } catch (IOException e
) {
1085 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1086 } catch (NotMasterDeviceException e
) {
1087 throw new Error
.Failure("This command doesn't work on linked devices.");
1091 private boolean getReadReceipts() {
1092 return m
.getConfiguration().readReceipts().orElse(false);
1095 private boolean getUnidentifiedDeliveryIndicators() {
1096 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1099 private boolean getTypingIndicators() {
1100 return m
.getConfiguration().typingIndicators().orElse(false);
1103 private boolean getLinkPreviews() {
1104 return m
.getConfiguration().linkPreviews().orElse(false);
1108 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1110 private final GroupId groupId
;
1112 public DbusSignalGroupImpl(final GroupId groupId
) {
1113 this.groupId
= groupId
;
1114 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1115 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1116 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1117 new DbusProperty
<>("Description",
1118 () -> emptyIfNull(getGroup().description()),
1119 this::setGroupDescription
),
1120 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1121 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1122 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1123 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1124 new DbusProperty
<>("MessageExpirationTimer",
1125 () -> getGroup().messageExpirationTimer(),
1126 this::setMessageExpirationTime
),
1127 new DbusProperty
<>("Members",
1128 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1129 new DbusProperty
<>("PendingMembers",
1130 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1131 new DbusProperty
<>("RequestingMembers",
1132 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1133 new DbusProperty
<>("Admins",
1134 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1135 new DbusProperty
<>("PermissionAddMember",
1136 () -> getGroup().permissionAddMember().name(),
1137 this::setGroupPermissionAddMember
),
1138 new DbusProperty
<>("PermissionEditDetails",
1139 () -> getGroup().permissionEditDetails().name(),
1140 this::setGroupPermissionEditDetails
),
1141 new DbusProperty
<>("PermissionSendMessage",
1142 () -> getGroup().permissionSendMessage().name(),
1143 this::setGroupPermissionSendMessage
),
1144 new DbusProperty
<>("GroupInviteLink", () -> {
1145 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1146 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1151 public String
getObjectPath() {
1152 return getGroupObjectPath(objectPath
, groupId
.serialize());
1156 public void quitGroup() throws Error
.Failure
{
1158 m
.quitGroup(groupId
, Set
.of());
1159 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1160 throw new Error
.GroupNotFound(e
.getMessage());
1161 } catch (IOException e
) {
1162 throw new Error
.Failure(e
.getMessage());
1163 } catch (LastGroupAdminException e
) {
1164 throw new Error
.LastGroupAdmin(e
.getMessage());
1165 } catch (UnregisteredRecipientException e
) {
1166 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");
1171 public void deleteGroup() throws Error
.Failure
, Error
.LastGroupAdmin
{
1173 m
.deleteGroup(groupId
);
1174 } catch (IOException e
) {
1175 throw new Error
.Failure(e
.getMessage());
1181 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1182 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1183 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1187 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1188 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1189 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1193 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1194 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1195 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1199 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1200 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1201 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1205 public void resetLink() throws Error
.Failure
{
1206 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1210 public void disableLink() throws Error
.Failure
{
1211 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1215 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1216 updateGroup(UpdateGroup
.newBuilder()
1217 .withGroupLinkState(requiresApproval
1218 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1219 : GroupLinkState
.ENABLED
)
1223 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1224 return m
.getGroup(groupId
);
1227 private void setGroupName(final String name
) {
1228 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1231 private void setGroupDescription(final String description
) {
1232 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1235 private void setGroupAvatar(final String avatar
) {
1236 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1239 private void setMessageExpirationTime(final int expirationTime
) {
1240 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1243 private void setGroupPermissionAddMember(final String permission
) {
1244 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1247 private void setGroupPermissionEditDetails(final String permission
) {
1248 updateGroup(UpdateGroup
.newBuilder()
1249 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1253 private void setGroupPermissionSendMessage(final String permission
) {
1254 updateGroup(UpdateGroup
.newBuilder()
1255 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1259 private void setIsBlocked(final boolean isBlocked
) {
1261 m
.setGroupBlocked(groupId
, isBlocked
);
1262 } catch (NotMasterDeviceException e
) {
1263 throw new Error
.Failure("This command doesn't work on linked devices.");
1264 } catch (GroupNotFoundException e
) {
1265 throw new Error
.GroupNotFound(e
.getMessage());
1266 } catch (IOException e
) {
1267 throw new Error
.Failure(e
.getMessage());
1271 private void updateGroup(final UpdateGroup updateGroup
) {
1273 m
.updateGroup(groupId
, updateGroup
);
1274 } catch (IOException e
) {
1275 throw new Error
.Failure(e
.getMessage());
1276 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1277 throw new Error
.GroupNotFound(e
.getMessage());
1278 } catch (AttachmentInvalidException e
) {
1279 throw new Error
.AttachmentInvalid(e
.getMessage());
1280 } catch (UnregisteredRecipientException e
) {
1281 throw new Error
.UntrustedIdentity(e
.getSender().getIdentifier() + " is not registered.");