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
.InvalidDeviceLinkException
;
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
.TypingAction
;
17 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
18 import org
.asamk
.signal
.manager
.groups
.GroupId
;
19 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
20 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
21 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
22 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
23 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
24 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
25 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
26 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
27 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
28 import org
.asamk
.signal
.util
.ErrorUtils
;
29 import org
.freedesktop
.dbus
.DBusPath
;
30 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
31 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
32 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
33 import org
.freedesktop
.dbus
.types
.Variant
;
34 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
35 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
36 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
37 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
38 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
41 import java
.io
.IOException
;
43 import java
.net
.URISyntaxException
;
44 import java
.util
.ArrayList
;
45 import java
.util
.Arrays
;
46 import java
.util
.Base64
;
47 import java
.util
.Collection
;
48 import java
.util
.HashSet
;
49 import java
.util
.List
;
51 import java
.util
.Objects
;
52 import java
.util
.Optional
;
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() {
85 public String
getObjectPath() {
90 public String
getSelfNumber() {
91 return m
.getSelfNumber();
95 public void submitRateLimitChallenge(String challenge
, String captchaString
) throws IOErrorException
{
96 final var captcha
= captchaString
== null ?
null : captchaString
.replace("signalcaptcha://", "");
99 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
100 } catch (IOException e
) {
101 throw new IOErrorException("Submit challenge error: " + e
.getMessage(), e
);
107 public void addDevice(String uri
) {
109 m
.addDeviceLink(new URI(uri
));
110 } catch (IOException
| InvalidDeviceLinkException e
) {
111 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
112 } catch (URISyntaxException e
) {
113 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
114 + " Device link uri has invalid format: "
120 public DBusPath
getDevice(long deviceId
) {
122 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
123 if (deviceOptional
.isEmpty()) {
124 throw new Error
.DeviceNotFound("Device not found");
126 return deviceOptional
.get().getObjectPath();
130 public List
<StructDevice
> listDevices() {
136 public DBusPath
getThisDevice() {
142 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
143 var recipients
= new ArrayList
<String
>(1);
144 recipients
.add(recipient
);
145 return sendMessage(message
, attachments
, recipients
);
149 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
151 final var results
= m
.sendMessage(new Message(message
, attachments
),
152 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
153 .map(RecipientIdentifier
.class::cast
)
154 .collect(Collectors
.toSet()));
156 checkSendMessageResults(results
.timestamp(), results
.results());
157 return results
.timestamp();
158 } catch (AttachmentInvalidException e
) {
159 throw new Error
.AttachmentInvalid(e
.getMessage());
160 } catch (IOException e
) {
161 throw new Error
.Failure(e
);
162 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
163 throw new Error
.GroupNotFound(e
.getMessage());
168 public long sendRemoteDeleteMessage(
169 final long targetSentTimestamp
, final String recipient
171 var recipients
= new ArrayList
<String
>(1);
172 recipients
.add(recipient
);
173 return sendRemoteDeleteMessage(targetSentTimestamp
, recipients
);
177 public long sendRemoteDeleteMessage(
178 final long targetSentTimestamp
, final List
<String
> recipients
181 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
182 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
183 .map(RecipientIdentifier
.class::cast
)
184 .collect(Collectors
.toSet()));
185 checkSendMessageResults(results
.timestamp(), results
.results());
186 return results
.timestamp();
187 } catch (IOException e
) {
188 throw new Error
.Failure(e
.getMessage());
189 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
190 throw new Error
.GroupNotFound(e
.getMessage());
195 public long sendGroupRemoteDeleteMessage(
196 final long targetSentTimestamp
, final byte[] groupId
199 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
200 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
201 checkSendMessageResults(results
.timestamp(), results
.results());
202 return results
.timestamp();
203 } catch (IOException e
) {
204 throw new Error
.Failure(e
.getMessage());
205 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
206 throw new Error
.GroupNotFound(e
.getMessage());
211 public long sendMessageReaction(
213 final boolean remove
,
214 final String targetAuthor
,
215 final long targetSentTimestamp
,
216 final String recipient
218 var recipients
= new ArrayList
<String
>(1);
219 recipients
.add(recipient
);
220 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, recipients
);
224 public long sendMessageReaction(
226 final boolean remove
,
227 final String targetAuthor
,
228 final long targetSentTimestamp
,
229 final List
<String
> recipients
232 final var results
= m
.sendMessageReaction(emoji
,
234 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
236 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
237 .map(RecipientIdentifier
.class::cast
)
238 .collect(Collectors
.toSet()));
239 checkSendMessageResults(results
.timestamp(), results
.results());
240 return results
.timestamp();
241 } catch (IOException e
) {
242 throw new Error
.Failure(e
.getMessage());
243 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
244 throw new Error
.GroupNotFound(e
.getMessage());
249 public void sendTyping(
250 final String recipient
, final boolean stop
251 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
253 var recipients
= new ArrayList
<String
>(1);
254 recipients
.add(recipient
);
255 m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
256 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
257 .map(RecipientIdentifier
.class::cast
)
258 .collect(Collectors
.toSet()));
259 } catch (IOException e
) {
260 throw new Error
.Failure(e
.getMessage());
261 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
262 throw new Error
.GroupNotFound(e
.getMessage());
263 } catch (UntrustedIdentityException e
) {
264 throw new Error
.UntrustedIdentity(e
.getMessage());
269 public void sendReadReceipt(
270 final String recipient
, final List
<Long
> messageIds
271 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
273 m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
274 } catch (IOException e
) {
275 throw new Error
.Failure(e
.getMessage());
276 } catch (UntrustedIdentityException e
) {
277 throw new Error
.UntrustedIdentity(e
.getMessage());
282 public void sendViewedReceipt(
283 final String recipient
, final List
<Long
> messageIds
284 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
286 m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
287 } catch (IOException e
) {
288 throw new Error
.Failure(e
.getMessage());
289 } catch (UntrustedIdentityException e
) {
290 throw new Error
.UntrustedIdentity(e
.getMessage());
295 public void sendContacts() {
298 } catch (IOException e
) {
299 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
304 public void sendSyncRequest() {
306 m
.requestAllSyncData();
307 } catch (IOException e
) {
308 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
313 public long sendNoteToSelfMessage(
314 final String message
, final List
<String
> attachments
315 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
317 final var results
= m
.sendMessage(new Message(message
, attachments
),
318 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
319 checkSendMessageResults(results
.timestamp(), results
.results());
320 return results
.timestamp();
321 } catch (AttachmentInvalidException e
) {
322 throw new Error
.AttachmentInvalid(e
.getMessage());
323 } catch (IOException e
) {
324 throw new Error
.Failure(e
.getMessage());
325 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
326 throw new Error
.GroupNotFound(e
.getMessage());
331 public void sendEndSessionMessage(final List
<String
> recipients
) {
333 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
334 checkSendMessageResults(results
.timestamp(), results
.results());
335 } catch (IOException e
) {
336 throw new Error
.Failure(e
.getMessage());
341 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
343 var results
= m
.sendMessage(new Message(message
, attachments
),
344 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
345 checkSendMessageResults(results
.timestamp(), results
.results());
346 return results
.timestamp();
347 } catch (IOException e
) {
348 throw new Error
.Failure(e
.getMessage());
349 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
350 throw new Error
.GroupNotFound(e
.getMessage());
351 } catch (AttachmentInvalidException e
) {
352 throw new Error
.AttachmentInvalid(e
.getMessage());
357 public long sendGroupMessageReaction(
359 final boolean remove
,
360 final String targetAuthor
,
361 final long targetSentTimestamp
,
365 final var results
= m
.sendMessageReaction(emoji
,
367 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
369 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
370 checkSendMessageResults(results
.timestamp(), results
.results());
371 return results
.timestamp();
372 } catch (IOException e
) {
373 throw new Error
.Failure(e
.getMessage());
374 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
375 throw new Error
.GroupNotFound(e
.getMessage());
379 // Since contact names might be empty if not defined, also potentially return
382 public String
getContactName(final String number
) {
383 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
384 return name
== null ?
"" : name
;
388 public void setContactName(final String number
, final String name
) {
390 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
391 } catch (NotMasterDeviceException e
) {
392 throw new Error
.Failure("This command doesn't work on linked devices.");
393 } catch (UnregisteredUserException e
) {
394 throw new Error
.Failure("Contact is not registered.");
399 public void setExpirationTimer(final String number
, final int expiration
) {
401 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
402 } catch (IOException e
) {
403 throw new Error
.Failure(e
.getMessage());
408 public void setContactBlocked(final String number
, final boolean blocked
) {
410 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
411 } catch (NotMasterDeviceException e
) {
412 throw new Error
.Failure("This command doesn't work on linked devices.");
413 } catch (IOException e
) {
414 throw new Error
.Failure(e
.getMessage());
419 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
421 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
422 } catch (NotMasterDeviceException e
) {
423 throw new Error
.Failure("This command doesn't work on linked devices.");
424 } catch (GroupNotFoundException e
) {
425 throw new Error
.GroupNotFound(e
.getMessage());
426 } catch (IOException e
) {
427 throw new Error
.Failure(e
.getMessage());
432 public List
<byte[]> getGroupIds() {
433 var groups
= m
.getGroups();
434 var ids
= new ArrayList
<byte[]>(groups
.size());
435 for (var group
: groups
) {
436 ids
.add(group
.groupId().serialize());
442 public DBusPath
getGroup(final byte[] groupId
) {
444 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
445 if (groupOptional
.isEmpty()) {
446 throw new Error
.GroupNotFound("Group not found");
448 return groupOptional
.get().getObjectPath();
452 public List
<StructGroup
> listGroups() {
458 public String
getGroupName(final byte[] groupId
) {
459 var group
= m
.getGroup(getGroupId(groupId
));
460 if (group
== null || group
.title() == null) {
463 return group
.title();
468 public List
<String
> getGroupMembers(final byte[] groupId
) {
469 var group
= m
.getGroup(getGroupId(groupId
));
473 final var members
= group
.members();
474 return getRecipientStrings(members
);
479 public byte[] createGroup(
480 final String name
, final List
<String
> members
, final String avatar
481 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
482 return updateGroup(new byte[0], name
, members
, avatar
);
486 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
488 groupId
= nullIfEmpty(groupId
);
489 name
= nullIfEmpty(name
);
490 avatar
= nullIfEmpty(avatar
);
491 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
492 if (groupId
== null) {
493 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
494 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
495 return results
.first().serialize();
497 final var results
= m
.updateGroup(getGroupId(groupId
),
498 UpdateGroup
.newBuilder()
500 .withMembers(memberIdentifiers
)
501 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
503 if (results
!= null) {
504 checkSendMessageResults(results
.timestamp(), results
.results());
508 } catch (IOException e
) {
509 throw new Error
.Failure(e
.getMessage());
510 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
511 throw new Error
.GroupNotFound(e
.getMessage());
512 } catch (AttachmentInvalidException e
) {
513 throw new Error
.AttachmentInvalid(e
.getMessage());
518 public boolean isRegistered() {
523 public boolean isRegistered(String number
) {
524 var result
= isRegistered(List
.of(number
));
525 return result
.get(0);
529 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
530 var results
= new ArrayList
<Boolean
>();
531 if (numbers
.isEmpty()) {
535 Map
<String
, Pair
<String
, UUID
>> registered
;
537 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
538 } catch (IOException e
) {
539 throw new Error
.Failure(e
.getMessage());
542 return numbers
.stream().map(number
-> {
543 var uuid
= registered
.get(number
).second();
545 }).collect(Collectors
.toList());
549 public void updateProfile(
555 final boolean removeAvatar
558 givenName
= nullIfEmpty(givenName
);
559 familyName
= nullIfEmpty(familyName
);
560 about
= nullIfEmpty(about
);
561 aboutEmoji
= nullIfEmpty(aboutEmoji
);
562 avatarPath
= nullIfEmpty(avatarPath
);
563 Optional
<File
> avatarFile
= removeAvatar
565 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
566 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
567 } catch (IOException e
) {
568 throw new Error
.Failure(e
.getMessage());
573 public void updateProfile(
576 final String aboutEmoji
,
578 final boolean removeAvatar
580 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
584 public void removePin() {
586 m
.setRegistrationLockPin(Optional
.empty());
587 } catch (UnauthenticatedResponseException e
) {
588 throw new Error
.Failure("Remove pin failed with unauthenticated response: " + e
.getMessage());
589 } catch (IOException e
) {
590 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
595 public void setPin(String registrationLockPin
) {
597 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
598 } catch (UnauthenticatedResponseException e
) {
599 throw new Error
.Failure("Set pin error failed with unauthenticated response: " + e
.getMessage());
600 } catch (IOException e
) {
601 throw new Error
.Failure("Set pin error: " + e
.getMessage());
605 // Provide option to query a version string in order to react on potential
606 // future interface changes
608 public String
version() {
609 return BaseConfig
.PROJECT_VERSION
;
612 // Create a unique list of Numbers from Identities and Contacts to really get
613 // all numbers the system knows
615 public List
<String
> listNumbers() {
616 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
617 m
.getContacts().stream().map(Pair
::first
))
618 .map(a
-> a
.getNumber().orElse(null))
619 .filter(Objects
::nonNull
)
621 .collect(Collectors
.toList());
625 public List
<String
> getContactNumber(final String name
) {
626 // Contact names have precedence.
627 var numbers
= new ArrayList
<String
>();
628 var contacts
= m
.getContacts();
629 for (var c
: contacts
) {
630 if (name
.equals(c
.second().getName())) {
631 numbers
.add(c
.first().getLegacyIdentifier());
634 // Try profiles if no contact name was found
635 for (var identity
: m
.getIdentities()) {
636 final var address
= identity
.recipient();
637 var number
= address
.getNumber().orElse(null);
638 if (number
!= null) {
639 Profile profile
= null;
641 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
642 } catch (UnregisteredUserException ignored
) {
644 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
653 public void quitGroup(final byte[] groupId
) {
654 var group
= getGroupId(groupId
);
656 m
.quitGroup(group
, Set
.of());
657 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
658 throw new Error
.GroupNotFound(e
.getMessage());
659 } catch (IOException
| LastGroupAdminException e
) {
660 throw new Error
.Failure(e
.getMessage());
665 public byte[] joinGroup(final String groupLink
) {
667 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
668 if (linkUrl
== null) {
669 throw new Error
.Failure("Group link is invalid:");
671 final var result
= m
.joinGroup(linkUrl
);
672 return result
.first().serialize();
673 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| GroupLinkNotActiveException e
) {
674 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
675 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
676 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
677 } catch (IOException e
) {
678 throw new Error
.Failure(e
.getMessage());
683 public boolean isContactBlocked(final String number
) {
684 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
688 public boolean isGroupBlocked(final byte[] groupId
) {
689 var group
= m
.getGroup(getGroupId(groupId
));
693 return group
.isBlocked();
698 public boolean isMember(final byte[] groupId
) {
699 var group
= m
.getGroup(getGroupId(groupId
));
703 return group
.isMember();
708 public String
uploadStickerPack(String stickerPackPath
) {
709 File path
= new File(stickerPackPath
);
711 return m
.uploadStickerPack(path
).toString();
712 } catch (IOException e
) {
713 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
714 } catch (StickerPackInvalidException e
) {
715 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
719 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
720 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
726 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
728 if (result
.getIdentityFailure() != null) {
729 throw new Error
.UntrustedIdentity(message
);
731 throw new Error
.Failure(message
);
735 private static void checkSendMessageResults(
736 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
737 ) throws DBusExecutionException
{
738 final var sendMessageResults
= results
.values().stream().findFirst();
739 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
740 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
744 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
745 if (errors
.size() == 0) {
749 var message
= new StringBuilder();
750 message
.append(timestamp
).append('\n');
751 message
.append("Failed to send (some) messages:\n");
752 for (var error
: errors
) {
753 message
.append(error
).append('\n');
756 throw new Error
.Failure(message
.toString());
759 private static void checkSendMessageResults(
760 long timestamp
, Collection
<SendMessageResult
> results
761 ) throws DBusExecutionException
{
762 if (results
.size() == 1) {
763 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
767 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
768 if (errors
.size() == 0) {
772 var message
= new StringBuilder();
773 message
.append(timestamp
).append('\n');
774 message
.append("Failed to send (some) messages:\n");
775 for (var error
: errors
) {
776 message
.append(error
).append('\n');
779 throw new Error
.Failure(message
.toString());
782 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
783 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).collect(Collectors
.toList());
786 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
787 final Collection
<String
> recipientStrings
, final String localNumber
788 ) throws DBusExecutionException
{
789 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
790 for (var recipientString
: recipientStrings
) {
791 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
796 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
797 final String recipientString
, final String localNumber
798 ) throws DBusExecutionException
{
800 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
801 } catch (InvalidNumberException e
) {
802 throw new Error
.InvalidNumber(e
.getMessage());
806 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
808 return GroupId
.unknownVersion(groupId
);
809 } catch (Throwable e
) {
810 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
814 private byte[] nullIfEmpty(final byte[] array
) {
815 return array
.length
== 0 ?
null : array
;
818 private String
nullIfEmpty(final String name
) {
819 return name
.isEmpty() ?
null : name
;
822 private String
emptyIfNull(final String string
) {
823 return string
== null ?
"" : string
;
826 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
827 return basePath
+ "/Devices/" + deviceId
;
830 private void updateDevices() {
831 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
833 linkedDevices
= m
.getLinkedDevices();
834 } catch (IOException e
) {
835 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
840 linkedDevices
.forEach(d
-> {
841 final var object
= new DbusSignalDeviceImpl(d
);
842 final var deviceObjectPath
= object
.getObjectPath();
844 connection
.exportObject(object
);
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 } catch (DBusException e
) {
884 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
885 g
.groupId().serialize(),
886 emptyIfNull(g
.title())));
890 private void unExportGroups() {
891 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
895 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
897 private final org
.asamk
.signal
.manager
.api
.Device device
;
899 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
900 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
901 List
.of(new DbusProperty
<>("Id", device
::id
),
902 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
903 new DbusProperty
<>("Created", device
::created
),
904 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
905 this.device
= device
;
909 public String
getObjectPath() {
910 return getDeviceObjectPath(objectPath
, device
.id());
914 public void removeDevice() throws Error
.Failure
{
916 m
.removeLinkedDevices(device
.id());
918 } catch (IOException e
) {
919 throw new Error
.Failure(e
.getMessage());
923 private void setDeviceName(String name
) {
924 if (!device
.isThisDevice()) {
925 throw new Error
.Failure("Only the name of this device can be changed");
928 m
.updateAccountAttributes(name
);
929 // update device list
931 } catch (IOException e
) {
932 throw new Error
.Failure(e
.getMessage());
937 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
939 private final GroupId groupId
;
941 public DbusSignalGroupImpl(final GroupId groupId
) {
942 this.groupId
= groupId
;
943 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
944 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
945 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
946 new DbusProperty
<>("Description",
947 () -> emptyIfNull(getGroup().description()),
948 this::setGroupDescription
),
949 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
950 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
951 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
952 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
953 new DbusProperty
<>("MessageExpirationTimer",
954 () -> getGroup().messageExpirationTimer(),
955 this::setMessageExpirationTime
),
956 new DbusProperty
<>("Members",
957 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
958 new DbusProperty
<>("PendingMembers",
959 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
960 new DbusProperty
<>("RequestingMembers",
961 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
962 new DbusProperty
<>("Admins",
963 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
964 new DbusProperty
<>("PermissionAddMember",
965 () -> getGroup().permissionAddMember().name(),
966 this::setGroupPermissionAddMember
),
967 new DbusProperty
<>("PermissionEditDetails",
968 () -> getGroup().permissionEditDetails().name(),
969 this::setGroupPermissionEditDetails
),
970 new DbusProperty
<>("PermissionSendMessage",
971 () -> getGroup().permissionSendMessage().name(),
972 this::setGroupPermissionSendMessage
),
973 new DbusProperty
<>("GroupInviteLink", () -> {
974 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
975 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
980 public String
getObjectPath() {
981 return getGroupObjectPath(objectPath
, groupId
.serialize());
985 public void quitGroup() throws Error
.Failure
{
987 m
.quitGroup(groupId
, Set
.of());
988 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
989 throw new Error
.GroupNotFound(e
.getMessage());
990 } catch (IOException e
) {
991 throw new Error
.Failure(e
.getMessage());
992 } catch (LastGroupAdminException e
) {
993 throw new Error
.LastGroupAdmin(e
.getMessage());
998 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
999 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1000 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1004 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1005 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1006 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1010 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1011 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1012 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1016 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1017 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1018 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1022 public void resetLink() throws Error
.Failure
{
1023 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1027 public void disableLink() throws Error
.Failure
{
1028 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1032 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1033 updateGroup(UpdateGroup
.newBuilder()
1034 .withGroupLinkState(requiresApproval
1035 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1036 : GroupLinkState
.ENABLED
)
1040 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1041 return m
.getGroup(groupId
);
1044 private void setGroupName(final String name
) {
1045 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1048 private void setGroupDescription(final String description
) {
1049 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1052 private void setGroupAvatar(final String avatar
) {
1053 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1056 private void setMessageExpirationTime(final int expirationTime
) {
1057 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1060 private void setGroupPermissionAddMember(final String permission
) {
1061 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1064 private void setGroupPermissionEditDetails(final String permission
) {
1065 updateGroup(UpdateGroup
.newBuilder()
1066 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1070 private void setGroupPermissionSendMessage(final String permission
) {
1071 updateGroup(UpdateGroup
.newBuilder()
1072 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1076 private void setIsBlocked(final boolean isBlocked
) {
1078 m
.setGroupBlocked(groupId
, isBlocked
);
1079 } catch (NotMasterDeviceException e
) {
1080 throw new Error
.Failure("This command doesn't work on linked devices.");
1081 } catch (GroupNotFoundException e
) {
1082 throw new Error
.GroupNotFound(e
.getMessage());
1083 } catch (IOException e
) {
1084 throw new Error
.Failure(e
.getMessage());
1088 private void updateGroup(final UpdateGroup updateGroup
) {
1090 m
.updateGroup(groupId
, updateGroup
);
1091 } catch (IOException e
) {
1092 throw new Error
.Failure(e
.getMessage());
1093 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1094 throw new Error
.GroupNotFound(e
.getMessage());
1095 } catch (AttachmentInvalidException e
) {
1096 throw new Error
.AttachmentInvalid(e
.getMessage());