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
;
37 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
40 import java
.io
.IOException
;
42 import java
.net
.URISyntaxException
;
43 import java
.util
.ArrayList
;
44 import java
.util
.Arrays
;
45 import java
.util
.Base64
;
46 import java
.util
.Collection
;
47 import java
.util
.HashSet
;
48 import java
.util
.List
;
50 import java
.util
.Objects
;
51 import java
.util
.Optional
;
53 import java
.util
.UUID
;
54 import java
.util
.stream
.Collectors
;
55 import java
.util
.stream
.Stream
;
57 public class DbusSignalImpl
implements Signal
{
59 private final Manager m
;
60 private final DBusConnection connection
;
61 private final String objectPath
;
63 private DBusPath thisDevice
;
64 private final List
<StructDevice
> devices
= new ArrayList
<>();
65 private final List
<StructGroup
> groups
= new ArrayList
<>();
67 public DbusSignalImpl(final Manager m
, DBusConnection connection
, final String objectPath
) {
69 this.connection
= connection
;
70 this.objectPath
= objectPath
;
73 public void initObjects() {
84 public String
getObjectPath() {
89 public String
getSelfNumber() {
90 return m
.getSelfNumber();
94 public void submitRateLimitChallenge(String challenge
, String captchaString
) throws IOErrorException
{
95 final var captcha
= captchaString
== null ?
null : captchaString
.replace("signalcaptcha://", "");
98 m
.submitRateLimitRecaptchaChallenge(challenge
, captcha
);
99 } catch (IOException e
) {
100 throw new IOErrorException("Submit challenge error: " + e
.getMessage(), e
);
106 public void addDevice(String uri
) {
108 m
.addDeviceLink(new URI(uri
));
109 } catch (IOException
| InvalidDeviceLinkException e
) {
110 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
111 } catch (URISyntaxException e
) {
112 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
113 + " Device link uri has invalid format: "
119 public DBusPath
getDevice(long deviceId
) {
121 final var deviceOptional
= devices
.stream().filter(g
-> g
.getId().equals(deviceId
)).findFirst();
122 if (deviceOptional
.isEmpty()) {
123 throw new Error
.DeviceNotFound("Device not found");
125 return deviceOptional
.get().getObjectPath();
129 public List
<StructDevice
> listDevices() {
135 public DBusPath
getThisDevice() {
141 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
142 var recipients
= new ArrayList
<String
>(1);
143 recipients
.add(recipient
);
144 return sendMessage(message
, attachments
, recipients
);
148 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
150 final var results
= m
.sendMessage(new Message(message
, attachments
),
151 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
152 .map(RecipientIdentifier
.class::cast
)
153 .collect(Collectors
.toSet()));
155 checkSendMessageResults(results
.timestamp(), results
.results());
156 return results
.timestamp();
157 } catch (AttachmentInvalidException e
) {
158 throw new Error
.AttachmentInvalid(e
.getMessage());
159 } catch (IOException e
) {
160 throw new Error
.Failure(e
);
161 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
162 throw new Error
.GroupNotFound(e
.getMessage());
167 public long sendRemoteDeleteMessage(
168 final long targetSentTimestamp
, final String recipient
170 var recipients
= new ArrayList
<String
>(1);
171 recipients
.add(recipient
);
172 return sendRemoteDeleteMessage(targetSentTimestamp
, recipients
);
176 public long sendRemoteDeleteMessage(
177 final long targetSentTimestamp
, final List
<String
> recipients
180 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
181 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
182 .map(RecipientIdentifier
.class::cast
)
183 .collect(Collectors
.toSet()));
184 checkSendMessageResults(results
.timestamp(), results
.results());
185 return results
.timestamp();
186 } catch (IOException e
) {
187 throw new Error
.Failure(e
.getMessage());
188 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
189 throw new Error
.GroupNotFound(e
.getMessage());
194 public long sendGroupRemoteDeleteMessage(
195 final long targetSentTimestamp
, final byte[] groupId
198 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
199 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
200 checkSendMessageResults(results
.timestamp(), results
.results());
201 return results
.timestamp();
202 } catch (IOException e
) {
203 throw new Error
.Failure(e
.getMessage());
204 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
205 throw new Error
.GroupNotFound(e
.getMessage());
210 public long sendMessageReaction(
212 final boolean remove
,
213 final String targetAuthor
,
214 final long targetSentTimestamp
,
215 final String recipient
217 var recipients
= new ArrayList
<String
>(1);
218 recipients
.add(recipient
);
219 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, recipients
);
223 public long sendMessageReaction(
225 final boolean remove
,
226 final String targetAuthor
,
227 final long targetSentTimestamp
,
228 final List
<String
> recipients
231 final var results
= m
.sendMessageReaction(emoji
,
233 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
235 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
236 .map(RecipientIdentifier
.class::cast
)
237 .collect(Collectors
.toSet()));
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 void sendTyping(
249 final String recipient
, final boolean stop
250 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
252 var recipients
= new ArrayList
<String
>(1);
253 recipients
.add(recipient
);
254 m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
255 getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()).stream()
256 .map(RecipientIdentifier
.class::cast
)
257 .collect(Collectors
.toSet()));
258 } catch (IOException e
) {
259 throw new Error
.Failure(e
.getMessage());
260 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
261 throw new Error
.GroupNotFound(e
.getMessage());
262 } catch (UntrustedIdentityException e
) {
263 throw new Error
.UntrustedIdentity(e
.getMessage());
268 public void sendReadReceipt(
269 final String recipient
, final List
<Long
> messageIds
270 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
272 m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
273 } catch (IOException e
) {
274 throw new Error
.Failure(e
.getMessage());
275 } catch (UntrustedIdentityException e
) {
276 throw new Error
.UntrustedIdentity(e
.getMessage());
281 public void sendViewedReceipt(
282 final String recipient
, final List
<Long
> messageIds
283 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
285 m
.sendViewedReceipt(getSingleRecipientIdentifier(recipient
, m
.getSelfNumber()), messageIds
);
286 } catch (IOException e
) {
287 throw new Error
.Failure(e
.getMessage());
288 } catch (UntrustedIdentityException e
) {
289 throw new Error
.UntrustedIdentity(e
.getMessage());
294 public void sendContacts() {
297 } catch (IOException e
) {
298 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
303 public void sendSyncRequest() {
305 m
.requestAllSyncData();
306 } catch (IOException e
) {
307 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
312 public long sendNoteToSelfMessage(
313 final String message
, final List
<String
> attachments
314 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
316 final var results
= m
.sendMessage(new Message(message
, attachments
),
317 Set
.of(RecipientIdentifier
.NoteToSelf
.INSTANCE
));
318 checkSendMessageResults(results
.timestamp(), results
.results());
319 return results
.timestamp();
320 } catch (AttachmentInvalidException e
) {
321 throw new Error
.AttachmentInvalid(e
.getMessage());
322 } catch (IOException e
) {
323 throw new Error
.Failure(e
.getMessage());
324 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
325 throw new Error
.GroupNotFound(e
.getMessage());
330 public void sendEndSessionMessage(final List
<String
> recipients
) {
332 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber()));
333 checkSendMessageResults(results
.timestamp(), results
.results());
334 } catch (IOException e
) {
335 throw new Error
.Failure(e
.getMessage());
340 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
342 var results
= m
.sendMessage(new Message(message
, attachments
),
343 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
344 checkSendMessageResults(results
.timestamp(), results
.results());
345 return results
.timestamp();
346 } catch (IOException e
) {
347 throw new Error
.Failure(e
.getMessage());
348 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
349 throw new Error
.GroupNotFound(e
.getMessage());
350 } catch (AttachmentInvalidException e
) {
351 throw new Error
.AttachmentInvalid(e
.getMessage());
356 public long sendGroupMessageReaction(
358 final boolean remove
,
359 final String targetAuthor
,
360 final long targetSentTimestamp
,
364 final var results
= m
.sendMessageReaction(emoji
,
366 getSingleRecipientIdentifier(targetAuthor
, m
.getSelfNumber()),
368 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
369 checkSendMessageResults(results
.timestamp(), results
.results());
370 return results
.timestamp();
371 } catch (IOException e
) {
372 throw new Error
.Failure(e
.getMessage());
373 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
374 throw new Error
.GroupNotFound(e
.getMessage());
378 // Since contact names might be empty if not defined, also potentially return
381 public String
getContactName(final String number
) {
382 final var name
= m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
383 return name
== null ?
"" : name
;
387 public void setContactName(final String number
, final String name
) {
389 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), name
);
390 } catch (NotMasterDeviceException e
) {
391 throw new Error
.Failure("This command doesn't work on linked devices.");
392 } catch (IOException e
) {
393 throw new Error
.Failure("Contact is not registered.");
398 public void setExpirationTimer(final String number
, final int expiration
) {
400 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), expiration
);
401 } catch (IOException e
) {
402 throw new Error
.Failure(e
.getMessage());
407 public void setContactBlocked(final String number
, final boolean blocked
) {
409 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()), blocked
);
410 } catch (NotMasterDeviceException e
) {
411 throw new Error
.Failure("This command doesn't work on linked devices.");
412 } catch (IOException e
) {
413 throw new Error
.Failure(e
.getMessage());
418 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
420 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
421 } catch (NotMasterDeviceException e
) {
422 throw new Error
.Failure("This command doesn't work on linked devices.");
423 } catch (GroupNotFoundException e
) {
424 throw new Error
.GroupNotFound(e
.getMessage());
425 } catch (IOException e
) {
426 throw new Error
.Failure(e
.getMessage());
431 public List
<byte[]> getGroupIds() {
432 var groups
= m
.getGroups();
433 var ids
= new ArrayList
<byte[]>(groups
.size());
434 for (var group
: groups
) {
435 ids
.add(group
.groupId().serialize());
441 public DBusPath
getGroup(final byte[] groupId
) {
443 final var groupOptional
= groups
.stream().filter(g
-> Arrays
.equals(g
.getId(), groupId
)).findFirst();
444 if (groupOptional
.isEmpty()) {
445 throw new Error
.GroupNotFound("Group not found");
447 return groupOptional
.get().getObjectPath();
451 public List
<StructGroup
> listGroups() {
457 public String
getGroupName(final byte[] groupId
) {
458 var group
= m
.getGroup(getGroupId(groupId
));
459 if (group
== null || group
.title() == null) {
462 return group
.title();
467 public List
<String
> getGroupMembers(final byte[] groupId
) {
468 var group
= m
.getGroup(getGroupId(groupId
));
472 final var members
= group
.members();
473 return getRecipientStrings(members
);
478 public byte[] createGroup(
479 final String name
, final List
<String
> members
, final String avatar
480 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.InvalidNumber
{
481 return updateGroup(new byte[0], name
, members
, avatar
);
485 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
487 groupId
= nullIfEmpty(groupId
);
488 name
= nullIfEmpty(name
);
489 avatar
= nullIfEmpty(avatar
);
490 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getSelfNumber());
491 if (groupId
== null) {
492 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
493 checkSendMessageResults(results
.second().timestamp(), results
.second().results());
494 return results
.first().serialize();
496 final var results
= m
.updateGroup(getGroupId(groupId
),
497 UpdateGroup
.newBuilder()
499 .withMembers(memberIdentifiers
)
500 .withAvatarFile(avatar
== null ?
null : new File(avatar
))
502 if (results
!= null) {
503 checkSendMessageResults(results
.timestamp(), results
.results());
507 } catch (IOException e
) {
508 throw new Error
.Failure(e
.getMessage());
509 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
510 throw new Error
.GroupNotFound(e
.getMessage());
511 } catch (AttachmentInvalidException e
) {
512 throw new Error
.AttachmentInvalid(e
.getMessage());
517 public boolean isRegistered() {
522 public boolean isRegistered(String number
) {
523 var result
= isRegistered(List
.of(number
));
524 return result
.get(0);
528 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
529 var results
= new ArrayList
<Boolean
>();
530 if (numbers
.isEmpty()) {
534 Map
<String
, Pair
<String
, UUID
>> registered
;
536 registered
= m
.areUsersRegistered(new HashSet
<>(numbers
));
537 } catch (IOException e
) {
538 throw new Error
.Failure(e
.getMessage());
541 return numbers
.stream().map(number
-> {
542 var uuid
= registered
.get(number
).second();
544 }).collect(Collectors
.toList());
548 public void updateProfile(
554 final boolean removeAvatar
557 givenName
= nullIfEmpty(givenName
);
558 familyName
= nullIfEmpty(familyName
);
559 about
= nullIfEmpty(about
);
560 aboutEmoji
= nullIfEmpty(aboutEmoji
);
561 avatarPath
= nullIfEmpty(avatarPath
);
562 Optional
<File
> avatarFile
= removeAvatar
564 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
565 m
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatarFile
);
566 } catch (IOException e
) {
567 throw new Error
.Failure(e
.getMessage());
572 public void updateProfile(
575 final String aboutEmoji
,
577 final boolean removeAvatar
579 updateProfile(name
, "", about
, aboutEmoji
, avatarPath
, removeAvatar
);
583 public void removePin() {
585 m
.setRegistrationLockPin(Optional
.empty());
586 } catch (UnauthenticatedResponseException e
) {
587 throw new Error
.Failure("Remove pin failed with unauthenticated response: " + e
.getMessage());
588 } catch (IOException e
) {
589 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
594 public void setPin(String registrationLockPin
) {
596 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
597 } catch (UnauthenticatedResponseException e
) {
598 throw new Error
.Failure("Set pin error failed with unauthenticated response: " + e
.getMessage());
599 } catch (IOException e
) {
600 throw new Error
.Failure("Set pin error: " + e
.getMessage());
604 // Provide option to query a version string in order to react on potential
605 // future interface changes
607 public String
version() {
608 return BaseConfig
.PROJECT_VERSION
;
611 // Create a unique list of Numbers from Identities and Contacts to really get
612 // all numbers the system knows
614 public List
<String
> listNumbers() {
615 return Stream
.concat(m
.getIdentities().stream().map(Identity
::recipient
),
616 m
.getContacts().stream().map(Pair
::first
))
617 .map(a
-> a
.getNumber().orElse(null))
618 .filter(Objects
::nonNull
)
620 .collect(Collectors
.toList());
624 public List
<String
> getContactNumber(final String name
) {
625 // Contact names have precedence.
626 var numbers
= new ArrayList
<String
>();
627 var contacts
= m
.getContacts();
628 for (var c
: contacts
) {
629 if (name
.equals(c
.second().getName())) {
630 numbers
.add(c
.first().getLegacyIdentifier());
633 // Try profiles if no contact name was found
634 for (var identity
: m
.getIdentities()) {
635 final var address
= identity
.recipient();
636 var number
= address
.getNumber().orElse(null);
637 if (number
!= null) {
638 Profile profile
= null;
640 profile
= m
.getRecipientProfile(RecipientIdentifier
.Single
.fromAddress(address
));
641 } catch (IOException ignored
) {
643 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
652 public void quitGroup(final byte[] groupId
) {
653 var group
= getGroupId(groupId
);
655 m
.quitGroup(group
, Set
.of());
656 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
657 throw new Error
.GroupNotFound(e
.getMessage());
658 } catch (IOException
| LastGroupAdminException e
) {
659 throw new Error
.Failure(e
.getMessage());
664 public byte[] joinGroup(final String groupLink
) {
666 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
667 if (linkUrl
== null) {
668 throw new Error
.Failure("Group link is invalid:");
670 final var result
= m
.joinGroup(linkUrl
);
671 return result
.first().serialize();
672 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| InactiveGroupLinkException e
) {
673 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
674 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
675 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
676 } catch (IOException e
) {
677 throw new Error
.Failure(e
.getMessage());
682 public boolean isContactBlocked(final String number
) {
683 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getSelfNumber()));
687 public boolean isGroupBlocked(final byte[] groupId
) {
688 var group
= m
.getGroup(getGroupId(groupId
));
692 return group
.isBlocked();
697 public boolean isMember(final byte[] groupId
) {
698 var group
= m
.getGroup(getGroupId(groupId
));
702 return group
.isMember();
707 public String
uploadStickerPack(String stickerPackPath
) {
708 File path
= new File(stickerPackPath
);
710 return m
.uploadStickerPack(path
).toString();
711 } catch (IOException e
) {
712 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
713 } catch (StickerPackInvalidException e
) {
714 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
718 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
719 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
725 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
727 if (result
.getIdentityFailure() != null) {
728 throw new Error
.UntrustedIdentity(message
);
730 throw new Error
.Failure(message
);
734 private static void checkSendMessageResults(
735 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
736 ) throws DBusExecutionException
{
737 final var sendMessageResults
= results
.values().stream().findFirst();
738 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
739 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
743 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
744 if (errors
.size() == 0) {
748 var message
= new StringBuilder();
749 message
.append(timestamp
).append('\n');
750 message
.append("Failed to send (some) messages:\n");
751 for (var error
: errors
) {
752 message
.append(error
).append('\n');
755 throw new Error
.Failure(message
.toString());
758 private static void checkSendMessageResults(
759 long timestamp
, Collection
<SendMessageResult
> results
760 ) throws DBusExecutionException
{
761 if (results
.size() == 1) {
762 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
766 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
767 if (errors
.size() == 0) {
771 var message
= new StringBuilder();
772 message
.append(timestamp
).append('\n');
773 message
.append("Failed to send (some) messages:\n");
774 for (var error
: errors
) {
775 message
.append(error
).append('\n');
778 throw new Error
.Failure(message
.toString());
781 private static List
<String
> getRecipientStrings(final Set
<RecipientAddress
> members
) {
782 return members
.stream().map(RecipientAddress
::getLegacyIdentifier
).collect(Collectors
.toList());
785 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
786 final Collection
<String
> recipientStrings
, final String localNumber
787 ) throws DBusExecutionException
{
788 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
789 for (var recipientString
: recipientStrings
) {
790 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
795 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
796 final String recipientString
, final String localNumber
797 ) throws DBusExecutionException
{
799 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
800 } catch (InvalidNumberException e
) {
801 throw new Error
.InvalidNumber(e
.getMessage());
805 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
807 return GroupId
.unknownVersion(groupId
);
808 } catch (Throwable e
) {
809 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());
813 private byte[] nullIfEmpty(final byte[] array
) {
814 return array
.length
== 0 ?
null : array
;
817 private String
nullIfEmpty(final String name
) {
818 return name
.isEmpty() ?
null : name
;
821 private String
emptyIfNull(final String string
) {
822 return string
== null ?
"" : string
;
825 private static String
getDeviceObjectPath(String basePath
, long deviceId
) {
826 return basePath
+ "/Devices/" + deviceId
;
829 private void updateDevices() {
830 List
<org
.asamk
.signal
.manager
.api
.Device
> linkedDevices
;
832 linkedDevices
= m
.getLinkedDevices();
833 } catch (IOException e
) {
834 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
839 linkedDevices
.forEach(d
-> {
840 final var object
= new DbusSignalDeviceImpl(d
);
841 final var deviceObjectPath
= object
.getObjectPath();
843 connection
.exportObject(object
);
844 } catch (DBusException e
) {
847 if (d
.isThisDevice()) {
848 thisDevice
= new DBusPath(deviceObjectPath
);
850 this.devices
.add(new StructDevice(new DBusPath(deviceObjectPath
), d
.id(), emptyIfNull(d
.name())));
854 private void unExportDevices() {
855 this.devices
.stream()
856 .map(StructDevice
::getObjectPath
)
857 .map(DBusPath
::getPath
)
858 .forEach(connection
::unExportObject
);
859 this.devices
.clear();
862 private static String
getGroupObjectPath(String basePath
, byte[] groupId
) {
863 return basePath
+ "/Groups/" + Base64
.getEncoder()
864 .encodeToString(groupId
)
870 private void updateGroups() {
871 List
<org
.asamk
.signal
.manager
.api
.Group
> groups
;
872 groups
= m
.getGroups();
876 groups
.forEach(g
-> {
877 final var object
= new DbusSignalGroupImpl(g
.groupId());
879 connection
.exportObject(object
);
880 } catch (DBusException e
) {
883 this.groups
.add(new StructGroup(new DBusPath(object
.getObjectPath()),
884 g
.groupId().serialize(),
885 emptyIfNull(g
.title())));
889 private void unExportGroups() {
890 this.groups
.stream().map(StructGroup
::getObjectPath
).map(DBusPath
::getPath
).forEach(connection
::unExportObject
);
894 public class DbusSignalDeviceImpl
extends DbusProperties
implements Signal
.Device
{
896 private final org
.asamk
.signal
.manager
.api
.Device device
;
898 public DbusSignalDeviceImpl(final org
.asamk
.signal
.manager
.api
.Device device
) {
899 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Device",
900 List
.of(new DbusProperty
<>("Id", device
::id
),
901 new DbusProperty
<>("Name", () -> emptyIfNull(device
.name()), this::setDeviceName
),
902 new DbusProperty
<>("Created", device
::created
),
903 new DbusProperty
<>("LastSeen", device
::lastSeen
))));
904 this.device
= device
;
908 public String
getObjectPath() {
909 return getDeviceObjectPath(objectPath
, device
.id());
913 public void removeDevice() throws Error
.Failure
{
915 m
.removeLinkedDevices(device
.id());
917 } catch (IOException e
) {
918 throw new Error
.Failure(e
.getMessage());
922 private void setDeviceName(String name
) {
923 if (!device
.isThisDevice()) {
924 throw new Error
.Failure("Only the name of this device can be changed");
927 m
.updateAccountAttributes(name
);
928 // update device list
930 } catch (IOException e
) {
931 throw new Error
.Failure(e
.getMessage());
936 public class DbusSignalGroupImpl
extends DbusProperties
implements Signal
.Group
{
938 private final GroupId groupId
;
940 public DbusSignalGroupImpl(final GroupId groupId
) {
941 this.groupId
= groupId
;
942 super.addPropertiesHandler(new DbusInterfacePropertiesHandler("org.asamk.Signal.Group",
943 List
.of(new DbusProperty
<>("Id", groupId
::serialize
),
944 new DbusProperty
<>("Name", () -> emptyIfNull(getGroup().title()), this::setGroupName
),
945 new DbusProperty
<>("Description",
946 () -> emptyIfNull(getGroup().description()),
947 this::setGroupDescription
),
948 new DbusProperty
<>("Avatar", this::setGroupAvatar
),
949 new DbusProperty
<>("IsBlocked", () -> getGroup().isBlocked(), this::setIsBlocked
),
950 new DbusProperty
<>("IsMember", () -> getGroup().isMember()),
951 new DbusProperty
<>("IsAdmin", () -> getGroup().isAdmin()),
952 new DbusProperty
<>("MessageExpirationTimer",
953 () -> getGroup().messageExpirationTimer(),
954 this::setMessageExpirationTime
),
955 new DbusProperty
<>("Members",
956 () -> new Variant
<>(getRecipientStrings(getGroup().members()), "as")),
957 new DbusProperty
<>("PendingMembers",
958 () -> new Variant
<>(getRecipientStrings(getGroup().pendingMembers()), "as")),
959 new DbusProperty
<>("RequestingMembers",
960 () -> new Variant
<>(getRecipientStrings(getGroup().requestingMembers()), "as")),
961 new DbusProperty
<>("Admins",
962 () -> new Variant
<>(getRecipientStrings(getGroup().adminMembers()), "as")),
963 new DbusProperty
<>("PermissionAddMember",
964 () -> getGroup().permissionAddMember().name(),
965 this::setGroupPermissionAddMember
),
966 new DbusProperty
<>("PermissionEditDetails",
967 () -> getGroup().permissionEditDetails().name(),
968 this::setGroupPermissionEditDetails
),
969 new DbusProperty
<>("PermissionSendMessage",
970 () -> getGroup().permissionSendMessage().name(),
971 this::setGroupPermissionSendMessage
),
972 new DbusProperty
<>("GroupInviteLink", () -> {
973 final var groupInviteLinkUrl
= getGroup().groupInviteLinkUrl();
974 return groupInviteLinkUrl
== null ?
"" : groupInviteLinkUrl
.getUrl();
979 public String
getObjectPath() {
980 return getGroupObjectPath(objectPath
, groupId
.serialize());
984 public void quitGroup() throws Error
.Failure
{
986 m
.quitGroup(groupId
, Set
.of());
987 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
988 throw new Error
.GroupNotFound(e
.getMessage());
989 } catch (IOException e
) {
990 throw new Error
.Failure(e
.getMessage());
991 } catch (LastGroupAdminException e
) {
992 throw new Error
.LastGroupAdmin(e
.getMessage());
997 public void addMembers(final List
<String
> recipients
) throws Error
.Failure
{
998 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
999 updateGroup(UpdateGroup
.newBuilder().withMembers(memberIdentifiers
).build());
1003 public void removeMembers(final List
<String
> recipients
) throws Error
.Failure
{
1004 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1005 updateGroup(UpdateGroup
.newBuilder().withRemoveMembers(memberIdentifiers
).build());
1009 public void addAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1010 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1011 updateGroup(UpdateGroup
.newBuilder().withAdmins(memberIdentifiers
).build());
1015 public void removeAdmins(final List
<String
> recipients
) throws Error
.Failure
{
1016 final var memberIdentifiers
= getSingleRecipientIdentifiers(recipients
, m
.getSelfNumber());
1017 updateGroup(UpdateGroup
.newBuilder().withRemoveAdmins(memberIdentifiers
).build());
1021 public void resetLink() throws Error
.Failure
{
1022 updateGroup(UpdateGroup
.newBuilder().withResetGroupLink(true).build());
1026 public void disableLink() throws Error
.Failure
{
1027 updateGroup(UpdateGroup
.newBuilder().withGroupLinkState(GroupLinkState
.DISABLED
).build());
1031 public void enableLink(final boolean requiresApproval
) throws Error
.Failure
{
1032 updateGroup(UpdateGroup
.newBuilder()
1033 .withGroupLinkState(requiresApproval
1034 ? GroupLinkState
.ENABLED_WITH_APPROVAL
1035 : GroupLinkState
.ENABLED
)
1039 private org
.asamk
.signal
.manager
.api
.Group
getGroup() {
1040 return m
.getGroup(groupId
);
1043 private void setGroupName(final String name
) {
1044 updateGroup(UpdateGroup
.newBuilder().withName(name
).build());
1047 private void setGroupDescription(final String description
) {
1048 updateGroup(UpdateGroup
.newBuilder().withDescription(description
).build());
1051 private void setGroupAvatar(final String avatar
) {
1052 updateGroup(UpdateGroup
.newBuilder().withAvatarFile(new File(avatar
)).build());
1055 private void setMessageExpirationTime(final int expirationTime
) {
1056 updateGroup(UpdateGroup
.newBuilder().withExpirationTimer(expirationTime
).build());
1059 private void setGroupPermissionAddMember(final String permission
) {
1060 updateGroup(UpdateGroup
.newBuilder().withAddMemberPermission(GroupPermission
.valueOf(permission
)).build());
1063 private void setGroupPermissionEditDetails(final String permission
) {
1064 updateGroup(UpdateGroup
.newBuilder()
1065 .withEditDetailsPermission(GroupPermission
.valueOf(permission
))
1069 private void setGroupPermissionSendMessage(final String permission
) {
1070 updateGroup(UpdateGroup
.newBuilder()
1071 .withIsAnnouncementGroup(GroupPermission
.valueOf(permission
) == GroupPermission
.ONLY_ADMINS
)
1075 private void setIsBlocked(final boolean isBlocked
) {
1077 m
.setGroupBlocked(groupId
, isBlocked
);
1078 } catch (NotMasterDeviceException e
) {
1079 throw new Error
.Failure("This command doesn't work on linked devices.");
1080 } catch (GroupNotFoundException e
) {
1081 throw new Error
.GroupNotFound(e
.getMessage());
1082 } catch (IOException e
) {
1083 throw new Error
.Failure(e
.getMessage());
1087 private void updateGroup(final UpdateGroup updateGroup
) {
1089 m
.updateGroup(groupId
, updateGroup
);
1090 } catch (IOException e
) {
1091 throw new Error
.Failure(e
.getMessage());
1092 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
1093 throw new Error
.GroupNotFound(e
.getMessage());
1094 } catch (AttachmentInvalidException e
) {
1095 throw new Error
.AttachmentInvalid(e
.getMessage());