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 static final 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("-u", "--username").help("Specify the recipient username or username link.").nargs("*");
51 subparser
.addArgument("--note-to-self")
52 .help("Send the message to self without notification.")
53 .action(Arguments
.storeTrue());
54 subparser
.addArgument("--notify-self")
55 .help("If self is part of recipients/groups send a normal message, not a sync message.")
56 .action(Arguments
.storeTrue());
58 var mut
= subparser
.addMutuallyExclusiveGroup();
59 mut
.addArgument("-m", "--message").help("Specify the message to be sent.");
60 mut
.addArgument("--message-from-stdin")
61 .action(Arguments
.storeTrue())
62 .help("Read the message from standard input.");
64 subparser
.addArgument("-a", "--attachment")
66 .help("Add an attachment. "
67 + "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. "
68 + "data:<MIME-TYPE>;filename=<FILENAME>;base64,<BASE64 ENCODED DATA>.");
69 subparser
.addArgument("-e", "--end-session", "--endsession")
70 .help("Clear session state and send end session message.")
71 .action(Arguments
.storeTrue());
72 subparser
.addArgument("--mention")
74 .help("Mention another group member (syntax: start:length:recipientNumber)");
75 subparser
.addArgument("--text-style")
77 .help("Style parts of the message text (syntax: start:length:STYLE)");
78 subparser
.addArgument("--quote-timestamp")
80 .help("Specify the timestamp of a previous message with the recipient or group to add a quote to the new message.");
81 subparser
.addArgument("--quote-author").help("Specify the number of the author of the original message.");
82 subparser
.addArgument("--quote-message").help("Specify the message of the original message.");
83 subparser
.addArgument("--quote-mention")
85 .help("Quote with mention of another group member (syntax: start:length:recipientNumber)");
86 subparser
.addArgument("--quote-attachment")
88 .help("Specify the attachments of the original message (syntax: contentType[:filename[:previewFile]]), e.g. 'audio/aac' or 'image/png:test.png:/tmp/preview.jpg'.");
89 subparser
.addArgument("--quote-text-style")
91 .help("Quote with style parts of the message text (syntax: start:length:STYLE)");
92 subparser
.addArgument("--sticker").help("Send a sticker (syntax: stickerPackId:stickerId)");
93 subparser
.addArgument("--preview-url")
94 .help("Specify the url for the link preview (the same url must also appear in the message body).");
95 subparser
.addArgument("--preview-title").help("Specify the title for the link preview (mandatory).");
96 subparser
.addArgument("--preview-description").help("Specify the description for the link preview (optional).");
97 subparser
.addArgument("--preview-image").help("Specify the image file for the link preview (optional).");
98 subparser
.addArgument("--story-timestamp")
100 .help("Specify the timestamp of a story to reply to.");
101 subparser
.addArgument("--story-author").help("Specify the number of the author of the story.");
102 subparser
.addArgument("--edit-timestamp")
104 .help("Specify the timestamp of a previous message with the recipient or group to send an edited message.");
108 public void handleCommand(
109 final Namespace ns
, final Manager m
, final OutputWriter outputWriter
110 ) throws CommandException
{
111 final var notifySelf
= Boolean
.TRUE
.equals(ns
.getBoolean("notify-self"));
112 final var isNoteToSelf
= Boolean
.TRUE
.equals(ns
.getBoolean("note-to-self"));
113 final var recipientStrings
= ns
.<String
>getList("recipient");
114 final var groupIdStrings
= ns
.<String
>getList("group-id");
115 final var usernameStrings
= ns
.<String
>getList("username");
117 final var recipientIdentifiers
= CommandUtil
.getRecipientIdentifiers(m
,
123 final var isEndSession
= Boolean
.TRUE
.equals(ns
.getBoolean("end-session"));
125 final var singleRecipients
= recipientIdentifiers
.stream()
126 .filter(r
-> r
instanceof RecipientIdentifier
.Single
)
127 .map(RecipientIdentifier
.Single
.class::cast
)
128 .collect(Collectors
.toSet());
129 if (singleRecipients
.isEmpty()) {
130 throw new UserErrorException("No recipients given");
134 final var results
= m
.sendEndSessionMessage(singleRecipients
);
135 outputResult(outputWriter
, results
);
137 } catch (IOException e
) {
138 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
139 .getSimpleName() + ")", e
);
143 final var stickerString
= ns
.getString("sticker");
144 final var sticker
= stickerString
== null ?
null : parseSticker(stickerString
);
146 var messageText
= ns
.getString("message");
147 final var readMessageFromStdin
= ns
.getBoolean("message-from-stdin") == Boolean
.TRUE
;
148 if (readMessageFromStdin
) {
149 logger
.debug("Reading message from stdin...");
151 messageText
= IOUtils
.readAll(System
.in, IOUtils
.getConsoleCharset());
152 } catch (IOException e
) {
153 throw new UserErrorException("Failed to read message from stdin: " + e
.getMessage());
155 } else if (messageText
== null) {
159 var attachments
= ns
.<String
>getList("attachment");
160 if (attachments
== null) {
161 attachments
= List
.of();
164 final var selfNumber
= m
.getSelfNumber();
166 final var mentionStrings
= ns
.<String
>getList("mention");
167 final var mentions
= mentionStrings
== null
168 ? List
.<Message
.Mention
>of()
169 : parseMentions(selfNumber
, mentionStrings
);
171 final var textStyleStrings
= ns
.<String
>getList("text-style");
172 final var textStyles
= textStyleStrings
== null ? List
.<TextStyle
>of() : parseTextStyles(textStyleStrings
);
174 final Message
.Quote quote
;
175 final var quoteTimestamp
= ns
.getLong("quote-timestamp");
176 if (quoteTimestamp
!= null) {
177 final var quoteAuthor
= ns
.getString("quote-author");
178 final var quoteMessage
= ns
.getString("quote-message");
179 final var quoteMentionStrings
= ns
.<String
>getList("quote-mention");
180 final var quoteMentions
= quoteMentionStrings
== null
181 ? List
.<Message
.Mention
>of()
182 : parseMentions(selfNumber
, quoteMentionStrings
);
183 final var quoteTextStyleStrings
= ns
.<String
>getList("quote-text-style");
184 final var quoteAttachmentStrings
= ns
.<String
>getList("quote-attachment");
185 final var quoteTextStyles
= quoteTextStyleStrings
== null
186 ? List
.<TextStyle
>of()
187 : parseTextStyles(quoteTextStyleStrings
);
188 final var quoteAttachments
= quoteAttachmentStrings
== null
189 ? List
.<Message
.Quote
.Attachment
>of()
190 : parseQuoteAttachments(quoteAttachmentStrings
);
191 quote
= new Message
.Quote(quoteTimestamp
,
192 CommandUtil
.getSingleRecipientIdentifier(quoteAuthor
, selfNumber
),
193 quoteMessage
== null ?
"" : quoteMessage
,
201 final List
<Message
.Preview
> previews
;
202 final var previewUrl
= ns
.getString("preview-url");
203 if (previewUrl
!= null) {
204 final var previewTitle
= ns
.getString("preview-title");
205 final var previewDescription
= ns
.getString("preview-description");
206 final var previewImage
= ns
.getString("preview-image");
207 previews
= List
.of(new Message
.Preview(previewUrl
,
208 Optional
.ofNullable(previewTitle
).orElse(""),
209 Optional
.ofNullable(previewDescription
).orElse(""),
210 Optional
.ofNullable(previewImage
)));
212 previews
= List
.of();
215 final Message
.StoryReply storyReply
;
216 final var storyReplyTimestamp
= ns
.getLong("story-timestamp");
217 if (storyReplyTimestamp
!= null) {
218 final var storyAuthor
= ns
.getString("story-author");
219 storyReply
= new Message
.StoryReply(storyReplyTimestamp
,
220 CommandUtil
.getSingleRecipientIdentifier(storyAuthor
, selfNumber
));
225 if (messageText
.isEmpty() && attachments
.isEmpty() && sticker
== null && quote
== null) {
226 throw new UserErrorException(
227 "Sending empty message is not allowed, either a message, attachment or sticker must be given.");
230 final var editTimestamp
= ns
.getLong("edit-timestamp");
233 final var message
= new Message(messageText
,
236 Optional
.ofNullable(quote
),
237 Optional
.ofNullable(sticker
),
239 Optional
.ofNullable((storyReply
)),
241 var results
= editTimestamp
!= null
242 ? m
.sendEditMessage(message
, recipientIdentifiers
, editTimestamp
)
243 : m
.sendMessage(message
, recipientIdentifiers
, notifySelf
);
244 outputResult(outputWriter
, results
);
245 } catch (AttachmentInvalidException
| IOException e
) {
246 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
247 .getSimpleName() + ")", e
);
248 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
249 throw new UserErrorException(e
.getMessage());
250 } catch (UnregisteredRecipientException e
) {
251 throw new UserErrorException("The user " + e
.getSender().getIdentifier() + " is not registered.");
252 } catch (InvalidStickerException e
) {
253 throw new UserErrorException("Failed to send sticker: " + e
.getMessage(), e
);
257 private List
<Message
.Mention
> parseMentions(
258 final String selfNumber
, final List
<String
> mentionStrings
259 ) throws UserErrorException
{
260 final var mentionPattern
= Pattern
.compile("(\\d+):(\\d+):(.+)");
261 final var mentions
= new ArrayList
<Message
.Mention
>();
262 for (final var mention
: mentionStrings
) {
263 final var matcher
= mentionPattern
.matcher(mention
);
264 if (!matcher
.matches()) {
265 throw new UserErrorException("Invalid mention syntax ("
267 + ") expected 'start:length:recipientNumber'");
269 mentions
.add(new Message
.Mention(CommandUtil
.getSingleRecipientIdentifier(matcher
.group(3), selfNumber
),
270 Integer
.parseInt(matcher
.group(1)),
271 Integer
.parseInt(matcher
.group(2))));
276 private List
<TextStyle
> parseTextStyles(
277 final List
<String
> textStylesStrings
278 ) throws UserErrorException
{
279 final var textStylePattern
= Pattern
.compile("(\\d+):(\\d+):(.+)");
280 final var textStyles
= new ArrayList
<TextStyle
>();
281 for (final var textStyle
: textStylesStrings
) {
282 final var matcher
= textStylePattern
.matcher(textStyle
);
283 if (!matcher
.matches()) {
284 throw new UserErrorException("Invalid textStyle syntax ("
286 + ") expected 'start:length:STYLE'");
288 final var style
= TextStyle
.Style
.from(matcher
.group(3));
290 throw new UserErrorException("Invalid style: " + matcher
.group(3));
292 textStyles
.add(new TextStyle(style
,
293 Integer
.parseInt(matcher
.group(1)),
294 Integer
.parseInt(matcher
.group(2))));
299 private Message
.Sticker
parseSticker(final String stickerString
) throws UserErrorException
{
300 final var stickerPattern
= Pattern
.compile("([\\da-f]+):(\\d+)");
301 final var matcher
= stickerPattern
.matcher(stickerString
);
302 if (!matcher
.matches() || matcher
.group(1).length() % 2 != 0) {
303 throw new UserErrorException("Invalid sticker syntax ("
305 + ") expected 'stickerPackId:stickerId'");
307 return new Message
.Sticker(Hex
.toByteArray(matcher
.group(1)), Integer
.parseInt(matcher
.group(2)));
310 private List
<Message
.Quote
.Attachment
> parseQuoteAttachments(
311 final List
<String
> attachmentStrings
312 ) throws UserErrorException
{
313 final var attachmentPattern
= Pattern
.compile("([^:]+)(:([^:]+)(:(.+))?)?");
314 final var attachments
= new ArrayList
<Message
.Quote
.Attachment
>();
315 for (final var attachment
: attachmentStrings
) {
316 final var matcher
= attachmentPattern
.matcher(attachment
);
317 if (!matcher
.matches()) {
318 throw new UserErrorException("Invalid attachment syntax ("
320 + ") expected 'contentType[:filename[:previewFile]]'");
322 attachments
.add(new Message
.Quote
.Attachment(matcher
.group(1), matcher
.group(3), matcher
.group(5)));