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
.GroupNotFoundException
;
13 import org
.asamk
.signal
.manager
.api
.GroupSendingNotAllowedException
;
14 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
15 import org
.asamk
.signal
.manager
.api
.Message
;
16 import org
.asamk
.signal
.manager
.api
.NotAGroupMemberException
;
17 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
18 import org
.asamk
.signal
.manager
.api
.TextStyle
;
19 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
20 import org
.asamk
.signal
.output
.OutputWriter
;
21 import org
.asamk
.signal
.util
.CommandUtil
;
22 import org
.asamk
.signal
.util
.Hex
;
23 import org
.asamk
.signal
.util
.IOUtils
;
24 import org
.slf4j
.Logger
;
25 import org
.slf4j
.LoggerFactory
;
27 import java
.io
.IOException
;
28 import java
.util
.ArrayList
;
29 import java
.util
.List
;
30 import java
.util
.Optional
;
31 import java
.util
.regex
.Pattern
;
32 import java
.util
.stream
.Collectors
;
34 import static org
.asamk
.signal
.util
.SendMessageResultUtils
.outputResult
;
36 public class SendCommand
implements JsonRpcLocalCommand
{
38 private final static Logger logger
= LoggerFactory
.getLogger(SendCommand
.class);
41 public String
getName() {
46 public void attachToSubparser(final Subparser subparser
) {
47 subparser
.help("Send a message to another user or group.");
48 subparser
.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
49 subparser
.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.").nargs("*");
50 subparser
.addArgument("--note-to-self")
51 .help("Send the message to self without notification.")
52 .action(Arguments
.storeTrue());
54 var mut
= subparser
.addMutuallyExclusiveGroup();
55 mut
.addArgument("-m", "--message").help("Specify the message to be sent.");
56 mut
.addArgument("--message-from-stdin")
57 .action(Arguments
.storeTrue())
58 .help("Read the message from standard input.");
59 subparser
.addArgument("-a", "--attachment")
61 .help("Add an attachment. "
62 + "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. "
63 + "data:<MIME-TYPE>;filename=<FILENAME>;base64,<BASE64 ENCODED DATA>.");
64 subparser
.addArgument("-e", "--end-session", "--endsession")
65 .help("Clear session state and send end session message.")
66 .action(Arguments
.storeTrue());
67 subparser
.addArgument("--mention")
69 .help("Mention another group member (syntax: start:length:recipientNumber)");
70 subparser
.addArgument("--text-style")
72 .help("Style parts of the message text (syntax: start:length:STYLE)");
73 subparser
.addArgument("--quote-timestamp")
75 .help("Specify the timestamp of a previous message with the recipient or group to add a quote to the new message.");
76 subparser
.addArgument("--quote-author").help("Specify the number of the author of the original message.");
77 subparser
.addArgument("--quote-message").help("Specify the message of the original message.");
78 subparser
.addArgument("--quote-mention")
80 .help("Quote with mention of another group member (syntax: start:length:recipientNumber)");
81 subparser
.addArgument("--quote-attachment")
83 .help("Specify the attachments of the original message (syntax: contentType[:filename[:previewFile]]), e.g. 'audio/aac' or 'image/png:test.png:/tmp/preview.jpg'.");
84 subparser
.addArgument("--quote-text-style")
86 .help("Quote with style parts of the message text (syntax: start:length:STYLE)");
87 subparser
.addArgument("--sticker").help("Send a sticker (syntax: stickerPackId:stickerId)");
88 subparser
.addArgument("--preview-url")
89 .help("Specify the url for the link preview (the same url must also appear in the message body).");
90 subparser
.addArgument("--preview-title").help("Specify the title for the link preview (mandatory).");
91 subparser
.addArgument("--preview-description").help("Specify the description for the link preview (optional).");
92 subparser
.addArgument("--preview-image").help("Specify the image file for the link preview (optional).");
93 subparser
.addArgument("--story-timestamp")
95 .help("Specify the timestamp of a story to reply to.");
96 subparser
.addArgument("--story-author").help("Specify the number of the author of the story.");
97 subparser
.addArgument("--edit-timestamp")
99 .help("Specify the timestamp of a previous message with the recipient or group to send an edited message.");
103 public void handleCommand(
104 final Namespace ns
, final Manager m
, final OutputWriter outputWriter
105 ) throws CommandException
{
106 final var isNoteToSelf
= Boolean
.TRUE
.equals(ns
.getBoolean("note-to-self"));
107 final var recipientStrings
= ns
.<String
>getList("recipient");
108 final var groupIdStrings
= ns
.<String
>getList("group-id");
110 final var recipientIdentifiers
= CommandUtil
.getRecipientIdentifiers(m
,
115 final var isEndSession
= Boolean
.TRUE
.equals(ns
.getBoolean("end-session"));
117 final var singleRecipients
= recipientIdentifiers
.stream()
118 .filter(r
-> r
instanceof RecipientIdentifier
.Single
)
119 .map(RecipientIdentifier
.Single
.class::cast
)
120 .collect(Collectors
.toSet());
121 if (singleRecipients
.isEmpty()) {
122 throw new UserErrorException("No recipients given");
126 final var results
= m
.sendEndSessionMessage(singleRecipients
);
127 outputResult(outputWriter
, results
);
129 } catch (IOException e
) {
130 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
131 .getSimpleName() + ")", e
);
135 final var stickerString
= ns
.getString("sticker");
136 final var sticker
= stickerString
== null ?
null : parseSticker(stickerString
);
138 var messageText
= ns
.getString("message");
139 final var readMessageFromStdin
= ns
.getBoolean("message-from-stdin") == Boolean
.TRUE
;
140 if (readMessageFromStdin
) {
141 logger
.debug("Reading message from stdin...");
143 messageText
= IOUtils
.readAll(System
.in, IOUtils
.getConsoleCharset());
144 } catch (IOException e
) {
145 throw new UserErrorException("Failed to read message from stdin: " + e
.getMessage());
147 } else if (messageText
== null) {
151 var attachments
= ns
.<String
>getList("attachment");
152 if (attachments
== null) {
153 attachments
= List
.of();
156 final var selfNumber
= m
.getSelfNumber();
158 final var mentionStrings
= ns
.<String
>getList("mention");
159 final var mentions
= mentionStrings
== null
160 ? List
.<Message
.Mention
>of()
161 : parseMentions(selfNumber
, mentionStrings
);
163 final var textStyleStrings
= ns
.<String
>getList("text-style");
164 final var textStyles
= textStyleStrings
== null ? List
.<TextStyle
>of() : parseTextStyles(textStyleStrings
);
166 final Message
.Quote quote
;
167 final var quoteTimestamp
= ns
.getLong("quote-timestamp");
168 if (quoteTimestamp
!= null) {
169 final var quoteAuthor
= ns
.getString("quote-author");
170 final var quoteMessage
= ns
.getString("quote-message");
171 final var quoteMentionStrings
= ns
.<String
>getList("quote-mention");
172 final var quoteMentions
= quoteMentionStrings
== null
173 ? List
.<Message
.Mention
>of()
174 : parseMentions(selfNumber
, quoteMentionStrings
);
175 final var quoteTextStyleStrings
= ns
.<String
>getList("quote-text-style");
176 final var quoteAttachmentStrings
= ns
.<String
>getList("quote-attachment");
177 final var quoteTextStyles
= quoteTextStyleStrings
== null
178 ? List
.<TextStyle
>of()
179 : parseTextStyles(quoteTextStyleStrings
);
180 final var quoteAttachments
= quoteAttachmentStrings
== null
181 ? List
.<Message
.Quote
.Attachment
>of()
182 : parseQuoteAttachments(quoteAttachmentStrings
);
183 quote
= new Message
.Quote(quoteTimestamp
,
184 CommandUtil
.getSingleRecipientIdentifier(quoteAuthor
, selfNumber
),
185 quoteMessage
== null ?
"" : quoteMessage
,
193 final List
<Message
.Preview
> previews
;
194 final var previewUrl
= ns
.getString("preview-url");
195 if (previewUrl
!= null) {
196 final var previewTitle
= ns
.getString("preview-title");
197 final var previewDescription
= ns
.getString("preview-description");
198 final var previewImage
= ns
.getString("preview-image");
199 previews
= List
.of(new Message
.Preview(previewUrl
,
200 Optional
.ofNullable(previewTitle
).orElse(""),
201 Optional
.ofNullable(previewDescription
).orElse(""),
202 Optional
.ofNullable(previewImage
)));
204 previews
= List
.of();
207 final Message
.StoryReply storyReply
;
208 final var storyReplyTimestamp
= ns
.getLong("story-timestamp");
209 if (storyReplyTimestamp
!= null) {
210 final var storyAuthor
= ns
.getString("story-author");
211 storyReply
= new Message
.StoryReply(storyReplyTimestamp
,
212 CommandUtil
.getSingleRecipientIdentifier(storyAuthor
, selfNumber
));
217 if (messageText
.isEmpty() && attachments
.isEmpty() && sticker
== null && quote
== null) {
218 throw new UserErrorException(
219 "Sending empty message is not allowed, either a message, attachment or sticker must be given.");
222 final var editTimestamp
= ns
.getLong("edit-timestamp");
225 final var message
= new Message(messageText
,
228 Optional
.ofNullable(quote
),
229 Optional
.ofNullable(sticker
),
231 Optional
.ofNullable((storyReply
)),
233 var results
= editTimestamp
!= null
234 ? m
.sendEditMessage(message
, recipientIdentifiers
, editTimestamp
)
235 : m
.sendMessage(message
, recipientIdentifiers
);
236 outputResult(outputWriter
, results
);
237 } catch (AttachmentInvalidException
| IOException e
) {
238 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
239 .getSimpleName() + ")", e
);
240 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
241 throw new UserErrorException(e
.getMessage());
242 } catch (UnregisteredRecipientException e
) {
243 throw new UserErrorException("The user " + e
.getSender().getIdentifier() + " is not registered.");
244 } catch (InvalidStickerException e
) {
245 throw new UserErrorException("Failed to send sticker: " + e
.getMessage(), e
);
249 private List
<Message
.Mention
> parseMentions(
250 final String selfNumber
, final List
<String
> mentionStrings
251 ) throws UserErrorException
{
252 final var mentionPattern
= Pattern
.compile("(\\d+):(\\d+):(.+)");
253 final var mentions
= new ArrayList
<Message
.Mention
>();
254 for (final var mention
: mentionStrings
) {
255 final var matcher
= mentionPattern
.matcher(mention
);
256 if (!matcher
.matches()) {
257 throw new UserErrorException("Invalid mention syntax ("
259 + ") expected 'start:length:recipientNumber'");
261 mentions
.add(new Message
.Mention(CommandUtil
.getSingleRecipientIdentifier(matcher
.group(3), selfNumber
),
262 Integer
.parseInt(matcher
.group(1)),
263 Integer
.parseInt(matcher
.group(2))));
268 private List
<TextStyle
> parseTextStyles(
269 final List
<String
> textStylesStrings
270 ) throws UserErrorException
{
271 final var textStylePattern
= Pattern
.compile("(\\d+):(\\d+):(.+)");
272 final var textStyles
= new ArrayList
<TextStyle
>();
273 for (final var textStyle
: textStylesStrings
) {
274 final var matcher
= textStylePattern
.matcher(textStyle
);
275 if (!matcher
.matches()) {
276 throw new UserErrorException("Invalid textStyle syntax ("
278 + ") expected 'start:length:STYLE'");
280 final var style
= TextStyle
.Style
.from(matcher
.group(3));
282 throw new UserErrorException("Invalid style: " + matcher
.group(3));
284 textStyles
.add(new TextStyle(style
,
285 Integer
.parseInt(matcher
.group(1)),
286 Integer
.parseInt(matcher
.group(2))));
291 private Message
.Sticker
parseSticker(final String stickerString
) throws UserErrorException
{
292 final var stickerPattern
= Pattern
.compile("([\\da-f]+):(\\d+)");
293 final var matcher
= stickerPattern
.matcher(stickerString
);
294 if (!matcher
.matches() || matcher
.group(1).length() % 2 != 0) {
295 throw new UserErrorException("Invalid sticker syntax ("
297 + ") expected 'stickerPackId:stickerId'");
299 return new Message
.Sticker(Hex
.toByteArray(matcher
.group(1)), Integer
.parseInt(matcher
.group(2)));
302 private List
<Message
.Quote
.Attachment
> parseQuoteAttachments(
303 final List
<String
> attachmentStrings
304 ) throws UserErrorException
{
305 final var attachmentPattern
= Pattern
.compile("([^:]+)(:([^:]+)(:(.+))?)?");
306 final var attachments
= new ArrayList
<Message
.Quote
.Attachment
>();
307 for (final var attachment
: attachmentStrings
) {
308 final var matcher
= attachmentPattern
.matcher(attachment
);
309 if (!matcher
.matches()) {
310 throw new UserErrorException("Invalid attachment syntax ("
312 + ") expected 'contentType[:filename[:previewFile]]'");
314 attachments
.add(new Message
.Quote
.Attachment(matcher
.group(1), matcher
.group(3), matcher
.group(5)));