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
.UntrustedIdentityException
;
10 import org
.asamk
.signal
.manager
.api
.Identity
;
11 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
12 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
13 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
14 import org
.asamk
.signal
.manager
.api
.Message
;
15 import org
.asamk
.signal
.manager
.api
.Pair
;
16 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
17 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
18 import org
.asamk
.signal
.manager
.api
.TypingAction
;
19 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
20 import org
.asamk
.signal
.manager
.groups
.GroupId
;
21 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
22 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
23 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
24 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
25 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
26 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
27 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
29 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
30 import org
.asamk
.signal
.util
.ErrorUtils
;
31 import org
.freedesktop
.dbus
.DBusPath
;
32 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
33 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
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
;
63 private DBusPath thisDevice
;
64 private final List
<StructDevice
> devices
= new ArrayList
<>();
65 private final List
<StructGroup
> groups
= new ArrayList
<>();
67 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
69 public DbusSignalImpl(final Manager m
, DBusConnection connection
, final String objectPath
) {
71 this.connection
= connection
;
72 this.objectPath
= objectPath
;
75 public void initObjects() {
78 updateConfiguration();
84 unExportConfiguration();
88 public String
getObjectPath() {
93 public String
getSelfNumber() {
94 return m
.getSelfNumber();
98 public void submitRateLimitChallenge(String challenge
, String captchaString
) {
99 final var captcha
= captchaString
== null ?
null : captchaString
.replace("signalcaptcha://", "");
102 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
103 } catch (IOException e
) {
104 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
110 public void addDevice(String uri
) {
112 m
.addDeviceLink(new URI(uri
));
113 } catch (IOException
| InvalidDeviceLinkException e
) {
114 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
115 } catch (URISyntaxException e
) {
116 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
117 + " Device link uri has invalid format: "
123 public DBusPath
getDevice(long deviceId
) {
125 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
126 if (deviceOptional
.isEmpty()) {
127 throw new Error
.DeviceNotFound("Device not found");
129 return deviceOptional
.get().getObjectPath();
133 public List
<StructDevice
> listDevices() {
139 public DBusPath
getThisDevice() {
145 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
146 var recipients
= new ArrayList
<String
>(1);
147 recipients
.add(recipient
);
148 return sendMessage(message
, attachments
, recipients
);
152 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
154 final var results
= m
.sendMessage(new Message(message
, attachments
),
155 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
156 .map(RecipientIdentifier
.class::cast
)
157 .collect(Collectors
.toSet()));
159 checkSendMessageResults(results
.timestamp(), results
.results());
160 return results
.timestamp();
161 } catch (AttachmentInvalidException e
) {
162 throw new Error
.AttachmentInvalid(e
.getMessage());
163 } catch (IOException e
) {
164 throw new Error
.Failure(e
);
165 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
166 throw new Error
.GroupNotFound(e
.getMessage());
171 public long sendRemoteDeleteMessage(
172 final long targetSentTimestamp
, final String recipient
174 var recipients
= new ArrayList
<String
>(1);
175 recipients
.add(recipient
);
176 return sendRemoteDeleteMessage(targetSentTimestamp
, recipients
);
180 public long sendRemoteDeleteMessage(
181 final long targetSentTimestamp
, final List
<String
> recipients
184 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
185 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
186 .map(RecipientIdentifier
.class::cast
)
187 .collect(Collectors
.toSet()));
188 checkSendMessageResults(results
.timestamp(), results
.results());
189 return results
.timestamp();
190 } catch (IOException e
) {
191 throw new Error
.Failure(e
.getMessage());
192 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
193 throw new Error
.GroupNotFound(e
.getMessage());
198 public long sendGroupRemoteDeleteMessage(
199 final long targetSentTimestamp
, final byte[] groupId
202 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
203 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
204 checkSendMessageResults(results
.timestamp(), results
.results());
205 return results
.timestamp();
206 } catch (IOException e
) {
207 throw new Error
.Failure(e
.getMessage());
208 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
209 throw new Error
.GroupNotFound(e
.getMessage());
214 public long sendMessageReaction(
216 final boolean remove
,
217 final String targetAuthor
,
218 final long targetSentTimestamp
,
219 final String recipient
221 var recipients
= new ArrayList
<String
>(1);
222 recipients
.add(recipient
);
223 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, recipients
);
227 public long sendMessageReaction(
229 final boolean remove
,
230 final String targetAuthor
,
231 final long targetSentTimestamp
,
232 final List
<String
> recipients
235 final var results
= m
.sendMessageReaction(emoji
,
237 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
239 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
240 .map(RecipientIdentifier
.class::cast
)
241 .collect(Collectors
.toSet()));
242 checkSendMessageResults(results
.timestamp(), results
.results());
243 return results
.timestamp();
244 } catch (IOException e
) {
245 throw new Error
.Failure(e
.getMessage());
246 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
247 throw new Error
.GroupNotFound(e
.getMessage());
252 public void sendTyping(
253 final String recipient
, final boolean stop
254 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
256 var recipients
= new ArrayList
<String
>(1);
257 recipients
.add(recipient
);
258 m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
259 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
260 .map(RecipientIdentifier
.class::cast
)
261 .collect(Collectors
.toSet()));
262 } catch (IOException e
) {
263 throw new Error
.Failure(e
.getMessage());
264 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
265 throw new Error
.GroupNotFound(e
.getMessage());
266 } catch (UntrustedIdentityException e
) {
267 throw new Error
.UntrustedIdentity(e
.getMessage());
272 public void sendReadReceipt(
273 final String recipient
, final List
<Long
> messageIds
274 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
276 m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
277 } catch (IOException e
) {
278 throw new Error
.Failure(e
.getMessage());
279 } catch (UntrustedIdentityException e
) {
280 throw new Error
.UntrustedIdentity(e
.getMessage());
285 public void sendViewedReceipt(
286 final String recipient
, final List
<Long
> messageIds
287 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
289 m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
290 } catch (IOException e
) {
291 throw new Error
.Failure(e
.getMessage());
292 } catch (UntrustedIdentityException e
) {
293 throw new Error
.UntrustedIdentity(e
.getMessage());
298 public void sendContacts() {
301 } catch (IOException e
) {
302 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
307 public void sendSyncRequest() {
309 m
.requestAllSyncData();
310 } catch (IOException e
) {
311 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
316 public long sendNoteToSelfMessage(
317 final String message
, final List
<String
> attachments
318 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
320 final var results
= m
.sendMessage(new Message(message
, attachments
),
321 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
322 checkSendMessageResults(results
.timestamp(), results
.results());
323 return results
.timestamp();
324 } catch (AttachmentInvalidException e
) {
325 throw new Error
.AttachmentInvalid(e
.getMessage());
326 } catch (IOException e
) {
327 throw new Error
.Failure(e
.getMessage());
328 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
329 throw new Error
.GroupNotFound(e
.getMessage());
334 public void sendEndSessionMessage(final List
<String
> recipients
) {
336 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
337 checkSendMessageResults(results
.timestamp(), results
.results());
338 } catch (IOException e
) {
339 throw new Error
.Failure(e
.getMessage());
344 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
346 var results
= m
.sendMessage(new Message(message
, attachments
),
347 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
348 checkSendMessageResults(results
.timestamp(), results
.results());
349 return results
.timestamp();
350 } catch (IOException e
) {
351 throw new Error
.Failure(e
.getMessage());
352 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
353 throw new Error
.GroupNotFound(e
.getMessage());
354 } catch (AttachmentInvalidException e
) {
355 throw new Error
.AttachmentInvalid(e
.getMessage());
360 public long sendGroupMessageReaction(
362 final boolean remove
,
363 final String targetAuthor
,
364 final long targetSentTimestamp
,
368 final var results
= m
.sendMessageReaction(emoji
,
370 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
372 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
373 checkSendMessageResults(results
.timestamp(), results
.results());
374 return results
.timestamp();
375 } catch (IOException e
) {
376 throw new Error
.Failure(e
.getMessage());
377 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
378 throw new Error
.GroupNotFound(e
.getMessage());
382 // Since contact names might be empty if not defined, also potentially return
385 public String
getContactName(final String number
) {
386 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
387 return name
== null ?
"" : name
;
391 public void setContactName(final String number
, final String name
) {
393 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
394 } catch (NotMasterDeviceException e
) {
395 throw new Error
.Failure("This command doesn't work on linked devices.");
396 } catch (IOException e
) {
397 throw new Error
.Failure("Contact is not registered.");
402 public void setExpirationTimer(final String number
, final int expiration
) {
404 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
405 } catch (IOException e
) {
406 throw new Error
.Failure(e
.getMessage());
411 public void setContactBlocked(final String number
, final boolean blocked
) {
413 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
414 } catch (NotMasterDeviceException e
) {
415 throw new Error
.Failure("This command doesn't work on linked devices.");
416 } catch (IOException e
) {
417 throw new Error
.Failure(e
.getMessage());
422 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
424 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
425 } catch (NotMasterDeviceException e
) {
426 throw new Error
.Failure("This command doesn't work on linked devices.");
427 } catch (GroupNotFoundException e
) {
428 throw new Error
.GroupNotFound(e
.getMessage());
429 } catch (IOException e
) {
430 throw new Error
.Failure(e
.getMessage());
435 public List
<byte[]> getGroupIds() {
436 var groups
= m
.getGroups();
437 var ids
= new ArrayList
<byte[]>(groups
.size());
438 for (var group
: groups
) {
439 ids
.add(group
.groupId().serialize());
445 public DBusPath
getGroup(final byte[] groupId
) {
447 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
448 if (groupOptional
.isEmpty()) {
449 throw new Error
.GroupNotFound("Group not found");
451 return groupOptional
.get().getObjectPath();
455 public List
<StructGroup
> listGroups() {
461 public String
getGroupName(final byte[] groupId
) {
462 var group
= m
.getGroup(getGroupId(groupId
));
463 if (group
== null || group
.title() == null) {
466 return group
.title();
471 public List
<String
> getGroupMembers(final byte[] groupId
) {
472 var group
= m
.getGroup(getGroupId(groupId
));
476 final var members
= group
.members();
477 return getRecipientStrings(members
);
482 public byte[] createGroup(
483 final String name
, final List
<String
> members
, final String avatar
484 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
485 return updateGroup(new byte[0], name
, members
, avatar
);
489 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
491 groupId
= nullIfEmpty(groupId
);
492 name
= nullIfEmpty(name
);
493 avatar
= nullIfEmpty(avatar
);
494 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
495 if (groupId
== null) {
496 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
497 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
498 return results
.first().serialize();
500 final var results
= m
.updateGroup(getGroupId(groupId
),
501 UpdateGroup
.newBuilder()
503 .withMembers(memberIdentifiers
)
504 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
506 if (results
!= null) {
507 checkSendMessageResults(results
.timestamp(), results
.results());
511 } catch (IOException e
) {
512 throw new Error
.Failure(e
.getMessage());
513 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
514 throw new Error
.GroupNotFound(e
.getMessage());
515 } catch (AttachmentInvalidException e
) {
516 throw new Error
.AttachmentInvalid(e
.getMessage());
521 public boolean isRegistered() {
526 public boolean isRegistered(String number
) {
527 var result
= isRegistered(List
.of(number
));
528 return result
.get(0);
532 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
533 var results
= new ArrayList
<Boolean
>();
534 if (numbers
.isEmpty()) {
538 Map
<String
, Pair
<String
, UUID
>> registered
;
540 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
541 } catch (IOException e
) {
542 throw new Error
.Failure(e
.getMessage());
545 return numbers
.stream().map(number
-> {
546 var uuid
= registered
.get(number
).second();
548 }).collect(Collectors
.toList());
552 public void updateProfile(
558 final boolean removeAvatar
561 givenName
= nullIfEmpty(givenName
);
562 familyName
= nullIfEmpty(familyName
);
563 about
= nullIfEmpty(about
);
564 aboutEmoji
= nullIfEmpty(aboutEmoji
);
565 avatarPath
= nullIfEmpty(avatarPath
);
566 Optional
<File
> avatarFile
= removeAvatar
568 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
569 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
570 } catch (IOException e
) {
571 throw new Error
.Failure(e
.getMessage());
576 public void updateProfile(
579 final String aboutEmoji
,
581 final boolean removeAvatar
583 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
587 public void removePin() {
589 m
.setRegistrationLockPin(Optional
.empty());
590 } catch (IOException e
) {
591 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
596 public void setPin(String registrationLockPin
) {
598 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
599 } catch (IOException e
) {
600 throw new Error
.Failure("Set pin error: " + e
.getMessage());
604 // Provide option to query a version string in order to react on potential
605 // future interface changes
607 public String
version() {
608 return BaseConfig
.PROJECT_VERSION
;
611 // Create a unique list of Numbers from Identities and Contacts to really get
612 // all numbers the system knows
614 public List
<String
> listNumbers() {
615 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
616 m
.getContacts().stream().map(Pair
::first
))
617 .map(a
-> a
.getNumber().orElse(null))
618 .filter(Objects
::nonNull
)
620 .collect(Collectors
.toList());
624 public List
<String
> getContactNumber(final String name
) {
625 // Contact names have precedence.
626 var numbers
= new ArrayList
<String
>();
627 var contacts
= m
.getContacts();
628 for (var c
: contacts
) {
629 if (name
.equals(c
.second().getName())) {
630 numbers
.add(c
.first().getLegacyIdentifier());
633 // Try profiles if no contact name was found
634 for (var identity
: m
.getIdentities()) {
635 final var address
= identity
.recipient();
636 var number
= address
.getNumber().orElse(null);
637 if (number
!= null) {
638 Profile profile
= null;
640 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
641 } catch (IOException ignored
) {
643 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
652 public void quitGroup(final byte[] groupId
) {
653 var group
= getGroupId(groupId
);
655 m
.quitGroup(group
, Set
.of());
656 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
657 throw new Error
.GroupNotFound(e
.getMessage());
658 } catch (IOException
| LastGroupAdminException e
) {
659 throw new Error
.Failure(e
.getMessage());
664 public byte[] joinGroup(final String groupLink
) {
666 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
667 if (linkUrl
== null) {
668 throw new Error
.Failure("Group link is invalid:");
670 final var result
= m
.joinGroup(linkUrl
);
671 return result
.first().serialize();
672 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
673 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
674 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
675 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
676 } catch (IOException e
) {
677 throw new Error
.Failure(e
.getMessage());
682 public boolean isContactBlocked(final String number
) {
683 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
687 public boolean isGroupBlocked(final byte[] groupId
) {
688 var group
= m
.getGroup(getGroupId(groupId
));
692 return group
.isBlocked();
697 public boolean isMember(final byte[] groupId
) {
698 var group
= m
.getGroup(getGroupId(groupId
));
702 return group
.isMember();
707 public String
uploadStickerPack(String stickerPackPath
) {
708 File path
= new File(stickerPackPath
);
710 return m
.uploadStickerPack(path
).toString();
711 } catch (IOException e
) {
712 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
713 } catch (StickerPackInvalidException e
) {
714 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
718 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
719 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
725 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
727 if (result
.isIdentityFailure()) {
728 throw new Error
.UntrustedIdentity(message
);
730 throw new Error
.Failure(message
);
734 private static void checkSendMessageResults(
735 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
736 ) throws DBusExecutionException
{
737 final var sendMessageResults
= results
.values().stream().findFirst();
738 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
739 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
743 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
744 if (errors
.size() == 0) {
748 var message
= new StringBuilder();
749 message
.append(timestamp
).append('\n');
750 message
.append("Failed to send (some) messages:\n");
751 for (var error
: errors
) {
752 message
.append(error
).append('\n');
755 throw new Error
.Failure(message
.toString());
758 private static void checkSendMessageResults(
759 long timestamp
, Collection
<SendMessageResult
> results
760 ) throws DBusExecutionException
{
761 if (results
.size() == 1) {
762 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
766 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
767 if (errors
.size() == 0) {
771 var message
= new StringBuilder();
772 message
.append(timestamp
).append('\n');
773 message
.append("Failed to send (some) messages:\n");
774 for (var error
: errors
) {
775 message
.append(error
).append('\n');
778 throw new Error
.Failure(message
.toString());
781 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
782 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).collect(Collectors
.toList());
785 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
786 final Collection
<String
> recipientStrings
, final String localNumber
787 ) throws DBusExecutionException
{
788 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
789 for (var recipientString
: recipientStrings
) {
790 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
795 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
796 final String recipientString
, final String localNumber
797 ) throws DBusExecutionException
{
799 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
800 } catch (InvalidNumberException e
) {
801 throw new Error
.InvalidNumber(e
.getMessage());
805 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
807 return GroupId
.unknownVersion(groupId
);
808 } catch (Throwable e
) {
809 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
813 private byte[] nullIfEmpty(final byte[] array
) {
814 return array
.length
== 0 ?
null : array
;
817 private String
nullIfEmpty(final String name
) {
818 return name
.isEmpty() ?
null : name
;
821 private String
emptyIfNull(final String string
) {
822 return string
== null ?
"" : string
;
825 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
826 return basePath
+ "/Devices/" + deviceId
;
829 private void updateDevices() {
830 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
832 linkedDevices
= m
.getLinkedDevices();
833 } catch (IOException e
) {
834 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
839 linkedDevices
.forEach(d
-> {
840 final var object
= new DbusSignalDeviceImpl(d
);
841 final var deviceObjectPath
= object
.getObjectPath();
843 connection
.exportObject(object
);
844 logger
.debug("Exported dbus object: " + deviceObjectPath
);
845 } catch (DBusException e
) {
848 if (d
.isThisDevice()) {
849 thisDevice
= new DBusPath(deviceObjectPath
);
851 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
855 private void unExportDevices() {
856 this.devices
.stream()
857 .map(StructDevice
::getObjectPath
)
858 .map(DBusPath
::getPath
)
859 .forEach(connection
::unExportObject
);
860 this.devices
.clear();
863 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
864 return basePath
+ "/Groups/" + Base64
.getEncoder()
865 .encodeToString(groupId
)
871 private void updateGroups() {
872 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
873 groups
= m
.getGroups();
877 groups
.forEach(g
-> {
878 final var object
= new DbusSignalGroupImpl(g
.groupId());
880 connection
.exportObject(object
);
881 logger
.debug("Exported dbus object: " + object
.getObjectPath());
882 } catch (DBusException e
) {
885 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
886 g
.groupId().serialize(),
887 emptyIfNull(g
.title())));
891 private void unExportGroups() {
892 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
896 private static String
getConfigurationObjectPath(String basePath
) {
897 return basePath
+ "/Configuration";
900 private void updateConfiguration() {
902 unExportConfiguration();
903 final var object
= new DbusSignalConfigurationImpl();
904 connection
.exportObject(object
);
905 logger
.debug("Exported dbus object: " + objectPath
+ "/Configuration");
906 } catch (DBusException e
) {
911 private void unExportConfiguration() {
912 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
913 connection
.unExportObject(objectPath
);
916 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
918 private final org
.asamk
.signal
.manager
.api
.Device device
;
920 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
921 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
922 List
.of(new DbusProperty
<>("Id", device
::id
),
923 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
924 new DbusProperty
<>("Created", device
::created
),
925 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
926 this.device
= device
;
930 public String
getObjectPath() {
931 return getDeviceObjectPath(objectPath
, device
.id());
935 public void removeDevice() throws Error
.Failure
{
937 m
.removeLinkedDevices(device
.id());
939 } catch (IOException e
) {
940 throw new Error
.Failure(e
.getMessage());
944 private void setDeviceName(String name
) {
945 if (!device
.isThisDevice()) {
946 throw new Error
.Failure("Only the name of this device can be changed");
949 m
.updateAccountAttributes(name
);
950 // update device list
952 } catch (IOException e
) {
953 throw new Error
.Failure(e
.getMessage());
958 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
960 public DbusSignalConfigurationImpl(
962 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
963 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
964 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
965 this::getUnidentifiedDeliveryIndicators
,
966 this::setUnidentifiedDeliveryIndicators
),
967 new DbusProperty
<>("TypingIndicators",
968 this::getTypingIndicators
,
969 this::setTypingIndicators
),
970 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
975 public String
getObjectPath() {
976 return getConfigurationObjectPath(objectPath
);
979 public void setReadReceipts(Boolean readReceipts
) {
980 setConfiguration(readReceipts
, null, null, null);
983 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
984 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
987 public void setTypingIndicators(Boolean typingIndicators
) {
988 setConfiguration(null, null, typingIndicators
, null);
991 public void setLinkPreviews(Boolean linkPreviews
) {
992 setConfiguration(null, null, null, linkPreviews
);
995 private void setConfiguration(
996 Boolean readReceipts
,
997 Boolean unidentifiedDeliveryIndicators
,
998 Boolean typingIndicators
,
1002 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1003 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1004 Optional
.ofNullable(typingIndicators
),
1005 Optional
.ofNullable(linkPreviews
)));
1006 } catch (IOException e
) {
1007 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1008 } catch (NotMasterDeviceException e
) {
1009 throw new Error
.Failure("This command doesn't work on linked devices.");
1013 private boolean getReadReceipts() {
1014 return m
.getConfiguration().readReceipts().orElse(false);
1017 private boolean getUnidentifiedDeliveryIndicators() {
1018 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1021 private boolean getTypingIndicators() {
1022 return m
.getConfiguration().typingIndicators().orElse(false);
1025 private boolean getLinkPreviews() {
1026 return m
.getConfiguration().linkPreviews().orElse(false);
1030 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1032 private final GroupId groupId
;
1034 public DbusSignalGroupImpl(final GroupId groupId
) {
1035 this.groupId
= groupId
;
1036 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1037 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1038 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1039 new DbusProperty
<>("Description",
1040 () -> emptyIfNull(getGroup().description()),
1041 this::setGroupDescription
),
1042 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1043 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1044 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1045 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1046 new DbusProperty
<>("MessageExpirationTimer",
1047 () -> getGroup().messageExpirationTimer(),
1048 this::setMessageExpirationTime
),
1049 new DbusProperty
<>("Members",
1050 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1051 new DbusProperty
<>("PendingMembers",
1052 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1053 new DbusProperty
<>("RequestingMembers",
1054 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1055 new DbusProperty
<>("Admins",
1056 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1057 new DbusProperty
<>("PermissionAddMember",
1058 () -> getGroup().permissionAddMember().name(),
1059 this::setGroupPermissionAddMember
),
1060 new DbusProperty
<>("PermissionEditDetails",
1061 () -> getGroup().permissionEditDetails().name(),
1062 this::setGroupPermissionEditDetails
),
1063 new DbusProperty
<>("PermissionSendMessage",
1064 () -> getGroup().permissionSendMessage().name(),
1065 this::setGroupPermissionSendMessage
),
1066 new DbusProperty
<>("GroupInviteLink", () -> {
1067 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1068 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1073 public String
getObjectPath() {
1074 return getGroupObjectPath(objectPath
, groupId
.serialize());
1078 public void quitGroup() throws Error
.Failure
{
1080 m
.quitGroup(groupId
, Set
.of());
1081 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1082 throw new Error
.GroupNotFound(e
.getMessage());
1083 } catch (IOException e
) {
1084 throw new Error
.Failure(e
.getMessage());
1085 } catch (LastGroupAdminException e
) {
1086 throw new Error
.LastGroupAdmin(e
.getMessage());
1091 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1092 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1093 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1097 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1098 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1099 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1103 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1104 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1105 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1109 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1110 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1111 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1115 public void resetLink() throws Error
.Failure
{
1116 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1120 public void disableLink() throws Error
.Failure
{
1121 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1125 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1126 updateGroup(UpdateGroup
.newBuilder()
1127 .withGroupLinkState(requiresApproval
1128 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1129 : GroupLinkState
.ENABLED
)
1133 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1134 return m
.getGroup(groupId
);
1137 private void setGroupName(final String name
) {
1138 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1141 private void setGroupDescription(final String description
) {
1142 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1145 private void setGroupAvatar(final String avatar
) {
1146 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1149 private void setMessageExpirationTime(final int expirationTime
) {
1150 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1153 private void setGroupPermissionAddMember(final String permission
) {
1154 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1157 private void setGroupPermissionEditDetails(final String permission
) {
1158 updateGroup(UpdateGroup
.newBuilder()
1159 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1163 private void setGroupPermissionSendMessage(final String permission
) {
1164 updateGroup(UpdateGroup
.newBuilder()
1165 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1169 private void setIsBlocked(final boolean isBlocked
) {
1171 m
.setGroupBlocked(groupId
, isBlocked
);
1172 } catch (NotMasterDeviceException e
) {
1173 throw new Error
.Failure("This command doesn't work on linked devices.");
1174 } catch (GroupNotFoundException e
) {
1175 throw new Error
.GroupNotFound(e
.getMessage());
1176 } catch (IOException e
) {
1177 throw new Error
.Failure(e
.getMessage());
1181 private void updateGroup(final UpdateGroup updateGroup
) {
1183 m
.updateGroup(groupId
, updateGroup
);
1184 } catch (IOException e
) {
1185 throw new Error
.Failure(e
.getMessage());
1186 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1187 throw new Error
.GroupNotFound(e
.getMessage());
1188 } catch (AttachmentInvalidException e
) {
1189 throw new Error
.AttachmentInvalid(e
.getMessage());