1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.BaseConfig
;
5 import org
.asamk
.signal
.manager
.AttachmentInvalidException
;
6 import org
.asamk
.signal
.manager
.Manager
;
7 import org
.asamk
.signal
.manager
.NotMasterDeviceException
;
8 import org
.asamk
.signal
.manager
.StickerPackInvalidException
;
9 import org
.asamk
.signal
.manager
.UntrustedIdentityException
;
10 import org
.asamk
.signal
.manager
.api
.Identity
;
11 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
12 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
13 import org
.asamk
.signal
.manager
.api
.InvalidNumberException
;
14 import org
.asamk
.signal
.manager
.api
.Message
;
15 import org
.asamk
.signal
.manager
.api
.Pair
;
16 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
17 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
18 import org
.asamk
.signal
.manager
.api
.TypingAction
;
19 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
20 import org
.asamk
.signal
.manager
.groups
.GroupId
;
21 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
22 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
23 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
24 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
25 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
26 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
27 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
28 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
29 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
30 import org
.asamk
.signal
.util
.ErrorUtils
;
31 import org
.freedesktop
.dbus
.DBusPath
;
32 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
33 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
35 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
36 import org
.freedesktop
.dbus
.types
.Variant
;
37 import org
.slf4j
.Logger
;
38 import org
.slf4j
.LoggerFactory
;
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 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
70 public DbusSignalImpl(final Manager m
, DBusConnection connection
, final String objectPath
) {
72 this.connection
= connection
;
73 this.objectPath
= objectPath
;
76 public void initObjects() {
79 updateConfiguration();
85 unExportConfiguration();
89 public String
getObjectPath() {
94 public String
getSelfNumber() {
95 return m
.getSelfNumber();
99 public void submitRateLimitChallenge(String challenge
, String captchaString
) {
100 final var captcha
= captchaString
== null ?
null : captchaString
.replace("signalcaptcha://", "");
103 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
104 } catch (IOException e
) {
105 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
111 public void addDevice(String uri
) {
113 m
.addDeviceLink(new URI(uri
));
114 } catch (IOException
| InvalidDeviceLinkException e
) {
115 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
116 } catch (URISyntaxException e
) {
117 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
118 + " Device link uri has invalid format: "
124 public DBusPath
getDevice(long deviceId
) {
126 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
127 if (deviceOptional
.isEmpty()) {
128 throw new Error
.DeviceNotFound("Device not found");
130 return deviceOptional
.get().getObjectPath();
134 public List
<StructDevice
> listDevices() {
140 public DBusPath
getThisDevice() {
146 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
147 var recipients
= new ArrayList
<String
>(1);
148 recipients
.add(recipient
);
149 return sendMessage(message
, attachments
, recipients
);
153 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
155 final var results
= m
.sendMessage(new Message(message
, attachments
),
156 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
157 .map(RecipientIdentifier
.class::cast
)
158 .collect(Collectors
.toSet()));
160 checkSendMessageResults(results
.timestamp(), results
.results());
161 return results
.timestamp();
162 } catch (AttachmentInvalidException e
) {
163 throw new Error
.AttachmentInvalid(e
.getMessage());
164 } catch (IOException e
) {
165 throw new Error
.Failure(e
);
166 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
167 throw new Error
.GroupNotFound(e
.getMessage());
172 public long sendRemoteDeleteMessage(
173 final long targetSentTimestamp
, final String recipient
175 var recipients
= new ArrayList
<String
>(1);
176 recipients
.add(recipient
);
177 return sendRemoteDeleteMessage(targetSentTimestamp
, recipients
);
181 public long sendRemoteDeleteMessage(
182 final long targetSentTimestamp
, final List
<String
> recipients
185 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
186 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
187 .map(RecipientIdentifier
.class::cast
)
188 .collect(Collectors
.toSet()));
189 checkSendMessageResults(results
.timestamp(), results
.results());
190 return results
.timestamp();
191 } catch (IOException e
) {
192 throw new Error
.Failure(e
.getMessage());
193 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
194 throw new Error
.GroupNotFound(e
.getMessage());
199 public long sendGroupRemoteDeleteMessage(
200 final long targetSentTimestamp
, final byte[] groupId
203 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
204 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
205 checkSendMessageResults(results
.timestamp(), results
.results());
206 return results
.timestamp();
207 } catch (IOException e
) {
208 throw new Error
.Failure(e
.getMessage());
209 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
210 throw new Error
.GroupNotFound(e
.getMessage());
215 public long sendMessageReaction(
217 final boolean remove
,
218 final String targetAuthor
,
219 final long targetSentTimestamp
,
220 final String recipient
222 var recipients
= new ArrayList
<String
>(1);
223 recipients
.add(recipient
);
224 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, recipients
);
228 public long sendMessageReaction(
230 final boolean remove
,
231 final String targetAuthor
,
232 final long targetSentTimestamp
,
233 final List
<String
> recipients
236 final var results
= m
.sendMessageReaction(emoji
,
238 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
240 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
241 .map(RecipientIdentifier
.class::cast
)
242 .collect(Collectors
.toSet()));
243 checkSendMessageResults(results
.timestamp(), results
.results());
244 return results
.timestamp();
245 } catch (IOException e
) {
246 throw new Error
.Failure(e
.getMessage());
247 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
248 throw new Error
.GroupNotFound(e
.getMessage());
253 public void sendTyping(
254 final String recipient
, final boolean stop
255 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
257 var recipients
= new ArrayList
<String
>(1);
258 recipients
.add(recipient
);
259 m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
260 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
261 .map(RecipientIdentifier
.class::cast
)
262 .collect(Collectors
.toSet()));
263 } catch (IOException e
) {
264 throw new Error
.Failure(e
.getMessage());
265 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
266 throw new Error
.GroupNotFound(e
.getMessage());
267 } catch (UntrustedIdentityException e
) {
268 throw new Error
.UntrustedIdentity(e
.getMessage());
273 public void sendReadReceipt(
274 final String recipient
, final List
<Long
> messageIds
275 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
277 m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
278 } catch (IOException e
) {
279 throw new Error
.Failure(e
.getMessage());
280 } catch (UntrustedIdentityException e
) {
281 throw new Error
.UntrustedIdentity(e
.getMessage());
286 public void sendViewedReceipt(
287 final String recipient
, final List
<Long
> messageIds
288 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
290 m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
291 } catch (IOException e
) {
292 throw new Error
.Failure(e
.getMessage());
293 } catch (UntrustedIdentityException e
) {
294 throw new Error
.UntrustedIdentity(e
.getMessage());
299 public void sendContacts() {
302 } catch (IOException e
) {
303 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
308 public void sendSyncRequest() {
310 m
.requestAllSyncData();
311 } catch (IOException e
) {
312 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
317 public long sendNoteToSelfMessage(
318 final String message
, final List
<String
> attachments
319 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
321 final var results
= m
.sendMessage(new Message(message
, attachments
),
322 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
323 checkSendMessageResults(results
.timestamp(), results
.results());
324 return results
.timestamp();
325 } catch (AttachmentInvalidException e
) {
326 throw new Error
.AttachmentInvalid(e
.getMessage());
327 } catch (IOException e
) {
328 throw new Error
.Failure(e
.getMessage());
329 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
330 throw new Error
.GroupNotFound(e
.getMessage());
335 public void sendEndSessionMessage(final List
<String
> recipients
) {
337 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
338 checkSendMessageResults(results
.timestamp(), results
.results());
339 } catch (IOException e
) {
340 throw new Error
.Failure(e
.getMessage());
345 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
347 var results
= m
.sendMessage(new Message(message
, attachments
),
348 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
349 checkSendMessageResults(results
.timestamp(), results
.results());
350 return results
.timestamp();
351 } catch (IOException e
) {
352 throw new Error
.Failure(e
.getMessage());
353 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
354 throw new Error
.GroupNotFound(e
.getMessage());
355 } catch (AttachmentInvalidException e
) {
356 throw new Error
.AttachmentInvalid(e
.getMessage());
361 public long sendGroupMessageReaction(
363 final boolean remove
,
364 final String targetAuthor
,
365 final long targetSentTimestamp
,
369 final var results
= m
.sendMessageReaction(emoji
,
371 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
373 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
374 checkSendMessageResults(results
.timestamp(), results
.results());
375 return results
.timestamp();
376 } catch (IOException e
) {
377 throw new Error
.Failure(e
.getMessage());
378 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
379 throw new Error
.GroupNotFound(e
.getMessage());
383 // Since contact names might be empty if not defined, also potentially return
386 public String
getContactName(final String number
) {
387 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
388 return name
== null ?
"" : name
;
392 public void setContactName(final String number
, final String name
) {
394 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
395 } catch (NotMasterDeviceException e
) {
396 throw new Error
.Failure("This command doesn't work on linked devices.");
397 } catch (IOException e
) {
398 throw new Error
.Failure("Contact is not registered.");
403 public void setExpirationTimer(final String number
, final int expiration
) {
405 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
406 } catch (IOException e
) {
407 throw new Error
.Failure(e
.getMessage());
412 public void setContactBlocked(final String number
, final boolean blocked
) {
414 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
415 } catch (NotMasterDeviceException e
) {
416 throw new Error
.Failure("This command doesn't work on linked devices.");
417 } catch (IOException e
) {
418 throw new Error
.Failure(e
.getMessage());
423 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
425 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
426 } catch (NotMasterDeviceException e
) {
427 throw new Error
.Failure("This command doesn't work on linked devices.");
428 } catch (GroupNotFoundException e
) {
429 throw new Error
.GroupNotFound(e
.getMessage());
430 } catch (IOException e
) {
431 throw new Error
.Failure(e
.getMessage());
436 public List
<byte[]> getGroupIds() {
437 var groups
= m
.getGroups();
438 var ids
= new ArrayList
<byte[]>(groups
.size());
439 for (var group
: groups
) {
440 ids
.add(group
.groupId().serialize());
446 public DBusPath
getGroup(final byte[] groupId
) {
448 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
449 if (groupOptional
.isEmpty()) {
450 throw new Error
.GroupNotFound("Group not found");
452 return groupOptional
.get().getObjectPath();
456 public List
<StructGroup
> listGroups() {
462 public String
getGroupName(final byte[] groupId
) {
463 var group
= m
.getGroup(getGroupId(groupId
));
464 if (group
== null || group
.title() == null) {
467 return group
.title();
472 public List
<String
> getGroupMembers(final byte[] groupId
) {
473 var group
= m
.getGroup(getGroupId(groupId
));
477 final var members
= group
.members();
478 return getRecipientStrings(members
);
483 public byte[] createGroup(
484 final String name
, final List
<String
> members
, final String avatar
485 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
486 return updateGroup(new byte[0], name
, members
, avatar
);
490 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
492 groupId
= nullIfEmpty(groupId
);
493 name
= nullIfEmpty(name
);
494 avatar
= nullIfEmpty(avatar
);
495 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
496 if (groupId
== null) {
497 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
498 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
499 return results
.first().serialize();
501 final var results
= m
.updateGroup(getGroupId(groupId
),
502 UpdateGroup
.newBuilder()
504 .withMembers(memberIdentifiers
)
505 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
507 if (results
!= null) {
508 checkSendMessageResults(results
.timestamp(), results
.results());
512 } catch (IOException e
) {
513 throw new Error
.Failure(e
.getMessage());
514 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
515 throw new Error
.GroupNotFound(e
.getMessage());
516 } catch (AttachmentInvalidException e
) {
517 throw new Error
.AttachmentInvalid(e
.getMessage());
522 public boolean isRegistered() {
527 public boolean isRegistered(String number
) {
528 var result
= isRegistered(List
.of(number
));
529 return result
.get(0);
533 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
534 var results
= new ArrayList
<Boolean
>();
535 if (numbers
.isEmpty()) {
539 Map
<String
, Pair
<String
, UUID
>> registered
;
541 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
542 } catch (IOException e
) {
543 throw new Error
.Failure(e
.getMessage());
546 return numbers
.stream().map(number
-> {
547 var uuid
= registered
.get(number
).second();
549 }).collect(Collectors
.toList());
553 public void updateProfile(
559 final boolean removeAvatar
562 givenName
= nullIfEmpty(givenName
);
563 familyName
= nullIfEmpty(familyName
);
564 about
= nullIfEmpty(about
);
565 aboutEmoji
= nullIfEmpty(aboutEmoji
);
566 avatarPath
= nullIfEmpty(avatarPath
);
567 Optional
<File
> avatarFile
= removeAvatar
569 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
570 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
571 } catch (IOException e
) {
572 throw new Error
.Failure(e
.getMessage());
577 public void updateProfile(
580 final String aboutEmoji
,
582 final boolean removeAvatar
584 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
588 public void removePin() {
590 m
.setRegistrationLockPin(Optional
.empty());
591 } catch (IOException e
) {
592 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
597 public void setPin(String registrationLockPin
) {
599 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
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 (IOException 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
| InactiveGroupLinkException 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
.isIdentityFailure()) {
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();
843 exportObject(object
);
844 if (d
.isThisDevice()) {
845 thisDevice
= new DBusPath(deviceObjectPath
);
847 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
851 private void unExportDevices() {
852 this.devices
.stream()
853 .map(StructDevice
::getObjectPath
)
854 .map(DBusPath
::getPath
)
855 .forEach(connection
::unExportObject
);
856 this.devices
.clear();
859 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
860 return basePath
+ "/Groups/" + Base64
.getEncoder()
861 .encodeToString(groupId
)
867 private void updateGroups() {
868 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
869 groups
= m
.getGroups();
873 groups
.forEach(g
-> {
874 final var object
= new DbusSignalGroupImpl(g
.groupId());
875 exportObject(object
);
876 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
877 g
.groupId().serialize(),
878 emptyIfNull(g
.title())));
882 private void unExportGroups() {
883 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
887 private static String
getConfigurationObjectPath(String basePath
) {
888 return basePath
+ "/Configuration";
891 private void updateConfiguration() {
892 unExportConfiguration();
893 final var object
= new DbusSignalConfigurationImpl();
894 exportObject(object
);
897 private void unExportConfiguration() {
898 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
899 connection
.unExportObject(objectPath
);
902 private void exportObject(final DBusInterface object
) {
904 connection
.exportObject(object
);
905 logger
.debug("Exported dbus object: " + object
.getObjectPath());
906 } catch (DBusException e
) {
911 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
913 private final org
.asamk
.signal
.manager
.api
.Device device
;
915 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
916 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
917 List
.of(new DbusProperty
<>("Id", device
::id
),
918 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
919 new DbusProperty
<>("Created", device
::created
),
920 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
921 this.device
= device
;
925 public String
getObjectPath() {
926 return getDeviceObjectPath(objectPath
, device
.id());
930 public void removeDevice() throws Error
.Failure
{
932 m
.removeLinkedDevices(device
.id());
934 } catch (IOException e
) {
935 throw new Error
.Failure(e
.getMessage());
939 private void setDeviceName(String name
) {
940 if (!device
.isThisDevice()) {
941 throw new Error
.Failure("Only the name of this device can be changed");
944 m
.updateAccountAttributes(name
);
945 // update device list
947 } catch (IOException e
) {
948 throw new Error
.Failure(e
.getMessage());
953 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
955 public DbusSignalConfigurationImpl(
957 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
958 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
959 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
960 this::getUnidentifiedDeliveryIndicators
,
961 this::setUnidentifiedDeliveryIndicators
),
962 new DbusProperty
<>("TypingIndicators",
963 this::getTypingIndicators
,
964 this::setTypingIndicators
),
965 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
970 public String
getObjectPath() {
971 return getConfigurationObjectPath(objectPath
);
974 public void setReadReceipts(Boolean readReceipts
) {
975 setConfiguration(readReceipts
, null, null, null);
978 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
979 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
982 public void setTypingIndicators(Boolean typingIndicators
) {
983 setConfiguration(null, null, typingIndicators
, null);
986 public void setLinkPreviews(Boolean linkPreviews
) {
987 setConfiguration(null, null, null, linkPreviews
);
990 private void setConfiguration(
991 Boolean readReceipts
,
992 Boolean unidentifiedDeliveryIndicators
,
993 Boolean typingIndicators
,
997 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
998 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
999 Optional
.ofNullable(typingIndicators
),
1000 Optional
.ofNullable(linkPreviews
)));
1001 } catch (IOException e
) {
1002 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1003 } catch (NotMasterDeviceException e
) {
1004 throw new Error
.Failure("This command doesn't work on linked devices.");
1008 private boolean getReadReceipts() {
1009 return m
.getConfiguration().readReceipts().orElse(false);
1012 private boolean getUnidentifiedDeliveryIndicators() {
1013 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1016 private boolean getTypingIndicators() {
1017 return m
.getConfiguration().typingIndicators().orElse(false);
1020 private boolean getLinkPreviews() {
1021 return m
.getConfiguration().linkPreviews().orElse(false);
1025 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1027 private final GroupId groupId
;
1029 public DbusSignalGroupImpl(final GroupId groupId
) {
1030 this.groupId
= groupId
;
1031 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1032 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1033 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1034 new DbusProperty
<>("Description",
1035 () -> emptyIfNull(getGroup().description()),
1036 this::setGroupDescription
),
1037 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1038 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1039 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1040 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1041 new DbusProperty
<>("MessageExpirationTimer",
1042 () -> getGroup().messageExpirationTimer(),
1043 this::setMessageExpirationTime
),
1044 new DbusProperty
<>("Members",
1045 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1046 new DbusProperty
<>("PendingMembers",
1047 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1048 new DbusProperty
<>("RequestingMembers",
1049 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1050 new DbusProperty
<>("Admins",
1051 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1052 new DbusProperty
<>("PermissionAddMember",
1053 () -> getGroup().permissionAddMember().name(),
1054 this::setGroupPermissionAddMember
),
1055 new DbusProperty
<>("PermissionEditDetails",
1056 () -> getGroup().permissionEditDetails().name(),
1057 this::setGroupPermissionEditDetails
),
1058 new DbusProperty
<>("PermissionSendMessage",
1059 () -> getGroup().permissionSendMessage().name(),
1060 this::setGroupPermissionSendMessage
),
1061 new DbusProperty
<>("GroupInviteLink", () -> {
1062 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1063 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1068 public String
getObjectPath() {
1069 return getGroupObjectPath(objectPath
, groupId
.serialize());
1073 public void quitGroup() throws Error
.Failure
{
1075 m
.quitGroup(groupId
, Set
.of());
1076 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1077 throw new Error
.GroupNotFound(e
.getMessage());
1078 } catch (IOException e
) {
1079 throw new Error
.Failure(e
.getMessage());
1080 } catch (LastGroupAdminException e
) {
1081 throw new Error
.LastGroupAdmin(e
.getMessage());
1086 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1087 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1088 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1092 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1093 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1094 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1098 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1099 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1100 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1104 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1105 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1106 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1110 public void resetLink() throws Error
.Failure
{
1111 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1115 public void disableLink() throws Error
.Failure
{
1116 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1120 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1121 updateGroup(UpdateGroup
.newBuilder()
1122 .withGroupLinkState(requiresApproval
1123 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1124 : GroupLinkState
.ENABLED
)
1128 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1129 return m
.getGroup(groupId
);
1132 private void setGroupName(final String name
) {
1133 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1136 private void setGroupDescription(final String description
) {
1137 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1140 private void setGroupAvatar(final String avatar
) {
1141 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1144 private void setMessageExpirationTime(final int expirationTime
) {
1145 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1148 private void setGroupPermissionAddMember(final String permission
) {
1149 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1152 private void setGroupPermissionEditDetails(final String permission
) {
1153 updateGroup(UpdateGroup
.newBuilder()
1154 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1158 private void setGroupPermissionSendMessage(final String permission
) {
1159 updateGroup(UpdateGroup
.newBuilder()
1160 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1164 private void setIsBlocked(final boolean isBlocked
) {
1166 m
.setGroupBlocked(groupId
, isBlocked
);
1167 } catch (NotMasterDeviceException e
) {
1168 throw new Error
.Failure("This command doesn't work on linked devices.");
1169 } catch (GroupNotFoundException e
) {
1170 throw new Error
.GroupNotFound(e
.getMessage());
1171 } catch (IOException e
) {
1172 throw new Error
.Failure(e
.getMessage());
1176 private void updateGroup(final UpdateGroup updateGroup
) {
1178 m
.updateGroup(groupId
, updateGroup
);
1179 } catch (IOException e
) {
1180 throw new Error
.Failure(e
.getMessage());
1181 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1182 throw new Error
.GroupNotFound(e
.getMessage());
1183 } catch (AttachmentInvalidException e
) {
1184 throw new Error
.AttachmentInvalid(e
.getMessage());