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
.InactiveGroupLinkException
;
13 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
14 import org
.asamk
.signal
.manager
.api
.Message
;
15 import org
.asamk
.signal
.manager
.api
.Pair
;
16 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
17 import org
.asamk
.signal
.manager
.api
.TypingAction
;
18 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
19 import org
.asamk
.signal
.manager
.groups
.GroupId
;
20 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
21 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
22 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
23 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
24 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
25 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
26 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
27 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
29 import org
.asamk
.signal
.util
.ErrorUtils
;
30 import org
.freedesktop
.dbus
.DBusPath
;
31 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
32 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
33 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
34 import org
.freedesktop
.dbus
.types
.Variant
;
35 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
36 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
39 import java
.io
.IOException
;
41 import java
.net
.URISyntaxException
;
42 import java
.util
.ArrayList
;
43 import java
.util
.Arrays
;
44 import java
.util
.Base64
;
45 import java
.util
.Collection
;
46 import java
.util
.HashSet
;
47 import java
.util
.List
;
49 import java
.util
.Objects
;
50 import java
.util
.Optional
;
52 import java
.util
.UUID
;
53 import java
.util
.stream
.Collectors
;
54 import java
.util
.stream
.Stream
;
56 public class DbusSignalImpl
implements Signal
{
58 private final Manager m
;
59 private final DBusConnection connection
;
60 private final String objectPath
;
62 private DBusPath thisDevice
;
63 private final List
<StructDevice
> devices
= new ArrayList
<>();
64 private final List
<StructGroup
> groups
= new ArrayList
<>();
66 public DbusSignalImpl(final Manager m
, DBusConnection connection
, final String objectPath
) {
68 this.connection
= connection
;
69 this.objectPath
= objectPath
;
72 public void initObjects() {
83 public String
getObjectPath() {
88 public String
getSelfNumber() {
89 return m
.getSelfNumber();
93 public void submitRateLimitChallenge(String challenge
, String captchaString
) throws IOErrorException
{
94 final var captcha
= captchaString
== null ?
null : captchaString
.replace("signalcaptcha://", "");
97 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
98 } catch (IOException e
) {
99 throw new IOErrorException("Submit challenge error: " + e
.getMessage(), e
);
105 public void addDevice(String uri
) {
107 m
.addDeviceLink(new URI(uri
));
108 } catch (IOException
| InvalidDeviceLinkException e
) {
109 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
110 } catch (URISyntaxException e
) {
111 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
112 + " Device link uri has invalid format: "
118 public DBusPath
getDevice(long deviceId
) {
120 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
121 if (deviceOptional
.isEmpty()) {
122 throw new Error
.DeviceNotFound("Device not found");
124 return deviceOptional
.get().getObjectPath();
128 public List
<StructDevice
> listDevices() {
134 public DBusPath
getThisDevice() {
140 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
141 var recipients
= new ArrayList
<String
>(1);
142 recipients
.add(recipient
);
143 return sendMessage(message
, attachments
, recipients
);
147 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
149 final var results
= m
.sendMessage(new Message(message
, attachments
),
150 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
151 .map(RecipientIdentifier
.class::cast
)
152 .collect(Collectors
.toSet()));
154 checkSendMessageResults(results
.timestamp(), results
.results());
155 return results
.timestamp();
156 } catch (AttachmentInvalidException e
) {
157 throw new Error
.AttachmentInvalid(e
.getMessage());
158 } catch (IOException e
) {
159 throw new Error
.Failure(e
);
160 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
161 throw new Error
.GroupNotFound(e
.getMessage());
166 public long sendRemoteDeleteMessage(
167 final long targetSentTimestamp
, final String recipient
169 var recipients
= new ArrayList
<String
>(1);
170 recipients
.add(recipient
);
171 return sendRemoteDeleteMessage(targetSentTimestamp
, recipients
);
175 public long sendRemoteDeleteMessage(
176 final long targetSentTimestamp
, final List
<String
> recipients
179 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
180 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
181 .map(RecipientIdentifier
.class::cast
)
182 .collect(Collectors
.toSet()));
183 checkSendMessageResults(results
.timestamp(), results
.results());
184 return results
.timestamp();
185 } catch (IOException e
) {
186 throw new Error
.Failure(e
.getMessage());
187 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
188 throw new Error
.GroupNotFound(e
.getMessage());
193 public long sendGroupRemoteDeleteMessage(
194 final long targetSentTimestamp
, final byte[] groupId
197 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
198 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
199 checkSendMessageResults(results
.timestamp(), results
.results());
200 return results
.timestamp();
201 } catch (IOException e
) {
202 throw new Error
.Failure(e
.getMessage());
203 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
204 throw new Error
.GroupNotFound(e
.getMessage());
209 public long sendMessageReaction(
211 final boolean remove
,
212 final String targetAuthor
,
213 final long targetSentTimestamp
,
214 final String recipient
216 var recipients
= new ArrayList
<String
>(1);
217 recipients
.add(recipient
);
218 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, recipients
);
222 public long sendMessageReaction(
224 final boolean remove
,
225 final String targetAuthor
,
226 final long targetSentTimestamp
,
227 final List
<String
> recipients
230 final var results
= m
.sendMessageReaction(emoji
,
232 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
234 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
235 .map(RecipientIdentifier
.class::cast
)
236 .collect(Collectors
.toSet()));
237 checkSendMessageResults(results
.timestamp(), results
.results());
238 return results
.timestamp();
239 } catch (IOException e
) {
240 throw new Error
.Failure(e
.getMessage());
241 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
242 throw new Error
.GroupNotFound(e
.getMessage());
247 public void sendTyping(
248 final String recipient
, final boolean stop
249 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
251 var recipients
= new ArrayList
<String
>(1);
252 recipients
.add(recipient
);
253 m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
254 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
255 .map(RecipientIdentifier
.class::cast
)
256 .collect(Collectors
.toSet()));
257 } catch (IOException e
) {
258 throw new Error
.Failure(e
.getMessage());
259 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
260 throw new Error
.GroupNotFound(e
.getMessage());
261 } catch (UntrustedIdentityException e
) {
262 throw new Error
.UntrustedIdentity(e
.getMessage());
267 public void sendReadReceipt(
268 final String recipient
, final List
<Long
> messageIds
269 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
271 m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
272 } catch (IOException e
) {
273 throw new Error
.Failure(e
.getMessage());
274 } catch (UntrustedIdentityException e
) {
275 throw new Error
.UntrustedIdentity(e
.getMessage());
280 public void sendViewedReceipt(
281 final String recipient
, final List
<Long
> messageIds
282 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
284 m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
285 } catch (IOException e
) {
286 throw new Error
.Failure(e
.getMessage());
287 } catch (UntrustedIdentityException e
) {
288 throw new Error
.UntrustedIdentity(e
.getMessage());
293 public void sendContacts() {
296 } catch (IOException e
) {
297 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
302 public void sendSyncRequest() {
304 m
.requestAllSyncData();
305 } catch (IOException e
) {
306 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
311 public long sendNoteToSelfMessage(
312 final String message
, final List
<String
> attachments
313 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
315 final var results
= m
.sendMessage(new Message(message
, attachments
),
316 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
317 checkSendMessageResults(results
.timestamp(), results
.results());
318 return results
.timestamp();
319 } catch (AttachmentInvalidException e
) {
320 throw new Error
.AttachmentInvalid(e
.getMessage());
321 } catch (IOException e
) {
322 throw new Error
.Failure(e
.getMessage());
323 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
324 throw new Error
.GroupNotFound(e
.getMessage());
329 public void sendEndSessionMessage(final List
<String
> recipients
) {
331 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
332 checkSendMessageResults(results
.timestamp(), results
.results());
333 } catch (IOException e
) {
334 throw new Error
.Failure(e
.getMessage());
339 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
341 var results
= m
.sendMessage(new Message(message
, attachments
),
342 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
343 checkSendMessageResults(results
.timestamp(), results
.results());
344 return results
.timestamp();
345 } catch (IOException e
) {
346 throw new Error
.Failure(e
.getMessage());
347 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
348 throw new Error
.GroupNotFound(e
.getMessage());
349 } catch (AttachmentInvalidException e
) {
350 throw new Error
.AttachmentInvalid(e
.getMessage());
355 public long sendGroupMessageReaction(
357 final boolean remove
,
358 final String targetAuthor
,
359 final long targetSentTimestamp
,
363 final var results
= m
.sendMessageReaction(emoji
,
365 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
367 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
368 checkSendMessageResults(results
.timestamp(), results
.results());
369 return results
.timestamp();
370 } catch (IOException e
) {
371 throw new Error
.Failure(e
.getMessage());
372 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
373 throw new Error
.GroupNotFound(e
.getMessage());
377 // Since contact names might be empty if not defined, also potentially return
380 public String
getContactName(final String number
) {
381 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
382 return name
== null ?
"" : name
;
386 public void setContactName(final String number
, final String name
) {
388 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
389 } catch (NotMasterDeviceException e
) {
390 throw new Error
.Failure("This command doesn't work on linked devices.");
391 } catch (IOException e
) {
392 throw new Error
.Failure("Contact is not registered.");
397 public void setExpirationTimer(final String number
, final int expiration
) {
399 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
400 } catch (IOException e
) {
401 throw new Error
.Failure(e
.getMessage());
406 public void setContactBlocked(final String number
, final boolean blocked
) {
408 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
409 } catch (NotMasterDeviceException e
) {
410 throw new Error
.Failure("This command doesn't work on linked devices.");
411 } catch (IOException e
) {
412 throw new Error
.Failure(e
.getMessage());
417 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
419 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
420 } catch (NotMasterDeviceException e
) {
421 throw new Error
.Failure("This command doesn't work on linked devices.");
422 } catch (GroupNotFoundException e
) {
423 throw new Error
.GroupNotFound(e
.getMessage());
424 } catch (IOException e
) {
425 throw new Error
.Failure(e
.getMessage());
430 public List
<byte[]> getGroupIds() {
431 var groups
= m
.getGroups();
432 var ids
= new ArrayList
<byte[]>(groups
.size());
433 for (var group
: groups
) {
434 ids
.add(group
.groupId().serialize());
440 public DBusPath
getGroup(final byte[] groupId
) {
442 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
443 if (groupOptional
.isEmpty()) {
444 throw new Error
.GroupNotFound("Group not found");
446 return groupOptional
.get().getObjectPath();
450 public List
<StructGroup
> listGroups() {
456 public String
getGroupName(final byte[] groupId
) {
457 var group
= m
.getGroup(getGroupId(groupId
));
458 if (group
== null || group
.title() == null) {
461 return group
.title();
466 public List
<String
> getGroupMembers(final byte[] groupId
) {
467 var group
= m
.getGroup(getGroupId(groupId
));
471 final var members
= group
.members();
472 return getRecipientStrings(members
);
477 public byte[] createGroup(
478 final String name
, final List
<String
> members
, final String avatar
479 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
480 return updateGroup(new byte[0], name
, members
, avatar
);
484 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
486 groupId
= nullIfEmpty(groupId
);
487 name
= nullIfEmpty(name
);
488 avatar
= nullIfEmpty(avatar
);
489 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
490 if (groupId
== null) {
491 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
492 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
493 return results
.first().serialize();
495 final var results
= m
.updateGroup(getGroupId(groupId
),
496 UpdateGroup
.newBuilder()
498 .withMembers(memberIdentifiers
)
499 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
501 if (results
!= null) {
502 checkSendMessageResults(results
.timestamp(), results
.results());
506 } catch (IOException e
) {
507 throw new Error
.Failure(e
.getMessage());
508 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
509 throw new Error
.GroupNotFound(e
.getMessage());
510 } catch (AttachmentInvalidException e
) {
511 throw new Error
.AttachmentInvalid(e
.getMessage());
516 public boolean isRegistered() {
521 public boolean isRegistered(String number
) {
522 var result
= isRegistered(List
.of(number
));
523 return result
.get(0);
527 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
528 var results
= new ArrayList
<Boolean
>();
529 if (numbers
.isEmpty()) {
533 Map
<String
, Pair
<String
, UUID
>> registered
;
535 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
536 } catch (IOException e
) {
537 throw new Error
.Failure(e
.getMessage());
540 return numbers
.stream().map(number
-> {
541 var uuid
= registered
.get(number
).second();
543 }).collect(Collectors
.toList());
547 public void updateProfile(
553 final boolean removeAvatar
556 givenName
= nullIfEmpty(givenName
);
557 familyName
= nullIfEmpty(familyName
);
558 about
= nullIfEmpty(about
);
559 aboutEmoji
= nullIfEmpty(aboutEmoji
);
560 avatarPath
= nullIfEmpty(avatarPath
);
561 Optional
<File
> avatarFile
= removeAvatar
563 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
564 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
565 } catch (IOException e
) {
566 throw new Error
.Failure(e
.getMessage());
571 public void updateProfile(
574 final String aboutEmoji
,
576 final boolean removeAvatar
578 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
582 public void removePin() {
584 m
.setRegistrationLockPin(Optional
.empty());
585 } catch (IOException e
) {
586 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
591 public void setPin(String registrationLockPin
) {
593 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
594 } catch (IOException e
) {
595 throw new Error
.Failure("Set pin error: " + e
.getMessage());
599 // Provide option to query a version string in order to react on potential
600 // future interface changes
602 public String
version() {
603 return BaseConfig
.PROJECT_VERSION
;
606 // Create a unique list of Numbers from Identities and Contacts to really get
607 // all numbers the system knows
609 public List
<String
> listNumbers() {
610 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
611 m
.getContacts().stream().map(Pair
::first
))
612 .map(a
-> a
.getNumber().orElse(null))
613 .filter(Objects
::nonNull
)
615 .collect(Collectors
.toList());
619 public List
<String
> getContactNumber(final String name
) {
620 // Contact names have precedence.
621 var numbers
= new ArrayList
<String
>();
622 var contacts
= m
.getContacts();
623 for (var c
: contacts
) {
624 if (name
.equals(c
.second().getName())) {
625 numbers
.add(c
.first().getLegacyIdentifier());
628 // Try profiles if no contact name was found
629 for (var identity
: m
.getIdentities()) {
630 final var address
= identity
.recipient();
631 var number
= address
.getNumber().orElse(null);
632 if (number
!= null) {
633 Profile profile
= null;
635 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
636 } catch (IOException ignored
) {
638 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
647 public void quitGroup(final byte[] groupId
) {
648 var group
= getGroupId(groupId
);
650 m
.quitGroup(group
, Set
.of());
651 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
652 throw new Error
.GroupNotFound(e
.getMessage());
653 } catch (IOException
| LastGroupAdminException e
) {
654 throw new Error
.Failure(e
.getMessage());
659 public byte[] joinGroup(final String groupLink
) {
661 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
662 if (linkUrl
== null) {
663 throw new Error
.Failure("Group link is invalid:");
665 final var result
= m
.joinGroup(linkUrl
);
666 return result
.first().serialize();
667 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
668 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
669 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
670 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
671 } catch (IOException e
) {
672 throw new Error
.Failure(e
.getMessage());
677 public boolean isContactBlocked(final String number
) {
678 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
682 public boolean isGroupBlocked(final byte[] groupId
) {
683 var group
= m
.getGroup(getGroupId(groupId
));
687 return group
.isBlocked();
692 public boolean isMember(final byte[] groupId
) {
693 var group
= m
.getGroup(getGroupId(groupId
));
697 return group
.isMember();
702 public String
uploadStickerPack(String stickerPackPath
) {
703 File path
= new File(stickerPackPath
);
705 return m
.uploadStickerPack(path
).toString();
706 } catch (IOException e
) {
707 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
708 } catch (StickerPackInvalidException e
) {
709 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
713 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
714 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
720 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
722 if (result
.getIdentityFailure() != null) {
723 throw new Error
.UntrustedIdentity(message
);
725 throw new Error
.Failure(message
);
729 private static void checkSendMessageResults(
730 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
731 ) throws DBusExecutionException
{
732 final var sendMessageResults
= results
.values().stream().findFirst();
733 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
734 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
738 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
739 if (errors
.size() == 0) {
743 var message
= new StringBuilder();
744 message
.append(timestamp
).append('\n');
745 message
.append("Failed to send (some) messages:\n");
746 for (var error
: errors
) {
747 message
.append(error
).append('\n');
750 throw new Error
.Failure(message
.toString());
753 private static void checkSendMessageResults(
754 long timestamp
, Collection
<SendMessageResult
> results
755 ) throws DBusExecutionException
{
756 if (results
.size() == 1) {
757 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
761 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
762 if (errors
.size() == 0) {
766 var message
= new StringBuilder();
767 message
.append(timestamp
).append('\n');
768 message
.append("Failed to send (some) messages:\n");
769 for (var error
: errors
) {
770 message
.append(error
).append('\n');
773 throw new Error
.Failure(message
.toString());
776 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
777 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).collect(Collectors
.toList());
780 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
781 final Collection
<String
> recipientStrings
, final String localNumber
782 ) throws DBusExecutionException
{
783 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
784 for (var recipientString
: recipientStrings
) {
785 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
790 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
791 final String recipientString
, final String localNumber
792 ) throws DBusExecutionException
{
794 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
795 } catch (InvalidNumberException e
) {
796 throw new Error
.InvalidNumber(e
.getMessage());
800 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
802 return GroupId
.unknownVersion(groupId
);
803 } catch (Throwable e
) {
804 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
808 private byte[] nullIfEmpty(final byte[] array
) {
809 return array
.length
== 0 ?
null : array
;
812 private String
nullIfEmpty(final String name
) {
813 return name
.isEmpty() ?
null : name
;
816 private String
emptyIfNull(final String string
) {
817 return string
== null ?
"" : string
;
820 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
821 return basePath
+ "/Devices/" + deviceId
;
824 private void updateDevices() {
825 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
827 linkedDevices
= m
.getLinkedDevices();
828 } catch (IOException e
) {
829 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
834 linkedDevices
.forEach(d
-> {
835 final var object
= new DbusSignalDeviceImpl(d
);
836 final var deviceObjectPath
= object
.getObjectPath();
838 connection
.exportObject(object
);
839 } catch (DBusException e
) {
842 if (d
.isThisDevice()) {
843 thisDevice
= new DBusPath(deviceObjectPath
);
845 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
849 private void unExportDevices() {
850 this.devices
.stream()
851 .map(StructDevice
::getObjectPath
)
852 .map(DBusPath
::getPath
)
853 .forEach(connection
::unExportObject
);
854 this.devices
.clear();
857 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
858 return basePath
+ "/Groups/" + Base64
.getEncoder()
859 .encodeToString(groupId
)
865 private void updateGroups() {
866 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
867 groups
= m
.getGroups();
871 groups
.forEach(g
-> {
872 final var object
= new DbusSignalGroupImpl(g
.groupId());
874 connection
.exportObject(object
);
875 } catch (DBusException e
) {
878 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
879 g
.groupId().serialize(),
880 emptyIfNull(g
.title())));
884 private void unExportGroups() {
885 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
889 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
891 private final org
.asamk
.signal
.manager
.api
.Device device
;
893 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
894 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
895 List
.of(new DbusProperty
<>("Id", device
::id
),
896 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
897 new DbusProperty
<>("Created", device
::created
),
898 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
899 this.device
= device
;
903 public String
getObjectPath() {
904 return getDeviceObjectPath(objectPath
, device
.id());
908 public void removeDevice() throws Error
.Failure
{
910 m
.removeLinkedDevices(device
.id());
912 } catch (IOException e
) {
913 throw new Error
.Failure(e
.getMessage());
917 private void setDeviceName(String name
) {
918 if (!device
.isThisDevice()) {
919 throw new Error
.Failure("Only the name of this device can be changed");
922 m
.updateAccountAttributes(name
);
923 // update device list
925 } catch (IOException e
) {
926 throw new Error
.Failure(e
.getMessage());
931 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
933 private final GroupId groupId
;
935 public DbusSignalGroupImpl(final GroupId groupId
) {
936 this.groupId
= groupId
;
937 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
938 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
939 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
940 new DbusProperty
<>("Description",
941 () -> emptyIfNull(getGroup().description()),
942 this::setGroupDescription
),
943 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
944 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
945 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
946 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
947 new DbusProperty
<>("MessageExpirationTimer",
948 () -> getGroup().messageExpirationTimer(),
949 this::setMessageExpirationTime
),
950 new DbusProperty
<>("Members",
951 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
952 new DbusProperty
<>("PendingMembers",
953 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
954 new DbusProperty
<>("RequestingMembers",
955 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
956 new DbusProperty
<>("Admins",
957 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
958 new DbusProperty
<>("PermissionAddMember",
959 () -> getGroup().permissionAddMember().name(),
960 this::setGroupPermissionAddMember
),
961 new DbusProperty
<>("PermissionEditDetails",
962 () -> getGroup().permissionEditDetails().name(),
963 this::setGroupPermissionEditDetails
),
964 new DbusProperty
<>("PermissionSendMessage",
965 () -> getGroup().permissionSendMessage().name(),
966 this::setGroupPermissionSendMessage
),
967 new DbusProperty
<>("GroupInviteLink", () -> {
968 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
969 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
974 public String
getObjectPath() {
975 return getGroupObjectPath(objectPath
, groupId
.serialize());
979 public void quitGroup() throws Error
.Failure
{
981 m
.quitGroup(groupId
, Set
.of());
982 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
983 throw new Error
.GroupNotFound(e
.getMessage());
984 } catch (IOException e
) {
985 throw new Error
.Failure(e
.getMessage());
986 } catch (LastGroupAdminException e
) {
987 throw new Error
.LastGroupAdmin(e
.getMessage());
992 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
993 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
994 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
998 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
999 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1000 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1004 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1005 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1006 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1010 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1011 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1012 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1016 public void resetLink() throws Error
.Failure
{
1017 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1021 public void disableLink() throws Error
.Failure
{
1022 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1026 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1027 updateGroup(UpdateGroup
.newBuilder()
1028 .withGroupLinkState(requiresApproval
1029 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1030 : GroupLinkState
.ENABLED
)
1034 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1035 return m
.getGroup(groupId
);
1038 private void setGroupName(final String name
) {
1039 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1042 private void setGroupDescription(final String description
) {
1043 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1046 private void setGroupAvatar(final String avatar
) {
1047 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1050 private void setMessageExpirationTime(final int expirationTime
) {
1051 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1054 private void setGroupPermissionAddMember(final String permission
) {
1055 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1058 private void setGroupPermissionEditDetails(final String permission
) {
1059 updateGroup(UpdateGroup
.newBuilder()
1060 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1064 private void setGroupPermissionSendMessage(final String permission
) {
1065 updateGroup(UpdateGroup
.newBuilder()
1066 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1070 private void setIsBlocked(final boolean isBlocked
) {
1072 m
.setGroupBlocked(groupId
, isBlocked
);
1073 } catch (NotMasterDeviceException e
) {
1074 throw new Error
.Failure("This command doesn't work on linked devices.");
1075 } catch (GroupNotFoundException e
) {
1076 throw new Error
.GroupNotFound(e
.getMessage());
1077 } catch (IOException e
) {
1078 throw new Error
.Failure(e
.getMessage());
1082 private void updateGroup(final UpdateGroup updateGroup
) {
1084 m
.updateGroup(groupId
, updateGroup
);
1085 } catch (IOException e
) {
1086 throw new Error
.Failure(e
.getMessage());
1087 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1088 throw new Error
.GroupNotFound(e
.getMessage());
1089 } catch (AttachmentInvalidException e
) {
1090 throw new Error
.AttachmentInvalid(e
.getMessage());