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() {
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
| InvalidKeyException 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 sendContacts() {
285 } catch (IOException e
) {
286 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
291 public void sendSyncRequest() {
293 m
.requestAllSyncData();
294 } catch (IOException e
) {
295 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
300 public long sendNoteToSelfMessage(
301 final String message
, final List
<String
> attachments
302 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
304 final var results
= m
.sendMessage(new Message(message
, attachments
),
305 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
306 checkSendMessageResults(results
.timestamp(), results
.results());
307 return results
.timestamp();
308 } catch (AttachmentInvalidException e
) {
309 throw new Error
.AttachmentInvalid(e
.getMessage());
310 } catch (IOException e
) {
311 throw new Error
.Failure(e
.getMessage());
312 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
313 throw new Error
.GroupNotFound(e
.getMessage());
318 public void sendEndSessionMessage(final List
<String
> recipients
) {
320 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
321 checkSendMessageResults(results
.timestamp(), results
.results());
322 } catch (IOException e
) {
323 throw new Error
.Failure(e
.getMessage());
328 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
330 var results
= m
.sendMessage(new Message(message
, attachments
),
331 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
332 checkSendMessageResults(results
.timestamp(), results
.results());
333 return results
.timestamp();
334 } catch (IOException e
) {
335 throw new Error
.Failure(e
.getMessage());
336 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
337 throw new Error
.GroupNotFound(e
.getMessage());
338 } catch (AttachmentInvalidException e
) {
339 throw new Error
.AttachmentInvalid(e
.getMessage());
344 public long sendGroupMessageReaction(
346 final boolean remove
,
347 final String targetAuthor
,
348 final long targetSentTimestamp
,
352 final var results
= m
.sendMessageReaction(emoji
,
354 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
356 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
357 checkSendMessageResults(results
.timestamp(), results
.results());
358 return results
.timestamp();
359 } catch (IOException e
) {
360 throw new Error
.Failure(e
.getMessage());
361 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
362 throw new Error
.GroupNotFound(e
.getMessage());
366 // Since contact names might be empty if not defined, also potentially return
369 public String
getContactName(final String number
) {
370 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
371 return name
== null ?
"" : name
;
375 public void setContactName(final String number
, final String name
) {
377 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
378 } catch (NotMasterDeviceException e
) {
379 throw new Error
.Failure("This command doesn't work on linked devices.");
380 } catch (UnregisteredUserException e
) {
381 throw new Error
.Failure("Contact is not registered.");
386 public void setExpirationTimer(final String number
, final int expiration
) {
388 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
389 } catch (IOException e
) {
390 throw new Error
.Failure(e
.getMessage());
395 public void setContactBlocked(final String number
, final boolean blocked
) {
397 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
398 } catch (NotMasterDeviceException e
) {
399 throw new Error
.Failure("This command doesn't work on linked devices.");
400 } catch (IOException e
) {
401 throw new Error
.Failure(e
.getMessage());
406 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
408 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
409 } catch (NotMasterDeviceException e
) {
410 throw new Error
.Failure("This command doesn't work on linked devices.");
411 } catch (GroupNotFoundException e
) {
412 throw new Error
.GroupNotFound(e
.getMessage());
413 } catch (IOException e
) {
414 throw new Error
.Failure(e
.getMessage());
419 public List
<byte[]> getGroupIds() {
420 var groups
= m
.getGroups();
421 var ids
= new ArrayList
<byte[]>(groups
.size());
422 for (var group
: groups
) {
423 ids
.add(group
.groupId().serialize());
429 public DBusPath
getGroup(final byte[] groupId
) {
431 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
432 if (groupOptional
.isEmpty()) {
433 throw new Error
.GroupNotFound("Group not found");
435 return groupOptional
.get().getObjectPath();
439 public List
<StructGroup
> listGroups() {
445 public String
getGroupName(final byte[] groupId
) {
446 var group
= m
.getGroup(getGroupId(groupId
));
447 if (group
== null || group
.title() == null) {
450 return group
.title();
455 public List
<String
> getGroupMembers(final byte[] groupId
) {
456 var group
= m
.getGroup(getGroupId(groupId
));
460 final var members
= group
.members();
461 return getRecipientStrings(members
);
466 public byte[] createGroup(
467 final String name
, final List
<String
> members
, final String avatar
468 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
469 return updateGroup(new byte[0], name
, members
, avatar
);
473 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
475 groupId
= nullIfEmpty(groupId
);
476 name
= nullIfEmpty(name
);
477 avatar
= nullIfEmpty(avatar
);
478 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
479 if (groupId
== null) {
480 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
481 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
482 return results
.first().serialize();
484 final var results
= m
.updateGroup(getGroupId(groupId
),
485 UpdateGroup
.newBuilder()
487 .withMembers(memberIdentifiers
)
488 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
490 if (results
!= null) {
491 checkSendMessageResults(results
.timestamp(), results
.results());
495 } catch (IOException e
) {
496 throw new Error
.Failure(e
.getMessage());
497 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
498 throw new Error
.GroupNotFound(e
.getMessage());
499 } catch (AttachmentInvalidException e
) {
500 throw new Error
.AttachmentInvalid(e
.getMessage());
505 public boolean isRegistered() {
510 public boolean isRegistered(String number
) {
511 var result
= isRegistered(List
.of(number
));
512 return result
.get(0);
516 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
517 var results
= new ArrayList
<Boolean
>();
518 if (numbers
.isEmpty()) {
522 Map
<String
, Pair
<String
, UUID
>> registered
;
524 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
525 } catch (IOException e
) {
526 throw new Error
.Failure(e
.getMessage());
529 return numbers
.stream().map(number
-> {
530 var uuid
= registered
.get(number
).second();
532 }).collect(Collectors
.toList());
536 public void updateProfile(
542 final boolean removeAvatar
545 givenName
= nullIfEmpty(givenName
);
546 familyName
= nullIfEmpty(familyName
);
547 about
= nullIfEmpty(about
);
548 aboutEmoji
= nullIfEmpty(aboutEmoji
);
549 avatarPath
= nullIfEmpty(avatarPath
);
550 Optional
<File
> avatarFile
= removeAvatar
552 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
553 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
554 } catch (IOException e
) {
555 throw new Error
.Failure(e
.getMessage());
560 public void updateProfile(
563 final String aboutEmoji
,
565 final boolean removeAvatar
567 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
571 public void removePin() {
573 m
.setRegistrationLockPin(Optional
.absent());
574 } catch (UnauthenticatedResponseException e
) {
575 throw new Error
.Failure("Remove pin failed with unauthenticated response: " + e
.getMessage());
576 } catch (IOException e
) {
577 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
582 public void setPin(String registrationLockPin
) {
584 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
585 } catch (UnauthenticatedResponseException e
) {
586 throw new Error
.Failure("Set pin error failed with unauthenticated response: " + e
.getMessage());
587 } catch (IOException e
) {
588 throw new Error
.Failure("Set pin error: " + e
.getMessage());
592 // Provide option to query a version string in order to react on potential
593 // future interface changes
595 public String
version() {
596 return BaseConfig
.PROJECT_VERSION
;
599 // Create a unique list of Numbers from Identities and Contacts to really get
600 // all numbers the system knows
602 public List
<String
> listNumbers() {
603 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
604 m
.getContacts().stream().map(Pair
::first
))
605 .map(a
-> a
.getNumber().orElse(null))
606 .filter(Objects
::nonNull
)
608 .collect(Collectors
.toList());
612 public List
<String
> getContactNumber(final String name
) {
613 // Contact names have precedence.
614 var numbers
= new ArrayList
<String
>();
615 var contacts
= m
.getContacts();
616 for (var c
: contacts
) {
617 if (name
.equals(c
.second().getName())) {
618 numbers
.add(c
.first().getLegacyIdentifier());
621 // Try profiles if no contact name was found
622 for (var identity
: m
.getIdentities()) {
623 final var address
= identity
.recipient();
624 var number
= address
.getNumber().orElse(null);
625 if (number
!= null) {
626 Profile profile
= null;
628 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
629 } catch (UnregisteredUserException ignored
) {
631 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
640 public void quitGroup(final byte[] groupId
) {
641 var group
= getGroupId(groupId
);
643 m
.quitGroup(group
, Set
.of());
644 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
645 throw new Error
.GroupNotFound(e
.getMessage());
646 } catch (IOException
| LastGroupAdminException e
) {
647 throw new Error
.Failure(e
.getMessage());
652 public byte[] joinGroup(final String groupLink
) {
654 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
655 if (linkUrl
== null) {
656 throw new Error
.Failure("Group link is invalid:");
658 final var result
= m
.joinGroup(linkUrl
);
659 return result
.first().serialize();
660 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| GroupLinkNotActiveException e
) {
661 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
662 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
663 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
664 } catch (IOException e
) {
665 throw new Error
.Failure(e
.getMessage());
670 public boolean isContactBlocked(final String number
) {
671 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
675 public boolean isGroupBlocked(final byte[] groupId
) {
676 var group
= m
.getGroup(getGroupId(groupId
));
680 return group
.isBlocked();
685 public boolean isMember(final byte[] groupId
) {
686 var group
= m
.getGroup(getGroupId(groupId
));
690 return group
.isMember();
695 public String
uploadStickerPack(String stickerPackPath
) {
696 File path
= new File(stickerPackPath
);
698 return m
.uploadStickerPack(path
).toString();
699 } catch (IOException e
) {
700 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
701 } catch (StickerPackInvalidException e
) {
702 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
706 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
707 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
713 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
715 if (result
.getIdentityFailure() != null) {
716 throw new Error
.UntrustedIdentity(message
);
718 throw new Error
.Failure(message
);
722 private static void checkSendMessageResults(
723 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
724 ) throws DBusExecutionException
{
725 final var sendMessageResults
= results
.values().stream().findFirst();
726 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
727 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
731 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
732 if (errors
.size() == 0) {
736 var message
= new StringBuilder();
737 message
.append(timestamp
).append('\n');
738 message
.append("Failed to send (some) messages:\n");
739 for (var error
: errors
) {
740 message
.append(error
).append('\n');
743 throw new Error
.Failure(message
.toString());
746 private static void checkSendMessageResults(
747 long timestamp
, Collection
<SendMessageResult
> results
748 ) throws DBusExecutionException
{
749 if (results
.size() == 1) {
750 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
754 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
755 if (errors
.size() == 0) {
759 var message
= new StringBuilder();
760 message
.append(timestamp
).append('\n');
761 message
.append("Failed to send (some) messages:\n");
762 for (var error
: errors
) {
763 message
.append(error
).append('\n');
766 throw new Error
.Failure(message
.toString());
769 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
770 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).collect(Collectors
.toList());
773 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
774 final Collection
<String
> recipientStrings
, final String localNumber
775 ) throws DBusExecutionException
{
776 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
777 for (var recipientString
: recipientStrings
) {
778 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
783 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
784 final String recipientString
, final String localNumber
785 ) throws DBusExecutionException
{
787 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
788 } catch (InvalidNumberException e
) {
789 throw new Error
.InvalidNumber(e
.getMessage());
793 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
795 return GroupId
.unknownVersion(groupId
);
796 } catch (Throwable e
) {
797 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
801 private byte[] nullIfEmpty(final byte[] array
) {
802 return array
.length
== 0 ?
null : array
;
805 private String
nullIfEmpty(final String name
) {
806 return name
.isEmpty() ?
null : name
;
809 private String
emptyIfNull(final String string
) {
810 return string
== null ?
"" : string
;
813 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
814 return basePath
+ "/Devices/" + deviceId
;
817 private void updateDevices() {
818 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
820 linkedDevices
= m
.getLinkedDevices();
821 } catch (IOException e
) {
822 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
827 linkedDevices
.forEach(d
-> {
828 final var object
= new DbusSignalDeviceImpl(d
);
829 final var deviceObjectPath
= object
.getObjectPath();
831 connection
.exportObject(object
);
832 } catch (DBusException e
) {
835 if (d
.isThisDevice()) {
836 thisDevice
= new DBusPath(deviceObjectPath
);
838 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
842 private void unExportDevices() {
843 this.devices
.stream()
844 .map(StructDevice
::getObjectPath
)
845 .map(DBusPath
::getPath
)
846 .forEach(connection
::unExportObject
);
847 this.devices
.clear();
850 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
851 return basePath
+ "/Groups/" + Base64
.getEncoder()
852 .encodeToString(groupId
)
858 private void updateGroups() {
859 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
860 groups
= m
.getGroups();
864 groups
.forEach(g
-> {
865 final var object
= new DbusSignalGroupImpl(g
.groupId());
867 connection
.exportObject(object
);
868 } catch (DBusException e
) {
871 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
872 g
.groupId().serialize(),
873 emptyIfNull(g
.title())));
877 private void unExportGroups() {
878 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
882 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
884 private final org
.asamk
.signal
.manager
.api
.Device device
;
886 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
887 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
888 List
.of(new DbusProperty
<>("Id", device
::id
),
889 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
890 new DbusProperty
<>("Created", device
::created
),
891 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
892 this.device
= device
;
896 public String
getObjectPath() {
897 return getDeviceObjectPath(objectPath
, device
.id());
901 public void removeDevice() throws Error
.Failure
{
903 m
.removeLinkedDevices(device
.id());
905 } catch (IOException e
) {
906 throw new Error
.Failure(e
.getMessage());
910 private void setDeviceName(String name
) {
911 if (!device
.isThisDevice()) {
912 throw new Error
.Failure("Only the name of this device can be changed");
915 m
.updateAccountAttributes(name
);
916 // update device list
918 } catch (IOException e
) {
919 throw new Error
.Failure(e
.getMessage());
924 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
926 private final GroupId groupId
;
928 public DbusSignalGroupImpl(final GroupId groupId
) {
929 this.groupId
= groupId
;
930 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
931 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
932 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
933 new DbusProperty
<>("Description",
934 () -> emptyIfNull(getGroup().description()),
935 this::setGroupDescription
),
936 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
937 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
938 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
939 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
940 new DbusProperty
<>("MessageExpirationTimer",
941 () -> getGroup().messageExpirationTimer(),
942 this::setMessageExpirationTime
),
943 new DbusProperty
<>("Members",
944 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
945 new DbusProperty
<>("PendingMembers",
946 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
947 new DbusProperty
<>("RequestingMembers",
948 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
949 new DbusProperty
<>("Admins",
950 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
951 new DbusProperty
<>("PermissionAddMember",
952 () -> getGroup().permissionAddMember().name(),
953 this::setGroupPermissionAddMember
),
954 new DbusProperty
<>("PermissionEditDetails",
955 () -> getGroup().permissionEditDetails().name(),
956 this::setGroupPermissionEditDetails
),
957 new DbusProperty
<>("PermissionSendMessage",
958 () -> getGroup().permissionSendMessage().name(),
959 this::setGroupPermissionSendMessage
),
960 new DbusProperty
<>("GroupInviteLink", () -> {
961 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
962 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
967 public String
getObjectPath() {
968 return getGroupObjectPath(objectPath
, groupId
.serialize());
972 public void quitGroup() throws Error
.Failure
{
974 m
.quitGroup(groupId
, Set
.of());
975 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
976 throw new Error
.GroupNotFound(e
.getMessage());
977 } catch (IOException e
) {
978 throw new Error
.Failure(e
.getMessage());
979 } catch (LastGroupAdminException e
) {
980 throw new Error
.LastGroupAdmin(e
.getMessage());
985 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
986 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
987 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
991 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
992 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
993 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
997 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
998 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
999 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1003 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1004 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1005 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1009 public void resetLink() throws Error
.Failure
{
1010 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1014 public void disableLink() throws Error
.Failure
{
1015 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1019 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1020 updateGroup(UpdateGroup
.newBuilder()
1021 .withGroupLinkState(requiresApproval
1022 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1023 : GroupLinkState
.ENABLED
)
1027 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1028 return m
.getGroup(groupId
);
1031 private void setGroupName(final String name
) {
1032 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1035 private void setGroupDescription(final String description
) {
1036 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1039 private void setGroupAvatar(final String avatar
) {
1040 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1043 private void setMessageExpirationTime(final int expirationTime
) {
1044 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1047 private void setGroupPermissionAddMember(final String permission
) {
1048 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1051 private void setGroupPermissionEditDetails(final String permission
) {
1052 updateGroup(UpdateGroup
.newBuilder()
1053 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1057 private void setGroupPermissionSendMessage(final String permission
) {
1058 updateGroup(UpdateGroup
.newBuilder()
1059 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1063 private void setIsBlocked(final boolean isBlocked
) {
1065 m
.setGroupBlocked(groupId
, isBlocked
);
1066 } catch (NotMasterDeviceException e
) {
1067 throw new Error
.Failure("This command doesn't work on linked devices.");
1068 } catch (GroupNotFoundException e
) {
1069 throw new Error
.GroupNotFound(e
.getMessage());
1070 } catch (IOException e
) {
1071 throw new Error
.Failure(e
.getMessage());
1075 private void updateGroup(final UpdateGroup updateGroup
) {
1077 m
.updateGroup(groupId
, updateGroup
);
1078 } catch (IOException e
) {
1079 throw new Error
.Failure(e
.getMessage());
1080 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1081 throw new Error
.GroupNotFound(e
.getMessage());
1082 } catch (AttachmentInvalidException e
) {
1083 throw new Error
.AttachmentInvalid(e
.getMessage());