1 package org
.asamk
.signal
.dbus
;
3 import org
.asamk
.Signal
;
4 import org
.asamk
.signal
.BaseConfig
;
5 import org
.asamk
.signal
.DbusReceiveMessageHandler
;
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
.InvalidNumberException
;
15 import org
.asamk
.signal
.manager
.api
.Message
;
16 import org
.asamk
.signal
.manager
.api
.Pair
;
17 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
18 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
19 import org
.asamk
.signal
.manager
.api
.TypingAction
;
20 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
21 import org
.asamk
.signal
.manager
.groups
.GroupId
;
22 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
23 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
24 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
25 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
26 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
27 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
28 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
29 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
30 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
31 import org
.asamk
.signal
.util
.ErrorUtils
;
32 import org
.freedesktop
.dbus
.DBusPath
;
33 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
34 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
35 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
36 import org
.freedesktop
.dbus
.interfaces
.DBusInterface
;
37 import org
.freedesktop
.dbus
.types
.Variant
;
38 import org
.slf4j
.Logger
;
39 import org
.slf4j
.LoggerFactory
;
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
;
53 import java
.util
.Optional
;
55 import java
.util
.UUID
;
56 import java
.util
.stream
.Collectors
;
57 import java
.util
.stream
.Stream
;
59 public class DbusSignalImpl
implements Signal
{
61 private final Manager m
;
62 private final DBusConnection connection
;
63 private final String objectPath
;
64 private final boolean noReceiveOnStart
;
66 private DBusPath thisDevice
;
67 private final List
<StructDevice
> devices
= new ArrayList
<>();
68 private final List
<StructGroup
> groups
= new ArrayList
<>();
69 private DbusReceiveMessageHandler dbusMessageHandler
;
70 private int subscriberCount
;
72 private final static Logger logger
= LoggerFactory
.getLogger(DbusSignalImpl
.class);
74 public DbusSignalImpl(
75 final Manager m
, DBusConnection connection
, final String objectPath
, final boolean noReceiveOnStart
78 this.connection
= connection
;
79 this.objectPath
= objectPath
;
80 this.noReceiveOnStart
= noReceiveOnStart
;
83 public void initObjects() {
84 if (!noReceiveOnStart
) {
90 updateConfiguration();
94 if (dbusMessageHandler
!= null) {
95 m
.removeReceiveHandler(dbusMessageHandler
);
96 dbusMessageHandler
= null;
100 unExportConfiguration();
104 public String
getObjectPath() {
109 public String
getSelfNumber() {
110 return m
.getSelfNumber();
114 public void subscribeReceive() {
115 if (dbusMessageHandler
== null) {
116 dbusMessageHandler
= new DbusReceiveMessageHandler(m
, connection
, objectPath
);
117 m
.addReceiveHandler(dbusMessageHandler
);
123 public void unsubscribeReceive() {
124 subscriberCount
= Math
.max(0, subscriberCount
- 1);
125 if (subscriberCount
== 0 && dbusMessageHandler
!= null) {
126 m
.removeReceiveHandler(dbusMessageHandler
);
127 dbusMessageHandler
= null;
132 public void submitRateLimitChallenge(String challenge
, String captchaString
) {
133 final var captcha
= captchaString
== null ?
null : captchaString
.replace("signalcaptcha://", "");
136 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
137 } catch (IOException e
) {
138 throw new Error
.Failure("Submit challenge error: " + e
.getMessage());
144 public void addDevice(String uri
) {
146 m
.addDeviceLink(new URI(uri
));
147 } catch (IOException
| InvalidDeviceLinkException e
) {
148 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
149 } catch (URISyntaxException e
) {
150 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
151 + " Device link uri has invalid format: "
157 public DBusPath
getDevice(long deviceId
) {
159 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
160 if (deviceOptional
.isEmpty()) {
161 throw new Error
.DeviceNotFound("Device not found");
163 return deviceOptional
.get().getObjectPath();
167 public List
<StructDevice
> listDevices() {
173 public DBusPath
getThisDevice() {
179 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
180 var recipients
= new ArrayList
<String
>(1);
181 recipients
.add(recipient
);
182 return sendMessage(message
, attachments
, recipients
);
186 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
188 final var results
= m
.sendMessage(new Message(message
, attachments
),
189 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
190 .map(RecipientIdentifier
.class::cast
)
191 .collect(Collectors
.toSet()));
193 checkSendMessageResults(results
.timestamp(), results
.results());
194 return results
.timestamp();
195 } catch (AttachmentInvalidException e
) {
196 throw new Error
.AttachmentInvalid(e
.getMessage());
197 } catch (IOException e
) {
198 throw new Error
.Failure(e
);
199 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
200 throw new Error
.GroupNotFound(e
.getMessage());
205 public long sendRemoteDeleteMessage(
206 final long targetSentTimestamp
, final String recipient
208 var recipients
= new ArrayList
<String
>(1);
209 recipients
.add(recipient
);
210 return sendRemoteDeleteMessage(targetSentTimestamp
, recipients
);
214 public long sendRemoteDeleteMessage(
215 final long targetSentTimestamp
, final List
<String
> recipients
218 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
219 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
220 .map(RecipientIdentifier
.class::cast
)
221 .collect(Collectors
.toSet()));
222 checkSendMessageResults(results
.timestamp(), results
.results());
223 return results
.timestamp();
224 } catch (IOException e
) {
225 throw new Error
.Failure(e
.getMessage());
226 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
227 throw new Error
.GroupNotFound(e
.getMessage());
232 public long sendGroupRemoteDeleteMessage(
233 final long targetSentTimestamp
, final byte[] groupId
236 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
237 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
238 checkSendMessageResults(results
.timestamp(), results
.results());
239 return results
.timestamp();
240 } catch (IOException e
) {
241 throw new Error
.Failure(e
.getMessage());
242 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
243 throw new Error
.GroupNotFound(e
.getMessage());
248 public long sendMessageReaction(
250 final boolean remove
,
251 final String targetAuthor
,
252 final long targetSentTimestamp
,
253 final String recipient
255 var recipients
= new ArrayList
<String
>(1);
256 recipients
.add(recipient
);
257 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, recipients
);
261 public long sendMessageReaction(
263 final boolean remove
,
264 final String targetAuthor
,
265 final long targetSentTimestamp
,
266 final List
<String
> recipients
269 final var results
= m
.sendMessageReaction(emoji
,
271 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
273 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
274 .map(RecipientIdentifier
.class::cast
)
275 .collect(Collectors
.toSet()));
276 checkSendMessageResults(results
.timestamp(), results
.results());
277 return results
.timestamp();
278 } catch (IOException e
) {
279 throw new Error
.Failure(e
.getMessage());
280 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
281 throw new Error
.GroupNotFound(e
.getMessage());
286 public void sendTyping(
287 final String recipient
, final boolean stop
288 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
290 var recipients
= new ArrayList
<String
>(1);
291 recipients
.add(recipient
);
292 m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
293 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
294 .map(RecipientIdentifier
.class::cast
)
295 .collect(Collectors
.toSet()));
296 } catch (IOException e
) {
297 throw new Error
.Failure(e
.getMessage());
298 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
299 throw new Error
.GroupNotFound(e
.getMessage());
300 } catch (UntrustedIdentityException e
) {
301 throw new Error
.UntrustedIdentity(e
.getMessage());
306 public void sendReadReceipt(
307 final String recipient
, final List
<Long
> messageIds
308 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
310 m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
311 } catch (IOException e
) {
312 throw new Error
.Failure(e
.getMessage());
313 } catch (UntrustedIdentityException e
) {
314 throw new Error
.UntrustedIdentity(e
.getMessage());
319 public void sendViewedReceipt(
320 final String recipient
, final List
<Long
> messageIds
321 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
323 m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
324 } catch (IOException e
) {
325 throw new Error
.Failure(e
.getMessage());
326 } catch (UntrustedIdentityException e
) {
327 throw new Error
.UntrustedIdentity(e
.getMessage());
332 public void sendContacts() {
335 } catch (IOException e
) {
336 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
341 public void sendSyncRequest() {
343 m
.requestAllSyncData();
344 } catch (IOException e
) {
345 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
350 public long sendNoteToSelfMessage(
351 final String message
, final List
<String
> attachments
352 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
354 final var results
= m
.sendMessage(new Message(message
, attachments
),
355 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
356 checkSendMessageResults(results
.timestamp(), results
.results());
357 return results
.timestamp();
358 } catch (AttachmentInvalidException e
) {
359 throw new Error
.AttachmentInvalid(e
.getMessage());
360 } catch (IOException e
) {
361 throw new Error
.Failure(e
.getMessage());
362 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
363 throw new Error
.GroupNotFound(e
.getMessage());
368 public void sendEndSessionMessage(final List
<String
> recipients
) {
370 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
371 checkSendMessageResults(results
.timestamp(), results
.results());
372 } catch (IOException e
) {
373 throw new Error
.Failure(e
.getMessage());
378 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
380 var results
= m
.sendMessage(new Message(message
, attachments
),
381 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
382 checkSendMessageResults(results
.timestamp(), results
.results());
383 return results
.timestamp();
384 } catch (IOException e
) {
385 throw new Error
.Failure(e
.getMessage());
386 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
387 throw new Error
.GroupNotFound(e
.getMessage());
388 } catch (AttachmentInvalidException e
) {
389 throw new Error
.AttachmentInvalid(e
.getMessage());
394 public long sendGroupMessageReaction(
396 final boolean remove
,
397 final String targetAuthor
,
398 final long targetSentTimestamp
,
402 final var results
= m
.sendMessageReaction(emoji
,
404 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
406 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
407 checkSendMessageResults(results
.timestamp(), results
.results());
408 return results
.timestamp();
409 } catch (IOException e
) {
410 throw new Error
.Failure(e
.getMessage());
411 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
412 throw new Error
.GroupNotFound(e
.getMessage());
416 // Since contact names might be empty if not defined, also potentially return
419 public String
getContactName(final String number
) {
420 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
421 return name
== null ?
"" : name
;
425 public void setContactName(final String number
, final String name
) {
427 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
428 } catch (NotMasterDeviceException e
) {
429 throw new Error
.Failure("This command doesn't work on linked devices.");
430 } catch (IOException e
) {
431 throw new Error
.Failure("Contact is not registered.");
436 public void setExpirationTimer(final String number
, final int expiration
) {
438 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
439 } catch (IOException e
) {
440 throw new Error
.Failure(e
.getMessage());
445 public void setContactBlocked(final String number
, final boolean blocked
) {
447 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
448 } catch (NotMasterDeviceException e
) {
449 throw new Error
.Failure("This command doesn't work on linked devices.");
450 } catch (IOException e
) {
451 throw new Error
.Failure(e
.getMessage());
456 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
458 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
459 } catch (NotMasterDeviceException e
) {
460 throw new Error
.Failure("This command doesn't work on linked devices.");
461 } catch (GroupNotFoundException e
) {
462 throw new Error
.GroupNotFound(e
.getMessage());
463 } catch (IOException e
) {
464 throw new Error
.Failure(e
.getMessage());
469 public List
<byte[]> getGroupIds() {
470 var groups
= m
.getGroups();
471 var ids
= new ArrayList
<byte[]>(groups
.size());
472 for (var group
: groups
) {
473 ids
.add(group
.groupId().serialize());
479 public DBusPath
getGroup(final byte[] groupId
) {
481 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
482 if (groupOptional
.isEmpty()) {
483 throw new Error
.GroupNotFound("Group not found");
485 return groupOptional
.get().getObjectPath();
489 public List
<StructGroup
> listGroups() {
495 public String
getGroupName(final byte[] groupId
) {
496 var group
= m
.getGroup(getGroupId(groupId
));
497 if (group
== null || group
.title() == null) {
500 return group
.title();
505 public List
<String
> getGroupMembers(final byte[] groupId
) {
506 var group
= m
.getGroup(getGroupId(groupId
));
510 final var members
= group
.members();
511 return getRecipientStrings(members
);
516 public byte[] createGroup(
517 final String name
, final List
<String
> members
, final String avatar
518 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
519 return updateGroup(new byte[0], name
, members
, avatar
);
523 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
525 groupId
= nullIfEmpty(groupId
);
526 name
= nullIfEmpty(name
);
527 avatar
= nullIfEmpty(avatar
);
528 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
529 if (groupId
== null) {
530 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
531 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
532 return results
.first().serialize();
534 final var results
= m
.updateGroup(getGroupId(groupId
),
535 UpdateGroup
.newBuilder()
537 .withMembers(memberIdentifiers
)
538 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
540 if (results
!= null) {
541 checkSendMessageResults(results
.timestamp(), results
.results());
545 } catch (IOException e
) {
546 throw new Error
.Failure(e
.getMessage());
547 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
548 throw new Error
.GroupNotFound(e
.getMessage());
549 } catch (AttachmentInvalidException e
) {
550 throw new Error
.AttachmentInvalid(e
.getMessage());
555 public boolean isRegistered() {
560 public boolean isRegistered(String number
) {
561 var result
= isRegistered(List
.of(number
));
562 return result
.get(0);
566 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
567 var results
= new ArrayList
<Boolean
>();
568 if (numbers
.isEmpty()) {
572 Map
<String
, Pair
<String
, UUID
>> registered
;
574 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
575 } catch (IOException e
) {
576 throw new Error
.Failure(e
.getMessage());
579 return numbers
.stream().map(number
-> {
580 var uuid
= registered
.get(number
).second();
582 }).collect(Collectors
.toList());
586 public void updateProfile(
592 final boolean removeAvatar
595 givenName
= nullIfEmpty(givenName
);
596 familyName
= nullIfEmpty(familyName
);
597 about
= nullIfEmpty(about
);
598 aboutEmoji
= nullIfEmpty(aboutEmoji
);
599 avatarPath
= nullIfEmpty(avatarPath
);
600 Optional
<File
> avatarFile
= removeAvatar
602 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
603 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
604 } catch (IOException e
) {
605 throw new Error
.Failure(e
.getMessage());
610 public void updateProfile(
613 final String aboutEmoji
,
615 final boolean removeAvatar
617 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
621 public void removePin() {
623 m
.setRegistrationLockPin(Optional
.empty());
624 } catch (IOException e
) {
625 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
630 public void setPin(String registrationLockPin
) {
632 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
633 } catch (IOException e
) {
634 throw new Error
.Failure("Set pin error: " + e
.getMessage());
638 // Provide option to query a version string in order to react on potential
639 // future interface changes
641 public String
version() {
642 return BaseConfig
.PROJECT_VERSION
;
645 // Create a unique list of Numbers from Identities and Contacts to really get
646 // all numbers the system knows
648 public List
<String
> listNumbers() {
649 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
650 m
.getContacts().stream().map(Pair
::first
))
651 .map(a
-> a
.getNumber().orElse(null))
652 .filter(Objects
::nonNull
)
654 .collect(Collectors
.toList());
658 public List
<String
> getContactNumber(final String name
) {
659 // Contact names have precedence.
660 var numbers
= new ArrayList
<String
>();
661 var contacts
= m
.getContacts();
662 for (var c
: contacts
) {
663 if (name
.equals(c
.second().getName())) {
664 numbers
.add(c
.first().getLegacyIdentifier());
667 // Try profiles if no contact name was found
668 for (var identity
: m
.getIdentities()) {
669 final var address
= identity
.recipient();
670 var number
= address
.getNumber().orElse(null);
671 if (number
!= null) {
672 Profile profile
= null;
674 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
675 } catch (IOException ignored
) {
677 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
686 public void quitGroup(final byte[] groupId
) {
687 var group
= getGroupId(groupId
);
689 m
.quitGroup(group
, Set
.of());
690 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
691 throw new Error
.GroupNotFound(e
.getMessage());
692 } catch (IOException
| LastGroupAdminException e
) {
693 throw new Error
.Failure(e
.getMessage());
698 public byte[] joinGroup(final String groupLink
) {
700 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
701 if (linkUrl
== null) {
702 throw new Error
.Failure("Group link is invalid:");
704 final var result
= m
.joinGroup(linkUrl
);
705 return result
.first().serialize();
706 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
707 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
708 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
709 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
710 } catch (IOException e
) {
711 throw new Error
.Failure(e
.getMessage());
716 public boolean isContactBlocked(final String number
) {
717 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
721 public boolean isGroupBlocked(final byte[] groupId
) {
722 var group
= m
.getGroup(getGroupId(groupId
));
726 return group
.isBlocked();
731 public boolean isMember(final byte[] groupId
) {
732 var group
= m
.getGroup(getGroupId(groupId
));
736 return group
.isMember();
741 public String
uploadStickerPack(String stickerPackPath
) {
742 File path
= new File(stickerPackPath
);
744 return m
.uploadStickerPack(path
).toString();
745 } catch (IOException e
) {
746 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
747 } catch (StickerPackInvalidException e
) {
748 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
752 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
753 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
759 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
761 if (result
.isIdentityFailure()) {
762 throw new Error
.UntrustedIdentity(message
);
764 throw new Error
.Failure(message
);
768 private static void checkSendMessageResults(
769 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
770 ) throws DBusExecutionException
{
771 final var sendMessageResults
= results
.values().stream().findFirst();
772 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
773 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
777 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
778 if (errors
.size() == 0) {
782 var message
= new StringBuilder();
783 message
.append(timestamp
).append('\n');
784 message
.append("Failed to send (some) messages:\n");
785 for (var error
: errors
) {
786 message
.append(error
).append('\n');
789 throw new Error
.Failure(message
.toString());
792 private static void checkSendMessageResults(
793 long timestamp
, Collection
<SendMessageResult
> results
794 ) throws DBusExecutionException
{
795 if (results
.size() == 1) {
796 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
800 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
801 if (errors
.size() == 0) {
805 var message
= new StringBuilder();
806 message
.append(timestamp
).append('\n');
807 message
.append("Failed to send (some) messages:\n");
808 for (var error
: errors
) {
809 message
.append(error
).append('\n');
812 throw new Error
.Failure(message
.toString());
815 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
816 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).collect(Collectors
.toList());
819 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
820 final Collection
<String
> recipientStrings
, final String localNumber
821 ) throws DBusExecutionException
{
822 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
823 for (var recipientString
: recipientStrings
) {
824 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
829 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
830 final String recipientString
, final String localNumber
831 ) throws DBusExecutionException
{
833 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
834 } catch (InvalidNumberException e
) {
835 throw new Error
.InvalidNumber(e
.getMessage());
839 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
841 return GroupId
.unknownVersion(groupId
);
842 } catch (Throwable e
) {
843 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
847 private byte[] nullIfEmpty(final byte[] array
) {
848 return array
.length
== 0 ?
null : array
;
851 private String
nullIfEmpty(final String name
) {
852 return name
.isEmpty() ?
null : name
;
855 private String
emptyIfNull(final String string
) {
856 return string
== null ?
"" : string
;
859 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
860 return basePath
+ "/Devices/" + deviceId
;
863 private void updateDevices() {
864 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
866 linkedDevices
= m
.getLinkedDevices();
867 } catch (IOException e
) {
868 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
873 linkedDevices
.forEach(d
-> {
874 final var object
= new DbusSignalDeviceImpl(d
);
875 final var deviceObjectPath
= object
.getObjectPath();
876 exportObject(object
);
877 if (d
.isThisDevice()) {
878 thisDevice
= new DBusPath(deviceObjectPath
);
880 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
884 private void unExportDevices() {
885 this.devices
.stream()
886 .map(StructDevice
::getObjectPath
)
887 .map(DBusPath
::getPath
)
888 .forEach(connection
::unExportObject
);
889 this.devices
.clear();
892 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
893 return basePath
+ "/Groups/" + Base64
.getEncoder()
894 .encodeToString(groupId
)
900 private void updateGroups() {
901 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
902 groups
= m
.getGroups();
906 groups
.forEach(g
-> {
907 final var object
= new DbusSignalGroupImpl(g
.groupId());
908 exportObject(object
);
909 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
910 g
.groupId().serialize(),
911 emptyIfNull(g
.title())));
915 private void unExportGroups() {
916 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
920 private static String
getConfigurationObjectPath(String basePath
) {
921 return basePath
+ "/Configuration";
924 private void updateConfiguration() {
925 unExportConfiguration();
926 final var object
= new DbusSignalConfigurationImpl();
927 exportObject(object
);
930 private void unExportConfiguration() {
931 final var objectPath
= getConfigurationObjectPath(this.objectPath
);
932 connection
.unExportObject(objectPath
);
935 private void exportObject(final DBusInterface object
) {
937 connection
.exportObject(object
);
938 logger
.debug("Exported dbus object: " + object
.getObjectPath());
939 } catch (DBusException e
) {
944 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
946 private final org
.asamk
.signal
.manager
.api
.Device device
;
948 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
949 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
950 List
.of(new DbusProperty
<>("Id", device
::id
),
951 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
952 new DbusProperty
<>("Created", device
::created
),
953 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
954 this.device
= device
;
958 public String
getObjectPath() {
959 return getDeviceObjectPath(objectPath
, device
.id());
963 public void removeDevice() throws Error
.Failure
{
965 m
.removeLinkedDevices(device
.id());
967 } catch (IOException e
) {
968 throw new Error
.Failure(e
.getMessage());
972 private void setDeviceName(String name
) {
973 if (!device
.isThisDevice()) {
974 throw new Error
.Failure("Only the name of this device can be changed");
977 m
.updateAccountAttributes(name
);
978 // update device list
980 } catch (IOException e
) {
981 throw new Error
.Failure(e
.getMessage());
986 public class DbusSignalConfigurationImpl
extends DbusProperties
implements Signal
.Configuration
{
988 public DbusSignalConfigurationImpl(
990 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Configuration",
991 List
.of(new DbusProperty
<>("ReadReceipts", this::getReadReceipts
, this::setReadReceipts
),
992 new DbusProperty
<>("UnidentifiedDeliveryIndicators",
993 this::getUnidentifiedDeliveryIndicators
,
994 this::setUnidentifiedDeliveryIndicators
),
995 new DbusProperty
<>("TypingIndicators",
996 this::getTypingIndicators
,
997 this::setTypingIndicators
),
998 new DbusProperty
<>("LinkPreviews", this::getLinkPreviews
, this::setLinkPreviews
))));
1003 public String
getObjectPath() {
1004 return getConfigurationObjectPath(objectPath
);
1007 public void setReadReceipts(Boolean readReceipts
) {
1008 setConfiguration(readReceipts
, null, null, null);
1011 public void setUnidentifiedDeliveryIndicators(Boolean unidentifiedDeliveryIndicators
) {
1012 setConfiguration(null, unidentifiedDeliveryIndicators
, null, null);
1015 public void setTypingIndicators(Boolean typingIndicators
) {
1016 setConfiguration(null, null, typingIndicators
, null);
1019 public void setLinkPreviews(Boolean linkPreviews
) {
1020 setConfiguration(null, null, null, linkPreviews
);
1023 private void setConfiguration(
1024 Boolean readReceipts
,
1025 Boolean unidentifiedDeliveryIndicators
,
1026 Boolean typingIndicators
,
1027 Boolean linkPreviews
1030 m
.updateConfiguration(new org
.asamk
.signal
.manager
.api
.Configuration(Optional
.ofNullable(readReceipts
),
1031 Optional
.ofNullable(unidentifiedDeliveryIndicators
),
1032 Optional
.ofNullable(typingIndicators
),
1033 Optional
.ofNullable(linkPreviews
)));
1034 } catch (IOException e
) {
1035 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
1036 } catch (NotMasterDeviceException e
) {
1037 throw new Error
.Failure("This command doesn't work on linked devices.");
1041 private boolean getReadReceipts() {
1042 return m
.getConfiguration().readReceipts().orElse(false);
1045 private boolean getUnidentifiedDeliveryIndicators() {
1046 return m
.getConfiguration().unidentifiedDeliveryIndicators().orElse(false);
1049 private boolean getTypingIndicators() {
1050 return m
.getConfiguration().typingIndicators().orElse(false);
1053 private boolean getLinkPreviews() {
1054 return m
.getConfiguration().linkPreviews().orElse(false);
1058 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
1060 private final GroupId groupId
;
1062 public DbusSignalGroupImpl(final GroupId groupId
) {
1063 this.groupId
= groupId
;
1064 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
1065 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
1066 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
1067 new DbusProperty
<>("Description",
1068 () -> emptyIfNull(getGroup().description()),
1069 this::setGroupDescription
),
1070 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
1071 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
1072 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
1073 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
1074 new DbusProperty
<>("MessageExpirationTimer",
1075 () -> getGroup().messageExpirationTimer(),
1076 this::setMessageExpirationTime
),
1077 new DbusProperty
<>("Members",
1078 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
1079 new DbusProperty
<>("PendingMembers",
1080 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
1081 new DbusProperty
<>("RequestingMembers",
1082 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
1083 new DbusProperty
<>("Admins",
1084 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
1085 new DbusProperty
<>("PermissionAddMember",
1086 () -> getGroup().permissionAddMember().name(),
1087 this::setGroupPermissionAddMember
),
1088 new DbusProperty
<>("PermissionEditDetails",
1089 () -> getGroup().permissionEditDetails().name(),
1090 this::setGroupPermissionEditDetails
),
1091 new DbusProperty
<>("PermissionSendMessage",
1092 () -> getGroup().permissionSendMessage().name(),
1093 this::setGroupPermissionSendMessage
),
1094 new DbusProperty
<>("GroupInviteLink", () -> {
1095 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
1096 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
1101 public String
getObjectPath() {
1102 return getGroupObjectPath(objectPath
, groupId
.serialize());
1106 public void quitGroup() throws Error
.Failure
{
1108 m
.quitGroup(groupId
, Set
.of());
1109 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
1110 throw new Error
.GroupNotFound(e
.getMessage());
1111 } catch (IOException e
) {
1112 throw new Error
.Failure(e
.getMessage());
1113 } catch (LastGroupAdminException e
) {
1114 throw new Error
.LastGroupAdmin(e
.getMessage());
1119 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
1120 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1121 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1125 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1126 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1127 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1131 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1132 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1133 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1137 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1138 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1139 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1143 public void resetLink() throws Error
.Failure
{
1144 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1148 public void disableLink() throws Error
.Failure
{
1149 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1153 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1154 updateGroup(UpdateGroup
.newBuilder()
1155 .withGroupLinkState(requiresApproval
1156 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1157 : GroupLinkState
.ENABLED
)
1161 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1162 return m
.getGroup(groupId
);
1165 private void setGroupName(final String name
) {
1166 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1169 private void setGroupDescription(final String description
) {
1170 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1173 private void setGroupAvatar(final String avatar
) {
1174 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1177 private void setMessageExpirationTime(final int expirationTime
) {
1178 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1181 private void setGroupPermissionAddMember(final String permission
) {
1182 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1185 private void setGroupPermissionEditDetails(final String permission
) {
1186 updateGroup(UpdateGroup
.newBuilder()
1187 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1191 private void setGroupPermissionSendMessage(final String permission
) {
1192 updateGroup(UpdateGroup
.newBuilder()
1193 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1197 private void setIsBlocked(final boolean isBlocked
) {
1199 m
.setGroupBlocked(groupId
, isBlocked
);
1200 } catch (NotMasterDeviceException e
) {
1201 throw new Error
.Failure("This command doesn't work on linked devices.");
1202 } catch (GroupNotFoundException e
) {
1203 throw new Error
.GroupNotFound(e
.getMessage());
1204 } catch (IOException e
) {
1205 throw new Error
.Failure(e
.getMessage());
1209 private void updateGroup(final UpdateGroup updateGroup
) {
1211 m
.updateGroup(groupId
, updateGroup
);
1212 } catch (IOException e
) {
1213 throw new Error
.Failure(e
.getMessage());
1214 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1215 throw new Error
.GroupNotFound(e
.getMessage());
1216 } catch (AttachmentInvalidException e
) {
1217 throw new Error
.AttachmentInvalid(e
.getMessage());