1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.BaseConfig
;
5 import org
.asamk
.signal
.commands
.exceptions
.IOErrorException
;
6 import org
.asamk
.signal
.manager
.AttachmentInvalidException
;
7 import org
.asamk
.signal
.manager
.Manager
;
8 import org
.asamk
.signal
.manager
.NotMasterDeviceException
;
9 import org
.asamk
.signal
.manager
.StickerPackInvalidException
;
10 import org
.asamk
.signal
.manager
.UntrustedIdentityException
;
11 import org
.asamk
.signal
.manager
.api
.Identity
;
12 import org
.asamk
.signal
.manager
.api
.Message
;
13 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
14 import org
.asamk
.signal
.manager
.api
.TypingAction
;
15 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
16 import org
.asamk
.signal
.manager
.groups
.GroupId
;
17 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
18 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
19 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
20 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
21 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
22 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
23 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
24 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
25 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
26 import org
.asamk
.signal
.util
.ErrorUtils
;
27 import org
.freedesktop
.dbus
.DBusPath
;
28 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
29 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
30 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
31 import org
.freedesktop
.dbus
.types
.Variant
;
32 import org
.whispersystems
.libsignal
.InvalidKeyException
;
33 import org
.whispersystems
.libsignal
.util
.Pair
;
34 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
35 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
36 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
37 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
38 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
39 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
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
;
54 import java
.util
.UUID
;
55 import java
.util
.stream
.Collectors
;
56 import java
.util
.stream
.Stream
;
58 public class DbusSignalImpl
implements Signal
{
60 private final Manager m
;
61 private final DBusConnection connection
;
62 private final String objectPath
;
64 private DBusPath thisDevice
;
65 private final List
<StructDevice
> devices
= new ArrayList
<>();
66 private final List
<StructGroup
> groups
= new ArrayList
<>();
68 public DbusSignalImpl(final Manager m
, DBusConnection connection
, final String objectPath
) {
70 this.connection
= connection
;
71 this.objectPath
= objectPath
;
74 public void initObjects() {
84 public String
getObjectPath() {
89 public String
getSelfNumber() {
90 return m
.getSelfNumber();
94 public void submitRateLimitChallenge(String challenge
, String captchaString
) throws IOErrorException
{
95 final var captcha
= captchaString
== null ?
null : captchaString
.replace("signalcaptcha://", "");
98 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
99 } catch (IOException e
) {
100 throw new IOErrorException("Submit challenge error: " + e
.getMessage(), e
);
106 public void addDevice(String uri
) {
108 m
.addDeviceLink(new URI(uri
));
109 } catch (IOException
| InvalidKeyException e
) {
110 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
111 } catch (URISyntaxException e
) {
112 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
113 + " Device link uri has invalid format: "
119 public DBusPath
getDevice(long deviceId
) {
121 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
122 if (deviceOptional
.isEmpty()) {
123 throw new Error
.DeviceNotFound("Device not found");
125 return deviceOptional
.get().getObjectPath();
129 public List
<StructDevice
> listDevices() {
135 public DBusPath
getThisDevice() {
141 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
142 var recipients
= new ArrayList
<String
>(1);
143 recipients
.add(recipient
);
144 return sendMessage(message
, attachments
, recipients
);
148 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
150 final var results
= m
.sendMessage(new Message(message
, attachments
),
151 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
152 .map(RecipientIdentifier
.class::cast
)
153 .collect(Collectors
.toSet()));
155 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
156 return results
.getTimestamp();
157 } catch (AttachmentInvalidException e
) {
158 throw new Error
.AttachmentInvalid(e
.getMessage());
159 } catch (IOException e
) {
160 throw new Error
.Failure(e
.getMessage());
161 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
162 throw new Error
.GroupNotFound(e
.getMessage());
167 public long sendRemoteDeleteMessage(
168 final long targetSentTimestamp
, final String recipient
170 var recipients
= new ArrayList
<String
>(1);
171 recipients
.add(recipient
);
172 return sendRemoteDeleteMessage(targetSentTimestamp
, recipients
);
176 public long sendRemoteDeleteMessage(
177 final long targetSentTimestamp
, final List
<String
> recipients
180 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
181 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
182 .map(RecipientIdentifier
.class::cast
)
183 .collect(Collectors
.toSet()));
184 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
185 return results
.getTimestamp();
186 } catch (IOException e
) {
187 throw new Error
.Failure(e
.getMessage());
188 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
189 throw new Error
.GroupNotFound(e
.getMessage());
194 public long sendGroupRemoteDeleteMessage(
195 final long targetSentTimestamp
, final byte[] groupId
198 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
199 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
200 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
201 return results
.getTimestamp();
202 } catch (IOException e
) {
203 throw new Error
.Failure(e
.getMessage());
204 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
205 throw new Error
.GroupNotFound(e
.getMessage());
210 public long sendMessageReaction(
212 final boolean remove
,
213 final String targetAuthor
,
214 final long targetSentTimestamp
,
215 final String recipient
217 var recipients
= new ArrayList
<String
>(1);
218 recipients
.add(recipient
);
219 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, recipients
);
223 public long sendMessageReaction(
225 final boolean remove
,
226 final String targetAuthor
,
227 final long targetSentTimestamp
,
228 final List
<String
> recipients
231 final var results
= m
.sendMessageReaction(emoji
,
233 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
235 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
236 .map(RecipientIdentifier
.class::cast
)
237 .collect(Collectors
.toSet()));
238 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
239 return results
.getTimestamp();
240 } catch (IOException e
) {
241 throw new Error
.Failure(e
.getMessage());
242 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
243 throw new Error
.GroupNotFound(e
.getMessage());
248 public void sendTyping(
249 final String recipient
, final boolean stop
250 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
252 var recipients
= new ArrayList
<String
>(1);
253 recipients
.add(recipient
);
254 m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
255 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
256 .map(RecipientIdentifier
.class::cast
)
257 .collect(Collectors
.toSet()));
258 } catch (IOException e
) {
259 throw new Error
.Failure(e
.getMessage());
260 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
261 throw new Error
.GroupNotFound(e
.getMessage());
262 } catch (UntrustedIdentityException e
) {
263 throw new Error
.UntrustedIdentity(e
.getMessage());
268 public void sendReadReceipt(
269 final String recipient
, final List
<Long
> messageIds
270 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
272 m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
273 } catch (IOException e
) {
274 throw new Error
.Failure(e
.getMessage());
275 } catch (UntrustedIdentityException e
) {
276 throw new Error
.UntrustedIdentity(e
.getMessage());
281 public void sendContacts() {
284 } catch (IOException e
) {
285 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
290 public void sendSyncRequest() {
292 m
.requestAllSyncData();
293 } catch (IOException e
) {
294 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
299 public long sendNoteToSelfMessage(
300 final String message
, final List
<String
> attachments
301 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
303 final var results
= m
.sendMessage(new Message(message
, attachments
),
304 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
305 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
306 return results
.getTimestamp();
307 } catch (AttachmentInvalidException e
) {
308 throw new Error
.AttachmentInvalid(e
.getMessage());
309 } catch (IOException e
) {
310 throw new Error
.Failure(e
.getMessage());
311 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
312 throw new Error
.GroupNotFound(e
.getMessage());
317 public void sendEndSessionMessage(final List
<String
> recipients
) {
319 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
320 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
321 } catch (IOException e
) {
322 throw new Error
.Failure(e
.getMessage());
327 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
329 var results
= m
.sendMessage(new Message(message
, attachments
),
330 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
331 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
332 return results
.getTimestamp();
333 } catch (IOException e
) {
334 throw new Error
.Failure(e
.getMessage());
335 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
336 throw new Error
.GroupNotFound(e
.getMessage());
337 } catch (AttachmentInvalidException e
) {
338 throw new Error
.AttachmentInvalid(e
.getMessage());
343 public long sendGroupMessageReaction(
345 final boolean remove
,
346 final String targetAuthor
,
347 final long targetSentTimestamp
,
351 final var results
= m
.sendMessageReaction(emoji
,
353 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
355 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
356 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
357 return results
.getTimestamp();
358 } catch (IOException e
) {
359 throw new Error
.Failure(e
.getMessage());
360 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
361 throw new Error
.GroupNotFound(e
.getMessage());
365 // Since contact names might be empty if not defined, also potentially return
368 public String
getContactName(final String number
) {
369 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
370 return name
== null ?
"" : name
;
374 public void setContactName(final String number
, final String name
) {
376 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
377 } catch (NotMasterDeviceException e
) {
378 throw new Error
.Failure("This command doesn't work on linked devices.");
379 } catch (UnregisteredUserException e
) {
380 throw new Error
.Failure("Contact is not registered.");
385 public void setExpirationTimer(final String number
, final int expiration
) {
387 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
388 } catch (IOException e
) {
389 throw new Error
.Failure(e
.getMessage());
394 public void setContactBlocked(final String number
, final boolean blocked
) {
396 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
397 } catch (NotMasterDeviceException e
) {
398 throw new Error
.Failure("This command doesn't work on linked devices.");
399 } catch (IOException e
) {
400 throw new Error
.Failure(e
.getMessage());
405 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
407 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
408 } catch (NotMasterDeviceException e
) {
409 throw new Error
.Failure("This command doesn't work on linked devices.");
410 } catch (GroupNotFoundException e
) {
411 throw new Error
.GroupNotFound(e
.getMessage());
412 } catch (IOException e
) {
413 throw new Error
.Failure(e
.getMessage());
418 public List
<byte[]> getGroupIds() {
419 var groups
= m
.getGroups();
420 var ids
= new ArrayList
<byte[]>(groups
.size());
421 for (var group
: groups
) {
422 ids
.add(group
.getGroupId().serialize());
428 public DBusPath
getGroup(final byte[] groupId
) {
430 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
431 if (groupOptional
.isEmpty()) {
432 throw new Error
.GroupNotFound("Group not found");
434 return groupOptional
.get().getObjectPath();
438 public List
<StructGroup
> listGroups() {
444 public String
getGroupName(final byte[] groupId
) {
445 var group
= m
.getGroup(getGroupId(groupId
));
446 if (group
== null || group
.getTitle() == null) {
449 return group
.getTitle();
454 public List
<String
> getGroupMembers(final byte[] groupId
) {
455 var group
= m
.getGroup(getGroupId(groupId
));
459 final var members
= group
.getMembers();
460 return getRecipientStrings(members
);
465 public byte[] createGroup(
466 final String name
, final List
<String
> members
, final String avatar
467 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
468 return updateGroup(new byte[0], name
, members
, avatar
);
472 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
474 groupId
= nullIfEmpty(groupId
);
475 name
= nullIfEmpty(name
);
476 avatar
= nullIfEmpty(avatar
);
477 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
478 if (groupId
== null) {
479 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
480 checkSendMessageResults(results
.second().getTimestamp(), results
.second().getResults());
481 return results
.first().serialize();
483 final var results
= m
.updateGroup(getGroupId(groupId
),
484 UpdateGroup
.newBuilder()
486 .withMembers(memberIdentifiers
)
487 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
489 if (results
!= null) {
490 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
494 } catch (IOException e
) {
495 throw new Error
.Failure(e
.getMessage());
496 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
497 throw new Error
.GroupNotFound(e
.getMessage());
498 } catch (AttachmentInvalidException e
) {
499 throw new Error
.AttachmentInvalid(e
.getMessage());
504 public boolean isRegistered() {
509 public boolean isRegistered(String number
) {
510 var result
= isRegistered(List
.of(number
));
511 return result
.get(0);
515 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
516 var results
= new ArrayList
<Boolean
>();
517 if (numbers
.isEmpty()) {
521 Map
<String
, Pair
<String
, UUID
>> registered
;
523 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
524 } catch (IOException e
) {
525 throw new Error
.Failure(e
.getMessage());
528 return numbers
.stream().map(number
-> {
529 var uuid
= registered
.get(number
).second();
531 }).collect(Collectors
.toList());
535 public void updateProfile(
541 final boolean removeAvatar
544 givenName
= nullIfEmpty(givenName
);
545 familyName
= nullIfEmpty(familyName
);
546 about
= nullIfEmpty(about
);
547 aboutEmoji
= nullIfEmpty(aboutEmoji
);
548 avatarPath
= nullIfEmpty(avatarPath
);
549 Optional
<File
> avatarFile
= removeAvatar
551 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
552 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
553 } catch (IOException e
) {
554 throw new Error
.Failure(e
.getMessage());
559 public void updateProfile(
562 final String aboutEmoji
,
564 final boolean removeAvatar
566 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
570 public void removePin() {
572 m
.setRegistrationLockPin(Optional
.absent());
573 } catch (UnauthenticatedResponseException e
) {
574 throw new Error
.Failure("Remove pin failed with unauthenticated response: " + e
.getMessage());
575 } catch (IOException e
) {
576 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
581 public void setPin(String registrationLockPin
) {
583 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
584 } catch (UnauthenticatedResponseException e
) {
585 throw new Error
.Failure("Set pin error failed with unauthenticated response: " + e
.getMessage());
586 } catch (IOException e
) {
587 throw new Error
.Failure("Set pin error: " + e
.getMessage());
591 // Provide option to query a version string in order to react on potential
592 // future interface changes
594 public String
version() {
595 return BaseConfig
.PROJECT_VERSION
;
598 // Create a unique list of Numbers from Identities and Contacts to really get
599 // all numbers the system knows
601 public List
<String
> listNumbers() {
602 return Stream
.concat(m
.getIdentities().stream().map(Identity
::getRecipient
),
603 m
.getContacts().stream().map(Pair
::first
))
604 .map(a
-> a
.getNumber().orElse(null))
605 .filter(Objects
::nonNull
)
607 .collect(Collectors
.toList());
611 public List
<String
> getContactNumber(final String name
) {
612 // Contact names have precedence.
613 var numbers
= new ArrayList
<String
>();
614 var contacts
= m
.getContacts();
615 for (var c
: contacts
) {
616 if (name
.equals(c
.second().getName())) {
617 numbers
.add(c
.first().getLegacyIdentifier());
620 // Try profiles if no contact name was found
621 for (var identity
: m
.getIdentities()) {
622 final var address
= identity
.getRecipient();
623 var number
= address
.getNumber().orElse(null);
624 if (number
!= null) {
625 Profile profile
= null;
627 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
628 } catch (UnregisteredUserException ignored
) {
630 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
639 public void quitGroup(final byte[] groupId
) {
640 var group
= getGroupId(groupId
);
642 m
.quitGroup(group
, Set
.of());
643 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
644 throw new Error
.GroupNotFound(e
.getMessage());
645 } catch (IOException
| LastGroupAdminException e
) {
646 throw new Error
.Failure(e
.getMessage());
651 public byte[] joinGroup(final String groupLink
) {
653 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
654 if (linkUrl
== null) {
655 throw new Error
.Failure("Group link is invalid:");
657 final var result
= m
.joinGroup(linkUrl
);
658 return result
.first().serialize();
659 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| GroupLinkNotActiveException e
) {
660 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
661 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
662 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
663 } catch (IOException e
) {
664 throw new Error
.Failure(e
.getMessage());
669 public boolean isContactBlocked(final String number
) {
670 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
674 public boolean isGroupBlocked(final byte[] groupId
) {
675 var group
= m
.getGroup(getGroupId(groupId
));
679 return group
.isBlocked();
684 public boolean isMember(final byte[] groupId
) {
685 var group
= m
.getGroup(getGroupId(groupId
));
689 return group
.isMember();
694 public String
uploadStickerPack(String stickerPackPath
) {
695 File path
= new File(stickerPackPath
);
697 return m
.uploadStickerPack(path
).toString();
698 } catch (IOException e
) {
699 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
700 } catch (StickerPackInvalidException e
) {
701 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
705 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
706 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
712 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
714 if (result
.getIdentityFailure() != null) {
715 throw new Error
.UntrustedIdentity(message
);
717 throw new Error
.Failure(message
);
721 private static void checkSendMessageResults(
722 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
723 ) throws DBusExecutionException
{
724 final var sendMessageResults
= results
.values().stream().findFirst();
725 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
726 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
730 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
731 if (errors
.size() == 0) {
735 var message
= new StringBuilder();
736 message
.append(timestamp
).append('\n');
737 message
.append("Failed to send (some) messages:\n");
738 for (var error
: errors
) {
739 message
.append(error
).append('\n');
742 throw new Error
.Failure(message
.toString());
745 private static void checkSendMessageResults(
746 long timestamp
, Collection
<SendMessageResult
> results
747 ) throws DBusExecutionException
{
748 if (results
.size() == 1) {
749 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
753 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
754 if (errors
.size() == 0) {
758 var message
= new StringBuilder();
759 message
.append(timestamp
).append('\n');
760 message
.append("Failed to send (some) messages:\n");
761 for (var error
: errors
) {
762 message
.append(error
).append('\n');
765 throw new Error
.Failure(message
.toString());
768 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
769 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).collect(Collectors
.toList());
772 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
773 final Collection
<String
> recipientStrings
, final String localNumber
774 ) throws DBusExecutionException
{
775 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
776 for (var recipientString
: recipientStrings
) {
777 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
782 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
783 final String recipientString
, final String localNumber
784 ) throws DBusExecutionException
{
786 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
787 } catch (InvalidNumberException e
) {
788 throw new Error
.InvalidNumber(e
.getMessage());
792 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
794 return GroupId
.unknownVersion(groupId
);
795 } catch (Throwable e
) {
796 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
800 private byte[] nullIfEmpty(final byte[] array
) {
801 return array
.length
== 0 ?
null : array
;
804 private String
nullIfEmpty(final String name
) {
805 return name
.isEmpty() ?
null : name
;
808 private String
emptyIfNull(final String string
) {
809 return string
== null ?
"" : string
;
812 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
813 return basePath
+ "/Devices/" + deviceId
;
816 private void updateDevices() {
817 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
819 linkedDevices
= m
.getLinkedDevices();
820 } catch (IOException e
) {
821 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
826 linkedDevices
.forEach(d
-> {
827 final var object
= new DbusSignalDeviceImpl(d
);
828 final var deviceObjectPath
= object
.getObjectPath();
830 connection
.exportObject(object
);
831 } catch (DBusException e
) {
834 if (d
.isThisDevice()) {
835 thisDevice
= new DBusPath(deviceObjectPath
);
837 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.getId(), emptyIfNull(d
.getName())));
841 private void unExportDevices() {
842 this.devices
.stream()
843 .map(StructDevice
::getObjectPath
)
844 .map(DBusPath
::getPath
)
845 .forEach(connection
::unExportObject
);
846 this.devices
.clear();
849 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
850 return basePath
+ "/Groups/" + Base64
.getEncoder()
851 .encodeToString(groupId
)
857 private void updateGroups() {
858 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
859 groups
= m
.getGroups();
863 groups
.forEach(g
-> {
864 final var object
= new DbusSignalGroupImpl(g
.getGroupId());
866 connection
.exportObject(object
);
867 } catch (DBusException e
) {
870 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
871 g
.getGroupId().serialize(),
872 emptyIfNull(g
.getTitle())));
876 private void unExportGroups() {
877 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
881 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
883 private final org
.asamk
.signal
.manager
.api
.Device device
;
885 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
886 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
887 List
.of(new DbusProperty
<>("Id", device
::getId
),
888 new DbusProperty
<>("Name", () -> emptyIfNull(device
.getName()), this::setDeviceName
),
889 new DbusProperty
<>("Created", device
::getCreated
),
890 new DbusProperty
<>("LastSeen", device
::getLastSeen
))));
891 this.device
= device
;
895 public String
getObjectPath() {
896 return getDeviceObjectPath(objectPath
, device
.getId());
900 public void removeDevice() throws Error
.Failure
{
902 m
.removeLinkedDevices(device
.getId());
904 } catch (IOException e
) {
905 throw new Error
.Failure(e
.getMessage());
909 private void setDeviceName(String name
) {
910 if (!device
.isThisDevice()) {
911 throw new Error
.Failure("Only the name of this device can be changed");
914 m
.updateAccountAttributes(name
);
915 // update device list
917 } catch (IOException e
) {
918 throw new Error
.Failure(e
.getMessage());
923 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
925 private final GroupId groupId
;
927 public DbusSignalGroupImpl(final GroupId groupId
) {
928 this.groupId
= groupId
;
929 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
930 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
931 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().getTitle()), this::setGroupName
),
932 new DbusProperty
<>("Description",
933 () -> emptyIfNull(getGroup().getDescription()),
934 this::setGroupDescription
),
935 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
936 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
937 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
938 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
939 new DbusProperty
<>("MessageExpirationTimer",
940 () -> getGroup().getMessageExpirationTimer(),
941 this::setMessageExpirationTime
),
942 new DbusProperty
<>("Members",
943 () -> new Variant
<>(getRecipientStrings(getGroup().getMembers()), "as")),
944 new DbusProperty
<>("PendingMembers",
945 () -> new Variant
<>(getRecipientStrings(getGroup().getPendingMembers()), "as")),
946 new DbusProperty
<>("RequestingMembers",
947 () -> new Variant
<>(getRecipientStrings(getGroup().getRequestingMembers()), "as")),
948 new DbusProperty
<>("Admins",
949 () -> new Variant
<>(getRecipientStrings(getGroup().getAdminMembers()), "as")),
950 new DbusProperty
<>("PermissionAddMember",
951 () -> getGroup().getPermissionAddMember().name(),
952 this::setGroupPermissionAddMember
),
953 new DbusProperty
<>("PermissionEditDetails",
954 () -> getGroup().getPermissionEditDetails().name(),
955 this::setGroupPermissionEditDetails
),
956 new DbusProperty
<>("PermissionSendMessage",
957 () -> getGroup().getPermissionSendMessage().name(),
958 this::setGroupPermissionSendMessage
),
959 new DbusProperty
<>("GroupInviteLink", () -> {
960 final var groupInviteLinkUrl
= getGroup().getGroupInviteLinkUrl();
961 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
966 public String
getObjectPath() {
967 return getGroupObjectPath(objectPath
, groupId
.serialize());
971 public void quitGroup() throws Error
.Failure
{
973 m
.quitGroup(groupId
, Set
.of());
974 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
975 throw new Error
.GroupNotFound(e
.getMessage());
976 } catch (IOException e
) {
977 throw new Error
.Failure(e
.getMessage());
978 } catch (LastGroupAdminException e
) {
979 throw new Error
.LastGroupAdmin(e
.getMessage());
984 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
985 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
986 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
990 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
991 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
992 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
996 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
997 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
998 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1002 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1003 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1004 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1008 public void resetLink() throws Error
.Failure
{
1009 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1013 public void disableLink() throws Error
.Failure
{
1014 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1018 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1019 updateGroup(UpdateGroup
.newBuilder()
1020 .withGroupLinkState(requiresApproval
1021 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1022 : GroupLinkState
.ENABLED
)
1026 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1027 return m
.getGroup(groupId
);
1030 private void setGroupName(final String name
) {
1031 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1034 private void setGroupDescription(final String description
) {
1035 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1038 private void setGroupAvatar(final String avatar
) {
1039 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1042 private void setMessageExpirationTime(final int expirationTime
) {
1043 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1046 private void setGroupPermissionAddMember(final String permission
) {
1047 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1050 private void setGroupPermissionEditDetails(final String permission
) {
1051 updateGroup(UpdateGroup
.newBuilder()
1052 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1056 private void setGroupPermissionSendMessage(final String permission
) {
1057 updateGroup(UpdateGroup
.newBuilder()
1058 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1062 private void setIsBlocked(final boolean isBlocked
) {
1064 m
.setGroupBlocked(groupId
, isBlocked
);
1065 } catch (NotMasterDeviceException e
) {
1066 throw new Error
.Failure("This command doesn't work on linked devices.");
1067 } catch (GroupNotFoundException e
) {
1068 throw new Error
.GroupNotFound(e
.getMessage());
1069 } catch (IOException e
) {
1070 throw new Error
.Failure(e
.getMessage());
1074 private void updateGroup(final UpdateGroup updateGroup
) {
1076 m
.updateGroup(groupId
, updateGroup
);
1077 } catch (IOException e
) {
1078 throw new Error
.Failure(e
.getMessage());
1079 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1080 throw new Error
.GroupNotFound(e
.getMessage());
1081 } catch (AttachmentInvalidException e
) {
1082 throw new Error
.AttachmentInvalid(e
.getMessage());