1 package org
.asamk
.signal
.commands
;
3 import net
.sourceforge
.argparse4j
.impl
.Arguments
;
4 import net
.sourceforge
.argparse4j
.inf
.Namespace
;
5 import net
.sourceforge
.argparse4j
.inf
.Subparser
;
7 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
8 import org
.asamk
.signal
.commands
.exceptions
.UnexpectedErrorException
;
9 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
10 import org
.asamk
.signal
.manager
.Manager
;
11 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
12 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
13 import org
.asamk
.signal
.manager
.api
.Message
;
14 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
15 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
16 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
17 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
18 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
19 import org
.asamk
.signal
.output
.OutputWriter
;
20 import org
.asamk
.signal
.util
.CommandUtil
;
21 import org
.asamk
.signal
.util
.Hex
;
22 import org
.asamk
.signal
.util
.IOUtils
;
23 import org
.slf4j
.Logger
;
24 import org
.slf4j
.LoggerFactory
;
26 import java
.io
.IOException
;
27 import java
.util
.ArrayList
;
28 import java
.util
.List
;
29 import java
.util
.Optional
;
30 import java
.util
.regex
.Pattern
;
31 import java
.util
.stream
.Collectors
;
33 import static org
.asamk
.signal
.util
.SendMessageResultUtils
.outputResult
;
35 public class SendCommand
implements JsonRpcLocalCommand
{
37 private final static Logger logger
= LoggerFactory
.getLogger(SendCommand
.class);
40 public String
getName() {
45 public void attachToSubparser(final Subparser subparser
) {
46 subparser
.help("Send a message to another user or group.");
47 subparser
.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
48 subparser
.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.").nargs("*");
49 subparser
.addArgument("--note-to-self")
50 .help("Send the message to self without notification.")
51 .action(Arguments
.storeTrue());
53 var mut
= subparser
.addMutuallyExclusiveGroup();
54 mut
.addArgument("-m", "--message").help("Specify the message to be sent.");
55 mut
.addArgument("--message-from-stdin")
56 .action(Arguments
.storeTrue())
57 .help("Read the message from standard input.");
58 subparser
.addArgument("-a", "--attachment").nargs("*").help("Add an attachment. "
59 + "Can be either a file path or a data URI. Data URI encoded attachments must follow the RFC 2397. Additionally a file name can be added, e.g. "
60 + "data:<MIME-TYPE>;filename=<FILENAME>;base64,<BASE64 ENCODED DATA>.");
61 subparser
.addArgument("-e", "--end-session", "--endsession")
62 .help("Clear session state and send end session message.")
63 .action(Arguments
.storeTrue());
64 subparser
.addArgument("--mention")
66 .help("Mention another group member (syntax: start:length:recipientNumber)");
67 subparser
.addArgument("--quote-timestamp")
69 .help("Specify the timestamp of a previous message with the recipient or group to add a quote to the new message.");
70 subparser
.addArgument("--quote-author").help("Specify the number of the author of the original message.");
71 subparser
.addArgument("--quote-message").help("Specify the message of the original message.");
72 subparser
.addArgument("--quote-mention")
74 .help("Quote with mention of another group member (syntax: start:length:recipientNumber)");
75 subparser
.addArgument("--sticker").help("Send a sticker (syntax: stickerPackId:stickerId)");
76 subparser
.addArgument("--preview-url")
77 .help("Specify the url for the link preview (the same url must also appear in the message body).");
78 subparser
.addArgument("--preview-title").help("Specify the title for the link preview (mandatory).");
79 subparser
.addArgument("--preview-description").help("Specify the description for the link preview (optional).");
80 subparser
.addArgument("--preview-image").help("Specify the image file for the link preview (optional).");
84 public void handleCommand(
85 final Namespace ns
, final Manager m
, final OutputWriter outputWriter
86 ) throws CommandException
{
87 final var isNoteToSelf
= Boolean
.TRUE
.equals(ns
.getBoolean("note-to-self"));
88 final var recipientStrings
= ns
.<String
>getList("recipient");
89 final var groupIdStrings
= ns
.<String
>getList("group-id");
91 final var recipientIdentifiers
= CommandUtil
.getRecipientIdentifiers(m
,
96 final var isEndSession
= Boolean
.TRUE
.equals(ns
.getBoolean("end-session"));
98 final var singleRecipients
= recipientIdentifiers
.stream()
99 .filter(r
-> r
instanceof RecipientIdentifier
.Single
)
100 .map(RecipientIdentifier
.Single
.class::cast
)
101 .collect(Collectors
.toSet());
102 if (singleRecipients
.isEmpty()) {
103 throw new UserErrorException("No recipients given");
107 final var results
= m
.sendEndSessionMessage(singleRecipients
);
108 outputResult(outputWriter
, results
);
110 } catch (IOException e
) {
111 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
112 .getSimpleName() + ")", e
);
116 final var stickerString
= ns
.getString("sticker");
117 final var sticker
= stickerString
== null ?
null : parseSticker(stickerString
);
119 var messageText
= ns
.getString("message");
120 final var readMessageFromStdin
= ns
.getBoolean("message-from-stdin") == Boolean
.TRUE
;
121 if (readMessageFromStdin
|| (messageText
== null && sticker
== null)) {
122 logger
.debug("Reading message from stdin...");
124 messageText
= IOUtils
.readAll(System
.in, IOUtils
.getConsoleCharset());
125 } catch (IOException e
) {
126 throw new UserErrorException("Failed to read message from stdin: " + e
.getMessage());
130 List
<String
> attachments
= ns
.getList("attachment");
131 if (attachments
== null) {
132 attachments
= List
.of();
135 List
<String
> mentionStrings
= ns
.getList("mention");
136 final var mentions
= mentionStrings
== null ? List
.<Message
.Mention
>of() : parseMentions(m
, mentionStrings
);
138 final Message
.Quote quote
;
139 final var quoteTimestamp
= ns
.getLong("quote-timestamp");
140 if (quoteTimestamp
!= null) {
141 final var quoteAuthor
= ns
.getString("quote-author");
142 final var quoteMessage
= ns
.getString("quote-message");
143 List
<String
> quoteMentionStrings
= ns
.getList("quote-mention");
144 final var quoteMentions
= quoteMentionStrings
== null
145 ? List
.<Message
.Mention
>of()
146 : parseMentions(m
, quoteMentionStrings
);
147 quote
= new Message
.Quote(quoteTimestamp
,
148 CommandUtil
.getSingleRecipientIdentifier(quoteAuthor
, m
.getSelfNumber()),
149 quoteMessage
== null ?
"" : quoteMessage
,
155 final List
<Message
.Preview
> previews
;
156 String previewUrl
= ns
.getString("preview-url");
157 if (previewUrl
!= null) {
158 String previewTitle
= ns
.getString("preview-title");
159 String previewDescription
= ns
.getString("preview-description");
160 String previewImage
= ns
.getString("preview-image");
161 previews
= List
.of(new Message
.Preview(previewUrl
,
162 Optional
.ofNullable(previewTitle
).orElse(""),
163 Optional
.ofNullable(previewDescription
).orElse(""),
164 Optional
.ofNullable(previewImage
)));
166 previews
= List
.of();
170 var results
= m
.sendMessage(new Message(messageText
== null ?
"" : messageText
,
173 Optional
.ofNullable(quote
),
174 Optional
.ofNullable(sticker
),
175 previews
), recipientIdentifiers
);
176 outputResult(outputWriter
, results
);
177 } catch (AttachmentInvalidException
| IOException e
) {
178 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
179 .getSimpleName() + ")", e
);
180 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
181 throw new UserErrorException(e
.getMessage());
182 } catch (UnregisteredRecipientException e
) {
183 throw new UserErrorException("The user " + e
.getSender().getIdentifier() + " is not registered.");
184 } catch (InvalidStickerException e
) {
185 throw new UserErrorException("Failed to send sticker: " + e
.getMessage(), e
);
189 private List
<Message
.Mention
> parseMentions(
190 final Manager m
, final List
<String
> mentionStrings
191 ) throws UserErrorException
{
192 List
<Message
.Mention
> mentions
;
193 final Pattern mentionPattern
= Pattern
.compile("(\\d+):(\\d+):(.+)");
194 mentions
= new ArrayList
<>();
195 for (final var mention
: mentionStrings
) {
196 final var matcher
= mentionPattern
.matcher(mention
);
197 if (!matcher
.matches()) {
198 throw new UserErrorException("Invalid mention syntax ("
200 + ") expected 'start:end:recipientNumber'");
202 mentions
.add(new Message
.Mention(CommandUtil
.getSingleRecipientIdentifier(matcher
.group(3),
203 m
.getSelfNumber()), Integer
.parseInt(matcher
.group(1)), Integer
.parseInt(matcher
.group(2))));
208 private Message
.Sticker
parseSticker(final String stickerString
) throws UserErrorException
{
209 final Pattern stickerPattern
= Pattern
.compile("([\\da-f]+):(\\d+)");
210 final var matcher
= stickerPattern
.matcher(stickerString
);
211 if (!matcher
.matches() || matcher
.group(1).length() % 2 != 0) {
212 throw new UserErrorException("Invalid sticker syntax ("
214 + ") expected 'stickerPackId:stickerId'");
216 return new Message
.Sticker(Hex
.toByteArray(matcher
.group(1)), Integer
.parseInt(matcher
.group(2)));