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(m
, 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 long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
393 var results
= m
.sendMessage(new Message(message
, attachments
, List
.of(), Optional
.empty()),
394 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
395 checkSendMessageResults(results
.timestamp(), results
.results());
396 return results
.timestamp();
397 } catch (IOException e
) {
398 throw new Error
.Failure(e
.getMessage());
399 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
400 throw new Error
.GroupNotFound(e
.getMessage());
401 } catch (AttachmentInvalidException e
) {
402 throw new Error
.AttachmentInvalid(e
.getMessage());
407 public long sendGroupMessageReaction(
409 final boolean remove
,
410 final String targetAuthor
,
411 final long targetSentTimestamp
,
415 final var results
= m
.sendMessageReaction(emoji
,
417 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
419 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
420 checkSendMessageResults(results
.timestamp(), results
.results());
421 return results
.timestamp();
422 } catch (IOException e
) {
423 throw new Error
.Failure(e
.getMessage());
424 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
425 throw new Error
.GroupNotFound(e
.getMessage());
429 // Since contact names might be empty if not defined, also potentially return
432 public String
getContactName(final String number
) {
433 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
434 return name
== null ?
"" : name
;
438 public void setContactName(final String number
, final String name
) {
440 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
441 } catch (NotMasterDeviceException e
) {
442 throw new Error
.Failure("This command doesn't work on linked devices.");
443 } catch (IOException e
) {
444 throw new Error
.Failure("Contact is not registered.");
449 public void setExpirationTimer(final String number
, final int expiration
) {
451 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
452 } catch (IOException e
) {
453 throw new Error
.Failure(e
.getMessage());
458 public void setContactBlocked(final String number
, final boolean blocked
) {
460 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
461 } catch (NotMasterDeviceException e
) {
462 throw new Error
.Failure("This command doesn't work on linked devices.");
463 } catch (IOException e
) {
464 throw new Error
.Failure(e
.getMessage());
469 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
471 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
472 } catch (NotMasterDeviceException e
) {
473 throw new Error
.Failure("This command doesn't work on linked devices.");
474 } catch (GroupNotFoundException e
) {
475 throw new Error
.GroupNotFound(e
.getMessage());
476 } catch (IOException e
) {
477 throw new Error
.Failure(e
.getMessage());
482 public List
<byte[]> getGroupIds() {
483 var groups
= m
.getGroups();
484 var ids
= new ArrayList
<byte[]>(groups
.size());
485 for (var group
: groups
) {
486 ids
.add(group
.groupId().serialize());
492 public DBusPath
getGroup(final byte[] groupId
) {
494 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
495 if (groupOptional
.isEmpty()) {
496 throw new Error
.GroupNotFound("Group not found");
498 return groupOptional
.get().getObjectPath();
502 public List
<StructGroup
> listGroups() {
508 public String
getGroupName(final byte[] groupId
) {
509 var group
= m
.getGroup(getGroupId(groupId
));
510 if (group
== null || group
.title() == null) {
513 return group
.title();
518 public List
<String
> getGroupMembers(final byte[] groupId
) {
519 var group
= m
.getGroup(getGroupId(groupId
));
523 final var members
= group
.members();
524 return getRecipientStrings(members
);
529 public byte[] createGroup(
530 final String name
, final List
<String
> members
, final String avatar
531 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
532 return updateGroup(new byte[0], name
, members
, avatar
);
536 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
538 groupId
= nullIfEmpty(groupId
);
539 name
= nullIfEmpty(name
);
540 avatar
= nullIfEmpty(avatar
);
541 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
542 if (groupId
== null) {
543 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
544 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
545 return results
.first().serialize();
547 final var results
= m
.updateGroup(getGroupId(groupId
),
548 UpdateGroup
.newBuilder()
550 .withMembers(memberIdentifiers
)
551 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
553 if (results
!= null) {
554 checkSendMessageResults(results
.timestamp(), results
.results());
558 } catch (IOException e
) {
559 throw new Error
.Failure(e
.getMessage());
560 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
561 throw new Error
.GroupNotFound(e
.getMessage());
562 } catch (AttachmentInvalidException e
) {
563 throw new Error
.AttachmentInvalid(e
.getMessage());
568 public boolean isRegistered() {
573 public boolean isRegistered(String number
) {
574 var result
= isRegistered(List
.of(number
));
575 return result
.get(0);
579 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
580 var results
= new ArrayList
<Boolean
>();
581 if (numbers
.isEmpty()) {
585 Map
<String
, Pair
<String
, UUID
>> registered
;
587 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
588 } catch (IOException e
) {
589 throw new Error
.Failure(e
.getMessage());
592 return numbers
.stream().map(number
-> {
593 var uuid
= registered
.get(number
).second();
595 }).collect(Collectors
.toList());
599 public void updateProfile(
605 final boolean removeAvatar
608 givenName
= nullIfEmpty(givenName
);
609 familyName
= nullIfEmpty(familyName
);
610 about
= nullIfEmpty(about
);
611 aboutEmoji
= nullIfEmpty(aboutEmoji
);
612 avatarPath
= nullIfEmpty(avatarPath
);
613 Optional
<File
> avatarFile
= removeAvatar
615 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
616 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
617 } catch (IOException e
) {
618 throw new Error
.Failure(e
.getMessage());
623 public void updateProfile(
626 final String aboutEmoji
,
628 final boolean removeAvatar
630 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
634 public void removePin() {
636 m
.setRegistrationLockPin(Optional
.empty());
637 } catch (IOException e
) {
638 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
643 public void setPin(String registrationLockPin
) {
645 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
646 } catch (IOException e
) {
647 throw new Error
.Failure("Set pin error: " + e
.getMessage());
651 // Provide option to query a version string in order to react on potential
652 // future interface changes
654 public String
version() {
655 return BaseConfig
.PROJECT_VERSION
;
658 // Create a unique list of Numbers from Identities and Contacts to really get
659 // all numbers the system knows
661 public List
<String
> listNumbers() {
662 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
663 m
.getContacts().stream().map(Pair
::first
))
664 .map(a
-> a
.getNumber().orElse(null))
665 .filter(Objects
::nonNull
)
667 .collect(Collectors
.toList());
671 public List
<String
> getContactNumber(final String name
) {
672 // Contact names have precedence.
673 var numbers
= new ArrayList
<String
>();
674 var contacts
= m
.getContacts();
675 for (var c
: contacts
) {
676 if (name
.equals(c
.second().getName())) {
677 numbers
.add(c
.first().getLegacyIdentifier());
680 // Try profiles if no contact name was found
681 for (var identity
: m
.getIdentities()) {
682 final var address
= identity
.recipient();
683 var number
= address
.getNumber().orElse(null);
684 if (number
!= null) {
685 Profile profile
= null;
687 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
688 } catch (IOException ignored
) {
690 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
699 public void quitGroup(final byte[] groupId
) {
700 var group
= getGroupId(groupId
);
702 m
.quitGroup(group
, Set
.of());
703 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
704 throw new Error
.GroupNotFound(e
.getMessage());
705 } catch (IOException
| LastGroupAdminException e
) {
706 throw new Error
.Failure(e
.getMessage());
711 public byte[] joinGroup(final String groupLink
) {
713 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
714 if (linkUrl
== null) {
715 throw new Error
.Failure("Group link is invalid:");
717 final var result
= m
.joinGroup(linkUrl
);
718 return result
.first().serialize();
719 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
720 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
721 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
722 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
723 } catch (IOException e
) {
724 throw new Error
.Failure(e
.getMessage());
729 public boolean isContactBlocked(final String number
) {
730 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
734 public boolean isGroupBlocked(final byte[] groupId
) {
735 var group
= m
.getGroup(getGroupId(groupId
));
739 return group
.isBlocked();
744 public boolean isMember(final byte[] groupId
) {
745 var group
= m
.getGroup(getGroupId(groupId
));
749 return group
.isMember();
754 public String
uploadStickerPack(String stickerPackPath
) {
755 File path
= new File(stickerPackPath
);
757 return m
.uploadStickerPack(path
).toString();
758 } catch (IOException e
) {
759 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
760 } catch (StickerPackInvalidException e
) {
761 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
765 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
766 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
772 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
774 if (result
.isIdentityFailure()) {
775 throw new Error
.UntrustedIdentity(message
);
777 throw new Error
.Failure(message
);
781 private static void checkSendMessageResults(
782 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
783 ) throws DBusExecutionException
{
784 final var sendMessageResults
= results
.values().stream().findFirst();
785 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
786 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
790 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
791 if (errors
.size() == 0) {
795 var message
= new StringBuilder();
796 message
.append(timestamp
).append('\n');
797 message
.append("Failed to send (some) messages:\n");
798 for (var error
: errors
) {
799 message
.append(error
).append('\n');
802 throw new Error
.Failure(message
.toString());
805 private static void checkSendMessageResults(
806 long timestamp
, Collection
<SendMessageResult
> results
807 ) throws DBusExecutionException
{
808 if (results
.size() == 1) {
809 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
813 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
814 if (errors
.size() == 0) {
818 var message
= new StringBuilder();
819 message
.append(timestamp
).append('\n');
820 message
.append("Failed to send (some) messages:\n");
821 for (var error
: errors
) {
822 message
.append(error
).append('\n');
825 throw new Error
.Failure(message
.toString());
828 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
829 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).collect(Collectors
.toList());
832 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
833 final Collection
<String
> recipientStrings
, final String localNumber
834 ) throws DBusExecutionException
{
835 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
836 for (var recipientString
: recipientStrings
) {
837 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
842 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
843 final String recipientString
, final String localNumber
844 ) throws DBusExecutionException
{
846 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
847 } catch (InvalidNumberException e
) {
848 throw new Error
.InvalidNumber(e
.getMessage());
852 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
854 return GroupId
.unknownVersion(groupId
);
855 } catch (Throwable e
) {
856 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
860 private byte[] nullIfEmpty(final byte[] array
) {
861 return array
.length
== 0 ?
null : array
;
864 private String
nullIfEmpty(final String name
) {
865 return name
.isEmpty() ?
null : name
;
868 private String
emptyIfNull(final String string
) {
869 return string
== null ?
"" : string
;
872 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
873 return basePath
+ "/Devices/" + deviceId
;
876 private void updateDevices() {
877 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
879 linkedDevices
= m
.getLinkedDevices();
880 } catch (IOException e
) {
881 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
886 linkedDevices
.forEach(d
-> {
887 final var object
= new DbusSignalDeviceImpl(d
);
888 final var deviceObjectPath
= object
.getObjectPath();
889 exportObject(object
);
890 if (d
.isThisDevice()) {
891 thisDevice
= new DBusPath(deviceObjectPath
);
893 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
897 private void unExportDevices() {
898 this.devices
.stream()
899 .map(StructDevice
::getObjectPath
)
900 .map(DBusPath
::getPath
)
901 .forEach(connection
::unExportObject
);
902 this.devices
.clear();
905 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
906 return basePath
+ "/Groups/" + Base64
.getEncoder()
907 .encodeToString(groupId
)
913 private void updateGroups() {
914 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
915 groups
= m
.getGroups();
919 groups
.forEach(g
-> {
920 final var object
= new DbusSignalGroupImpl(g
.groupId());
921 exportObject(object
);
922 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
923 g
.groupId().serialize(),
924 emptyIfNull(g
.title())));
928 private void unExportGroups() {
929 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
933 private static String
getConfigurationObjectPath(String basePath
) {
934 return basePath
+ "/Configuration";
937 private void updateConfiguration() {
938 unExportConfiguration();
939 final var object
= new DbusSignalConfigurationImpl();
940 exportObject(object
);
943 private void unExportConfiguration() {
944 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
945 connection
.unExportObject(objectPath
);
948 private void exportObject(final DBusInterface object
) {
950 connection
.exportObject(object
);
951 logger
.debug("Exported dbus object: " + object
.getObjectPath());
952 } catch (DBusException e
) {
957 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
959 private final org
.asamk
.signal
.manager
.api
.Device device
;
961 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
962 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
963 List
.of(new DbusProperty
<>("Id", device
::id
),
964 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
965 new DbusProperty
<>("Created", device
::created
),
966 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
967 this.device
= device
;
971 public String
getObjectPath() {
972 return getDeviceObjectPath(objectPath
, device
.id());
976 public void removeDevice() throws Error
.Failure
{
978 m
.removeLinkedDevices(device
.id());
980 } catch (IOException e
) {
981 throw new Error
.Failure(e
.getMessage());
985 private void setDeviceName(String name
) {
986 if (!device
.isThisDevice()) {
987 throw new Error
.Failure("Only the name of this device can be changed");
990 m
.updateAccountAttributes(name
);
991 // update device list
993 } catch (IOException e
) {
994 throw new Error
.Failure(e
.getMessage());
999 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
1001 public DbusSignalConfigurationImpl(
1003 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
1004 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
1005 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
1006 this::getUnidentifiedDeliveryIndicators
,
1007 this::setUnidentifiedDeliveryIndicators
),
1008 new DbusProperty
<>("TypingIndicators",
1009 this::getTypingIndicators
,
1010 this::setTypingIndicators
),
1011 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1016 public String
getObjectPath() {
1017 return getConfigurationObjectPath(objectPath
);
1020 public void setReadReceipts(Boolean readReceipts
) {
1021 setConfiguration(readReceipts
, null, null, null);
1024 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1025 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1028 public void setTypingIndicators(Boolean typingIndicators
) {
1029 setConfiguration(null, null, typingIndicators
, null);
1032 public void setLinkPreviews(Boolean linkPreviews
) {
1033 setConfiguration(null, null, null, linkPreviews
);
1036 private void setConfiguration(
1037 Boolean readReceipts
,
1038 Boolean unidentifiedDeliveryIndicators
,
1039 Boolean typingIndicators
,
1040 Boolean linkPreviews
1043 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1044 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1045 Optional
.ofNullable(typingIndicators
),
1046 Optional
.ofNullable(linkPreviews
)));
1047 } catch (IOException e
) {
1048 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1049 } catch (NotMasterDeviceException e
) {
1050 throw new Error
.Failure("This command doesn't work on linked devices.");
1054 private boolean getReadReceipts() {
1055 return m
.getConfiguration().readReceipts().orElse(false);
1058 private boolean getUnidentifiedDeliveryIndicators() {
1059 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1062 private boolean getTypingIndicators() {
1063 return m
.getConfiguration().typingIndicators().orElse(false);
1066 private boolean getLinkPreviews() {
1067 return m
.getConfiguration().linkPreviews().orElse(false);
1071 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1073 private final GroupId groupId
;
1075 public DbusSignalGroupImpl(final GroupId groupId
) {
1076 this.groupId
= groupId
;
1077 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1078 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1079 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1080 new DbusProperty
<>("Description",
1081 () -> emptyIfNull(getGroup().description()),
1082 this::setGroupDescription
),
1083 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1084 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1085 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1086 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1087 new DbusProperty
<>("MessageExpirationTimer",
1088 () -> getGroup().messageExpirationTimer(),
1089 this::setMessageExpirationTime
),
1090 new DbusProperty
<>("Members",
1091 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1092 new DbusProperty
<>("PendingMembers",
1093 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1094 new DbusProperty
<>("RequestingMembers",
1095 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1096 new DbusProperty
<>("Admins",
1097 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1098 new DbusProperty
<>("PermissionAddMember",
1099 () -> getGroup().permissionAddMember().name(),
1100 this::setGroupPermissionAddMember
),
1101 new DbusProperty
<>("PermissionEditDetails",
1102 () -> getGroup().permissionEditDetails().name(),
1103 this::setGroupPermissionEditDetails
),
1104 new DbusProperty
<>("PermissionSendMessage",
1105 () -> getGroup().permissionSendMessage().name(),
1106 this::setGroupPermissionSendMessage
),
1107 new DbusProperty
<>("GroupInviteLink", () -> {
1108 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1109 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1114 public String
getObjectPath() {
1115 return getGroupObjectPath(objectPath
, groupId
.serialize());
1119 public void quitGroup() throws Error
.Failure
{
1121 m
.quitGroup(groupId
, Set
.of());
1122 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1123 throw new Error
.GroupNotFound(e
.getMessage());
1124 } catch (IOException e
) {
1125 throw new Error
.Failure(e
.getMessage());
1126 } catch (LastGroupAdminException e
) {
1127 throw new Error
.LastGroupAdmin(e
.getMessage());
1132 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1133 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1134 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1138 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1139 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1140 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1144 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1145 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1146 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1150 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1151 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1152 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1156 public void resetLink() throws Error
.Failure
{
1157 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1161 public void disableLink() throws Error
.Failure
{
1162 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1166 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1167 updateGroup(UpdateGroup
.newBuilder()
1168 .withGroupLinkState(requiresApproval
1169 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1170 : GroupLinkState
.ENABLED
)
1174 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1175 return m
.getGroup(groupId
);
1178 private void setGroupName(final String name
) {
1179 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1182 private void setGroupDescription(final String description
) {
1183 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1186 private void setGroupAvatar(final String avatar
) {
1187 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1190 private void setMessageExpirationTime(final int expirationTime
) {
1191 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1194 private void setGroupPermissionAddMember(final String permission
) {
1195 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1198 private void setGroupPermissionEditDetails(final String permission
) {
1199 updateGroup(UpdateGroup
.newBuilder()
1200 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1204 private void setGroupPermissionSendMessage(final String permission
) {
1205 updateGroup(UpdateGroup
.newBuilder()
1206 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1210 private void setIsBlocked(final boolean isBlocked
) {
1212 m
.setGroupBlocked(groupId
, isBlocked
);
1213 } catch (NotMasterDeviceException e
) {
1214 throw new Error
.Failure("This command doesn't work on linked devices.");
1215 } catch (GroupNotFoundException e
) {
1216 throw new Error
.GroupNotFound(e
.getMessage());
1217 } catch (IOException e
) {
1218 throw new Error
.Failure(e
.getMessage());
1222 private void updateGroup(final UpdateGroup updateGroup
) {
1224 m
.updateGroup(groupId
, updateGroup
);
1225 } catch (IOException e
) {
1226 throw new Error
.Failure(e
.getMessage());
1227 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1228 throw new Error
.GroupNotFound(e
.getMessage());
1229 } catch (AttachmentInvalidException e
) {
1230 throw new Error
.AttachmentInvalid(e
.getMessage());