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
.Device
;
11 import org
.asamk
.signal
.manager
.api
.Message
;
12 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
13 import org
.asamk
.signal
.manager
.api
.TypingAction
;
14 import org
.asamk
.signal
.manager
.groups
.GroupId
;
15 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
16 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
17 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
18 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
19 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
20 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
21 import org
.asamk
.signal
.util
.ErrorUtils
;
22 import org
.asamk
.signal
.util
.Util
;
23 import org
.freedesktop
.dbus
.exceptions
.DBusExecutionException
;
24 import org
.whispersystems
.libsignal
.InvalidKeyException
;
25 import org
.whispersystems
.libsignal
.util
.Pair
;
26 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
27 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
28 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
29 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
30 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
31 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
34 import java
.io
.IOException
;
36 import java
.net
.URISyntaxException
;
37 import java
.util
.ArrayList
;
38 import java
.util
.Collection
;
39 import java
.util
.HashSet
;
40 import java
.util
.List
;
42 import java
.util
.Objects
;
44 import java
.util
.UUID
;
45 import java
.util
.stream
.Collectors
;
46 import java
.util
.stream
.Stream
;
48 import static org
.asamk
.signal
.util
.Util
.getLegacyIdentifier
;
50 public class DbusSignalImpl
implements Signal
{
52 private final Manager m
;
53 private final String objectPath
;
55 public DbusSignalImpl(final Manager m
, final String objectPath
) {
57 this.objectPath
= objectPath
;
61 public boolean isRemote() {
66 public String
getObjectPath() {
71 public void addDevice(String uri
) {
73 m
.addDeviceLink(new URI(uri
));
74 } catch (IOException
| InvalidKeyException e
) {
75 throw new Error
.Failure(e
.getClass().getSimpleName() + " Add device link failed. " + e
.getMessage());
76 } catch (URISyntaxException e
) {
77 throw new Error
.InvalidUri(e
.getClass().getSimpleName()
78 + " Device link uri has invalid format: "
84 public void removeDevice(int deviceId
) {
86 m
.removeLinkedDevices(deviceId
);
87 } catch (IOException e
) {
88 throw new Error
.Failure(e
.getClass().getSimpleName() + ": Error while removing device: " + e
.getMessage());
93 public List
<String
> listDevices() {
95 List
<String
> results
= new ArrayList
<String
>();
98 devices
= m
.getLinkedDevices();
99 } catch (IOException
| Error
.Failure e
) {
100 throw new Error
.Failure("Failed to get linked devices: " + e
.getMessage());
103 return devices
.stream().map(d
-> d
.getName() == null ?
"" : d
.getName()).collect(Collectors
.toList());
107 public void updateDeviceName(String deviceName
) {
109 m
.updateAccountAttributes(deviceName
);
110 } catch (IOException
| Signal
.Error
.Failure e
) {
111 throw new Error
.Failure("UpdateAccount error: " + e
.getMessage());
116 public long sendMessage(final String message
, final List
<String
> attachments
, final String recipient
) {
117 var recipients
= new ArrayList
<String
>(1);
118 recipients
.add(recipient
);
119 return sendMessage(message
, attachments
, recipients
);
123 public long sendMessage(final String message
, final List
<String
> attachments
, final List
<String
> recipients
) {
125 final var results
= m
.sendMessage(new Message(message
, attachments
),
126 getSingleRecipientIdentifiers(recipients
, m
.getUsername()).stream()
127 .map(RecipientIdentifier
.class::cast
)
128 .collect(Collectors
.toSet()));
130 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
131 return results
.getTimestamp();
132 } catch (AttachmentInvalidException e
) {
133 throw new Error
.AttachmentInvalid(e
.getMessage());
134 } catch (IOException e
) {
135 throw new Error
.Failure(e
.getMessage());
136 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
137 throw new Error
.GroupNotFound(e
.getMessage());
142 public long sendRemoteDeleteMessage(
143 final long targetSentTimestamp
, final String recipient
145 var recipients
= new ArrayList
<String
>(1);
146 recipients
.add(recipient
);
147 return sendRemoteDeleteMessage(targetSentTimestamp
, recipients
);
151 public long sendRemoteDeleteMessage(
152 final long targetSentTimestamp
, final List
<String
> recipients
155 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
156 getSingleRecipientIdentifiers(recipients
, m
.getUsername()).stream()
157 .map(RecipientIdentifier
.class::cast
)
158 .collect(Collectors
.toSet()));
159 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
160 return results
.getTimestamp();
161 } catch (IOException e
) {
162 throw new Error
.Failure(e
.getMessage());
163 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
164 throw new Error
.GroupNotFound(e
.getMessage());
169 public long sendGroupRemoteDeleteMessage(
170 final long targetSentTimestamp
, final byte[] groupId
173 final var results
= m
.sendRemoteDeleteMessage(targetSentTimestamp
,
174 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
175 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
176 return results
.getTimestamp();
177 } catch (IOException e
) {
178 throw new Error
.Failure(e
.getMessage());
179 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
180 throw new Error
.GroupNotFound(e
.getMessage());
185 public long sendMessageReaction(
187 final boolean remove
,
188 final String targetAuthor
,
189 final long targetSentTimestamp
,
190 final String recipient
192 var recipients
= new ArrayList
<String
>(1);
193 recipients
.add(recipient
);
194 return sendMessageReaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
, recipients
);
198 public long sendMessageReaction(
200 final boolean remove
,
201 final String targetAuthor
,
202 final long targetSentTimestamp
,
203 final List
<String
> recipients
206 final var results
= m
.sendMessageReaction(emoji
,
208 getSingleRecipientIdentifier(targetAuthor
, m
.getUsername()),
210 getSingleRecipientIdentifiers(recipients
, m
.getUsername()).stream()
211 .map(RecipientIdentifier
.class::cast
)
212 .collect(Collectors
.toSet()));
213 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
214 return results
.getTimestamp();
215 } catch (IOException e
) {
216 throw new Error
.Failure(e
.getMessage());
217 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
218 throw new Error
.GroupNotFound(e
.getMessage());
223 public void sendTyping(
224 final String recipient
, final boolean stop
225 ) throws Error
.Failure
, Error
.GroupNotFound
, Error
.UntrustedIdentity
{
227 var recipients
= new ArrayList
<String
>(1);
228 recipients
.add(recipient
);
229 m
.sendTypingMessage(stop ? TypingAction
.STOP
: TypingAction
.START
,
230 getSingleRecipientIdentifiers(recipients
, m
.getUsername()).stream()
231 .map(RecipientIdentifier
.class::cast
)
232 .collect(Collectors
.toSet()));
233 } catch (IOException e
) {
234 throw new Error
.Failure(e
.getMessage());
235 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
236 throw new Error
.GroupNotFound(e
.getMessage());
237 } catch (UntrustedIdentityException e
) {
238 throw new Error
.UntrustedIdentity(e
.getMessage());
243 public void sendReadReceipt(
244 final String recipient
, final List
<Long
> timestamps
245 ) throws Error
.Failure
, Error
.UntrustedIdentity
{
247 m
.sendReadReceipt(getSingleRecipientIdentifier(recipient
, m
.getUsername()), timestamps
);
248 } catch (IOException e
) {
249 throw new Error
.Failure(e
.getMessage());
250 } catch (UntrustedIdentityException e
) {
251 throw new Error
.UntrustedIdentity(e
.getMessage());
256 public void sendContacts() {
259 } catch (IOException e
) {
260 throw new Error
.Failure("SendContacts error: " + e
.getMessage());
265 public void sendSyncRequest() {
267 m
.requestAllSyncData();
268 } catch (IOException e
) {
269 throw new Error
.Failure("Request sync data error: " + e
.getMessage());
274 public long sendNoteToSelfMessage(
275 final String message
, final List
<String
> attachments
276 ) throws Error
.AttachmentInvalid
, Error
.Failure
, Error
.UntrustedIdentity
{
278 final var results
= m
.sendMessage(new Message(message
, attachments
),
279 Set
.of(new RecipientIdentifier
.NoteToSelf()));
280 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
281 return results
.getTimestamp();
282 } catch (AttachmentInvalidException e
) {
283 throw new Error
.AttachmentInvalid(e
.getMessage());
284 } catch (IOException e
) {
285 throw new Error
.Failure(e
.getMessage());
286 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
287 throw new Error
.GroupNotFound(e
.getMessage());
292 public void sendEndSessionMessage(final List
<String
> recipients
) {
294 final var results
= m
.sendEndSessionMessage(getSingleRecipientIdentifiers(recipients
, m
.getUsername()));
295 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
296 } catch (IOException e
) {
297 throw new Error
.Failure(e
.getMessage());
302 public long sendGroupMessage(final String message
, final List
<String
> attachments
, final byte[] groupId
) {
304 var results
= m
.sendMessage(new Message(message
, attachments
),
305 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
306 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
307 return results
.getTimestamp();
308 } catch (IOException e
) {
309 throw new Error
.Failure(e
.getMessage());
310 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
311 throw new Error
.GroupNotFound(e
.getMessage());
312 } catch (AttachmentInvalidException e
) {
313 throw new Error
.AttachmentInvalid(e
.getMessage());
318 public long sendGroupMessageReaction(
320 final boolean remove
,
321 final String targetAuthor
,
322 final long targetSentTimestamp
,
326 final var results
= m
.sendMessageReaction(emoji
,
328 getSingleRecipientIdentifier(targetAuthor
, m
.getUsername()),
330 Set
.of(new RecipientIdentifier
.Group(getGroupId(groupId
))));
331 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
332 return results
.getTimestamp();
333 } catch (IOException e
) {
334 throw new Error
.Failure(e
.getMessage());
335 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
336 throw new Error
.GroupNotFound(e
.getMessage());
340 // Since contact names might be empty if not defined, also potentially return
343 public String
getContactName(final String number
) {
344 return m
.getContactOrProfileName(getSingleRecipientIdentifier(number
, m
.getUsername()));
348 public void setContactName(final String number
, final String name
) {
350 m
.setContactName(getSingleRecipientIdentifier(number
, m
.getUsername()), name
);
351 } catch (NotMasterDeviceException e
) {
352 throw new Error
.Failure("This command doesn't work on linked devices.");
353 } catch (UnregisteredUserException e
) {
354 throw new Error
.Failure("Contact is not registered.");
359 public void setExpirationTimer(final String number
, final int expiration
) {
361 m
.setExpirationTimer(getSingleRecipientIdentifier(number
, m
.getUsername()), expiration
);
362 } catch (IOException e
) {
363 throw new Error
.Failure(e
.getMessage());
368 public void setContactBlocked(final String number
, final boolean blocked
) {
370 m
.setContactBlocked(getSingleRecipientIdentifier(number
, m
.getUsername()), blocked
);
371 } catch (NotMasterDeviceException e
) {
372 throw new Error
.Failure("This command doesn't work on linked devices.");
373 } catch (IOException e
) {
374 throw new Error
.Failure(e
.getMessage());
379 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) {
381 m
.setGroupBlocked(getGroupId(groupId
), blocked
);
382 } catch (GroupNotFoundException e
) {
383 throw new Error
.GroupNotFound(e
.getMessage());
384 } catch (IOException e
) {
385 throw new Error
.Failure(e
.getMessage());
390 public List
<byte[]> getGroupIds() {
391 var groups
= m
.getGroups();
392 var ids
= new ArrayList
<byte[]>(groups
.size());
393 for (var group
: groups
) {
394 ids
.add(group
.getGroupId().serialize());
400 public String
getGroupName(final byte[] groupId
) {
401 var group
= m
.getGroup(getGroupId(groupId
));
405 return group
.getTitle();
410 public List
<String
> getGroupMembers(final byte[] groupId
) {
411 var group
= m
.getGroup(getGroupId(groupId
));
415 return group
.getMembers()
417 .map(m
::resolveSignalServiceAddress
)
418 .map(Util
::getLegacyIdentifier
)
419 .collect(Collectors
.toList());
424 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) {
426 if (groupId
.length
== 0) {
429 if (name
.isEmpty()) {
432 if (avatar
.isEmpty()) {
435 final var memberIdentifiers
= getSingleRecipientIdentifiers(members
, m
.getUsername());
436 if (groupId
== null) {
437 final var results
= m
.createGroup(name
, memberIdentifiers
, avatar
== null ?
null : new File(avatar
));
438 checkSendMessageResults(results
.second().getTimestamp(), results
.second().getResults());
439 return results
.first().serialize();
441 final var results
= m
.updateGroup(getGroupId(groupId
),
452 avatar
== null ?
null : new File(avatar
),
455 if (results
!= null) {
456 checkSendMessageResults(results
.getTimestamp(), results
.getResults());
460 } catch (IOException e
) {
461 throw new Error
.Failure(e
.getMessage());
462 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
463 throw new Error
.GroupNotFound(e
.getMessage());
464 } catch (AttachmentInvalidException e
) {
465 throw new Error
.AttachmentInvalid(e
.getMessage());
470 public boolean isRegistered() {
471 var result
= isRegistered(List
.of(m
.getUsername()));
472 return result
.get(0);
476 public boolean isRegistered(String number
) {
477 var result
= isRegistered(List
.of(number
));
478 return result
.get(0);
482 public List
<Boolean
> isRegistered(List
<String
> numbers
) {
483 var results
= new ArrayList
<Boolean
> ();
484 Map
<String
, Pair
<String
, UUID
>> registered
;
485 if (numbers
.isEmpty()) {
489 registered
= m
.areUsersRegistered(new HashSet
<String
>(numbers
));
490 } catch (IOException e
) {
491 throw new Error
.Failure(e
.getMessage());
493 for (String number
: numbers
) {
494 UUID uuid
= registered
.get(number
).second();
495 results
.add(uuid
!= null);
501 public void updateProfile(
504 final String aboutEmoji
,
506 final boolean removeAvatar
509 if (avatarPath
.isEmpty()) {
512 Optional
<File
> avatarFile
= removeAvatar
514 : avatarPath
== null ?
null : Optional
.of(new File(avatarPath
));
515 m
.setProfile(name
, null, about
, aboutEmoji
, avatarFile
);
516 } catch (IOException e
) {
517 throw new Error
.Failure(e
.getMessage());
522 public void removePin() {
524 m
.setRegistrationLockPin(Optional
.absent());
525 } catch (UnauthenticatedResponseException e
) {
526 throw new Error
.Failure("Remove pin failed with unauthenticated response: " + e
.getMessage());
527 } catch (IOException e
) {
528 throw new Error
.Failure("Remove pin error: " + e
.getMessage());
533 public void setPin(String registrationLockPin
) {
535 m
.setRegistrationLockPin(Optional
.of(registrationLockPin
));
536 } catch (UnauthenticatedResponseException e
) {
537 throw new Error
.Failure("Set pin error failed with unauthenticated response: " + e
.getMessage());
538 } catch (IOException e
) {
539 throw new Error
.Failure("Set pin error: " + e
.getMessage());
543 // Provide option to query a version string in order to react on potential
544 // future interface changes
546 public String
version() {
547 return BaseConfig
.PROJECT_VERSION
;
550 // Create a unique list of Numbers from Identities and Contacts to really get
551 // all numbers the system knows
553 public List
<String
> listNumbers() {
554 return Stream
.concat(m
.getIdentities().stream().map(IdentityInfo
::getRecipientId
),
555 m
.getContacts().stream().map(Pair
::first
))
556 .map(m
::resolveSignalServiceAddress
)
557 .map(a
-> a
.getNumber().orNull())
558 .filter(Objects
::nonNull
)
560 .collect(Collectors
.toList());
564 public List
<String
> getContactNumber(final String name
) {
565 // Contact names have precedence.
566 var numbers
= new ArrayList
<String
>();
567 var contacts
= m
.getContacts();
568 for (var c
: contacts
) {
569 if (name
.equals(c
.second().getName())) {
570 numbers
.add(getLegacyIdentifier(m
.resolveSignalServiceAddress(c
.first())));
573 // Try profiles if no contact name was found
574 for (var identity
: m
.getIdentities()) {
575 final var recipientId
= identity
.getRecipientId();
576 final var address
= m
.resolveSignalServiceAddress(recipientId
);
577 var number
= address
.getNumber().orNull();
578 if (number
!= null) {
579 var profile
= m
.getRecipientProfile(recipientId
);
580 if (profile
!= null && profile
.getDisplayName().equals(name
)) {
589 public void quitGroup(final byte[] groupId
) {
590 var group
= getGroupId(groupId
);
592 m
.quitGroup(group
, Set
.of());
593 } catch (GroupNotFoundException
| NotAGroupMemberException e
) {
594 throw new Error
.GroupNotFound(e
.getMessage());
595 } catch (IOException
| LastGroupAdminException e
) {
596 throw new Error
.Failure(e
.getMessage());
601 public byte[] joinGroup(final String groupLink
) {
603 final var linkUrl
= GroupInviteLinkUrl
.fromUri(groupLink
);
604 if (linkUrl
== null) {
605 throw new Error
.Failure("Group link is invalid:");
607 final var result
= m
.joinGroup(linkUrl
);
608 return result
.first().serialize();
609 } catch (GroupInviteLinkUrl
.InvalidGroupLinkException
| GroupLinkNotActiveException e
) {
610 throw new Error
.Failure("Group link is invalid: " + e
.getMessage());
611 } catch (GroupInviteLinkUrl
.UnknownGroupLinkVersionException e
) {
612 throw new Error
.Failure("Group link was created with an incompatible version: " + e
.getMessage());
613 } catch (IOException e
) {
614 throw new Error
.Failure(e
.getMessage());
619 public boolean isContactBlocked(final String number
) {
620 return m
.isContactBlocked(getSingleRecipientIdentifier(number
, m
.getUsername()));
624 public boolean isGroupBlocked(final byte[] groupId
) {
625 var group
= m
.getGroup(getGroupId(groupId
));
629 return group
.isBlocked();
634 public boolean isMember(final byte[] groupId
) {
635 var group
= m
.getGroup(getGroupId(groupId
));
639 return group
.isMember(m
.getSelfRecipientId());
644 public String
uploadStickerPack(String stickerPackPath
) {
645 File path
= new File(stickerPackPath
);
647 return m
.uploadStickerPack(path
).toString();
648 } catch (IOException e
) {
649 throw new Error
.Failure("Upload error (maybe image size is too large):" + e
.getMessage());
650 } catch (StickerPackInvalidException e
) {
651 throw new Error
.Failure("Invalid sticker pack: " + e
.getMessage());
655 private static void checkSendMessageResult(long timestamp
, SendMessageResult result
) throws DBusExecutionException
{
656 var error
= ErrorUtils
.getErrorMessageFromSendMessageResult(result
);
662 final var message
= timestamp
+ "\nFailed to send message:\n" + error
+ '\n';
664 if (result
.getIdentityFailure() != null) {
665 throw new Error
.UntrustedIdentity(message
);
667 throw new Error
.Failure(message
);
671 private static void checkSendMessageResults(
672 long timestamp
, Map
<RecipientIdentifier
, List
<SendMessageResult
>> results
673 ) throws DBusExecutionException
{
674 final var sendMessageResults
= results
.values().stream().findFirst();
675 if (results
.size() == 1 && sendMessageResults
.get().size() == 1) {
676 checkSendMessageResult(timestamp
, sendMessageResults
.get().stream().findFirst().get());
680 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
681 if (errors
.size() == 0) {
685 var message
= new StringBuilder();
686 message
.append(timestamp
).append('\n');
687 message
.append("Failed to send (some) messages:\n");
688 for (var error
: errors
) {
689 message
.append(error
).append('\n');
692 throw new Error
.Failure(message
.toString());
695 private static void checkSendMessageResults(
696 long timestamp
, Collection
<SendMessageResult
> results
697 ) throws DBusExecutionException
{
698 if (results
.size() == 1) {
699 checkSendMessageResult(timestamp
, results
.stream().findFirst().get());
703 var errors
= ErrorUtils
.getErrorMessagesFromSendMessageResults(results
);
704 if (errors
.size() == 0) {
708 var message
= new StringBuilder();
709 message
.append(timestamp
).append('\n');
710 message
.append("Failed to send (some) messages:\n");
711 for (var error
: errors
) {
712 message
.append(error
).append('\n');
715 throw new Error
.Failure(message
.toString());
718 private static Set
<RecipientIdentifier
.Single
> getSingleRecipientIdentifiers(
719 final Collection
<String
> recipientStrings
, final String localNumber
720 ) throws DBusExecutionException
{
721 final var identifiers
= new HashSet
<RecipientIdentifier
.Single
>();
722 for (var recipientString
: recipientStrings
) {
723 identifiers
.add(getSingleRecipientIdentifier(recipientString
, localNumber
));
728 private static RecipientIdentifier
.Single
getSingleRecipientIdentifier(
729 final String recipientString
, final String localNumber
730 ) throws DBusExecutionException
{
732 return RecipientIdentifier
.Single
.fromString(recipientString
, localNumber
);
733 } catch (InvalidNumberException e
) {
734 throw new Error
.InvalidNumber(e
.getMessage());
738 private static GroupId
getGroupId(byte[] groupId
) throws DBusExecutionException
{
740 return GroupId
.unknownVersion(groupId
);
741 } catch (Throwable e
) {
742 throw new Error
.InvalidGroupId("Invalid group id: " + e
.getMessage());