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-text-style")
83 .help("Quote with style parts of the message text (syntax: start:length:STYLE)");
84 subparser
.addArgument("--sticker").help("Send a sticker (syntax: stickerPackId:stickerId)");
85 subparser
.addArgument("--preview-url")
86 .help("Specify the url for the link preview (the same url must also appear in the message body).");
87 subparser
.addArgument("--preview-title").help("Specify the title for the link preview (mandatory).");
88 subparser
.addArgument("--preview-description").help("Specify the description for the link preview (optional).");
89 subparser
.addArgument("--preview-image").help("Specify the image file for the link preview (optional).");
90 subparser
.addArgument("--story-timestamp")
92 .help("Specify the timestamp of a story to reply to.");
93 subparser
.addArgument("--story-author").help("Specify the number of the author of the story.");
94 subparser
.addArgument("--edit-timestamp")
96 .help("Specify the timestamp of a previous message with the recipient or group to send an edited message.");
100 public void handleCommand(
101 final Namespace ns
, final Manager m
, final OutputWriter outputWriter
102 ) throws CommandException
{
103 final var isNoteToSelf
= Boolean
.TRUE
.equals(ns
.getBoolean("note-to-self"));
104 final var recipientStrings
= ns
.<String
>getList("recipient");
105 final var groupIdStrings
= ns
.<String
>getList("group-id");
107 final var recipientIdentifiers
= CommandUtil
.getRecipientIdentifiers(m
,
112 final var isEndSession
= Boolean
.TRUE
.equals(ns
.getBoolean("end-session"));
114 final var singleRecipients
= recipientIdentifiers
.stream()
115 .filter(r
-> r
instanceof RecipientIdentifier
.Single
)
116 .map(RecipientIdentifier
.Single
.class::cast
)
117 .collect(Collectors
.toSet());
118 if (singleRecipients
.isEmpty()) {
119 throw new UserErrorException("No recipients given");
123 final var results
= m
.sendEndSessionMessage(singleRecipients
);
124 outputResult(outputWriter
, results
);
126 } catch (IOException e
) {
127 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
128 .getSimpleName() + ")", e
);
132 final var stickerString
= ns
.getString("sticker");
133 final var sticker
= stickerString
== null ?
null : parseSticker(stickerString
);
135 var messageText
= ns
.getString("message");
136 final var readMessageFromStdin
= ns
.getBoolean("message-from-stdin") == Boolean
.TRUE
;
137 if (readMessageFromStdin
) {
138 logger
.debug("Reading message from stdin...");
140 messageText
= IOUtils
.readAll(System
.in, IOUtils
.getConsoleCharset());
141 } catch (IOException e
) {
142 throw new UserErrorException("Failed to read message from stdin: " + e
.getMessage());
144 } else if (messageText
== null) {
148 List
<String
> attachments
= ns
.getList("attachment");
149 if (attachments
== null) {
150 attachments
= List
.of();
153 final var selfNumber
= m
.getSelfNumber();
155 List
<String
> mentionStrings
= ns
.getList("mention");
156 final var mentions
= mentionStrings
== null
157 ? List
.<Message
.Mention
>of()
158 : parseMentions(selfNumber
, mentionStrings
);
160 List
<String
> textStyleStrings
= ns
.getList("text-style");
161 final var textStyles
= textStyleStrings
== null ? List
.<TextStyle
>of() : parseTextStyles(textStyleStrings
);
163 final Message
.Quote quote
;
164 final var quoteTimestamp
= ns
.getLong("quote-timestamp");
165 if (quoteTimestamp
!= null) {
166 final var quoteAuthor
= ns
.getString("quote-author");
167 final var quoteMessage
= ns
.getString("quote-message");
168 List
<String
> quoteMentionStrings
= ns
.getList("quote-mention");
169 final var quoteMentions
= quoteMentionStrings
== null
170 ? List
.<Message
.Mention
>of()
171 : parseMentions(selfNumber
, quoteMentionStrings
);
172 List
<String
> quoteTextStyleStrings
= ns
.getList("quote-text-style");
173 final var quoteTextStyles
= quoteTextStyleStrings
== null
174 ? List
.<TextStyle
>of()
175 : parseTextStyles(quoteTextStyleStrings
);
176 quote
= new Message
.Quote(quoteTimestamp
,
177 CommandUtil
.getSingleRecipientIdentifier(quoteAuthor
, selfNumber
),
178 quoteMessage
== null ?
"" : quoteMessage
,
185 final List
<Message
.Preview
> previews
;
186 String previewUrl
= ns
.getString("preview-url");
187 if (previewUrl
!= null) {
188 String previewTitle
= ns
.getString("preview-title");
189 String previewDescription
= ns
.getString("preview-description");
190 String previewImage
= ns
.getString("preview-image");
191 previews
= List
.of(new Message
.Preview(previewUrl
,
192 Optional
.ofNullable(previewTitle
).orElse(""),
193 Optional
.ofNullable(previewDescription
).orElse(""),
194 Optional
.ofNullable(previewImage
)));
196 previews
= List
.of();
199 final Message
.StoryReply storyReply
;
200 final var storyReplyTimestamp
= ns
.getLong("story-timestamp");
201 if (storyReplyTimestamp
!= null) {
202 final var storyAuthor
= ns
.getString("story-author");
203 storyReply
= new Message
.StoryReply(storyReplyTimestamp
,
204 CommandUtil
.getSingleRecipientIdentifier(storyAuthor
, selfNumber
));
209 if (messageText
.isEmpty() && attachments
.isEmpty() && sticker
== null && quote
== null) {
210 throw new UserErrorException(
211 "Sending empty message is not allowed, either a message, attachment or sticker must be given.");
214 final var editTimestamp
= ns
.getLong("edit-timestamp");
217 final var message
= new Message(messageText
,
220 Optional
.ofNullable(quote
),
221 Optional
.ofNullable(sticker
),
223 Optional
.ofNullable((storyReply
)),
225 var results
= editTimestamp
!= null
226 ? m
.sendEditMessage(message
, recipientIdentifiers
, editTimestamp
)
227 : m
.sendMessage(message
, recipientIdentifiers
);
228 outputResult(outputWriter
, results
);
229 } catch (AttachmentInvalidException
| IOException e
) {
230 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
231 .getSimpleName() + ")", e
);
232 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
233 throw new UserErrorException(e
.getMessage());
234 } catch (UnregisteredRecipientException e
) {
235 throw new UserErrorException("The user " + e
.getSender().getIdentifier() + " is not registered.");
236 } catch (InvalidStickerException e
) {
237 throw new UserErrorException("Failed to send sticker: " + e
.getMessage(), e
);
241 private List
<Message
.Mention
> parseMentions(
242 final String selfNumber
, final List
<String
> mentionStrings
243 ) throws UserErrorException
{
244 List
<Message
.Mention
> mentions
;
245 final Pattern mentionPattern
= Pattern
.compile("(\\d+):(\\d+):(.+)");
246 mentions
= new ArrayList
<>();
247 for (final var mention
: mentionStrings
) {
248 final var matcher
= mentionPattern
.matcher(mention
);
249 if (!matcher
.matches()) {
250 throw new UserErrorException("Invalid mention syntax ("
252 + ") expected 'start:length:recipientNumber'");
254 mentions
.add(new Message
.Mention(CommandUtil
.getSingleRecipientIdentifier(matcher
.group(3), selfNumber
),
255 Integer
.parseInt(matcher
.group(1)),
256 Integer
.parseInt(matcher
.group(2))));
261 private List
<TextStyle
> parseTextStyles(
262 final List
<String
> textStylesStrings
263 ) throws UserErrorException
{
264 List
<TextStyle
> textStyles
;
265 final Pattern textStylePattern
= Pattern
.compile("(\\d+):(\\d+):(.+)");
266 textStyles
= new ArrayList
<>();
267 for (final var textStyle
: textStylesStrings
) {
268 final var matcher
= textStylePattern
.matcher(textStyle
);
269 if (!matcher
.matches()) {
270 throw new UserErrorException("Invalid textStyle syntax ("
272 + ") expected 'start:length:STYLE'");
274 final var style
= TextStyle
.Style
.from(matcher
.group(3));
276 throw new UserErrorException("Invalid style: " + matcher
.group(3));
278 textStyles
.add(new TextStyle(style
,
279 Integer
.parseInt(matcher
.group(1)),
280 Integer
.parseInt(matcher
.group(2))));
285 private Message
.Sticker
parseSticker(final String stickerString
) throws UserErrorException
{
286 final Pattern stickerPattern
= Pattern
.compile("([\\da-f]+):(\\d+)");
287 final var matcher
= stickerPattern
.matcher(stickerString
);
288 if (!matcher
.matches() || matcher
.group(1).length() % 2 != 0) {
289 throw new UserErrorException("Invalid sticker syntax ("
291 + ") expected 'stickerPackId:stickerId'");
293 return new Message
.Sticker(Hex
.toByteArray(matcher
.group(1)), Integer
.parseInt(matcher
.group(2)));