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
.TextStyle
;
16 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
17 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
18 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
19 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
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 List
<String
> mentionStrings
= ns
.getList("mention");
154 final var mentions
= mentionStrings
== null ? List
.<Message
.Mention
>of() : parseMentions(m
, mentionStrings
);
156 List
<String
> textStyleStrings
= ns
.getList("text-style");
157 final var textStyles
= textStyleStrings
== null ? List
.<TextStyle
>of() : parseTextStyles(textStyleStrings
);
159 final Message
.Quote quote
;
160 final var quoteTimestamp
= ns
.getLong("quote-timestamp");
161 if (quoteTimestamp
!= null) {
162 final var quoteAuthor
= ns
.getString("quote-author");
163 final var quoteMessage
= ns
.getString("quote-message");
164 List
<String
> quoteMentionStrings
= ns
.getList("quote-mention");
165 final var quoteMentions
= quoteMentionStrings
== null
166 ? List
.<Message
.Mention
>of()
167 : parseMentions(m
, quoteMentionStrings
);
168 List
<String
> quoteTextStyleStrings
= ns
.getList("quote-text-style");
169 final var quoteTextStyles
= quoteTextStyleStrings
== null
170 ? List
.<TextStyle
>of()
171 : parseTextStyles(quoteTextStyleStrings
);
172 quote
= new Message
.Quote(quoteTimestamp
,
173 CommandUtil
.getSingleRecipientIdentifier(quoteAuthor
, m
.getSelfNumber()),
174 quoteMessage
== null ?
"" : quoteMessage
,
181 final List
<Message
.Preview
> previews
;
182 String previewUrl
= ns
.getString("preview-url");
183 if (previewUrl
!= null) {
184 String previewTitle
= ns
.getString("preview-title");
185 String previewDescription
= ns
.getString("preview-description");
186 String previewImage
= ns
.getString("preview-image");
187 previews
= List
.of(new Message
.Preview(previewUrl
,
188 Optional
.ofNullable(previewTitle
).orElse(""),
189 Optional
.ofNullable(previewDescription
).orElse(""),
190 Optional
.ofNullable(previewImage
)));
192 previews
= List
.of();
195 final Message
.StoryReply storyReply
;
196 final var storyReplyTimestamp
= ns
.getLong("story-timestamp");
197 if (storyReplyTimestamp
!= null) {
198 final var storyAuthor
= ns
.getString("story-author");
199 storyReply
= new Message
.StoryReply(storyReplyTimestamp
,
200 CommandUtil
.getSingleRecipientIdentifier(storyAuthor
, m
.getSelfNumber()));
205 if (messageText
.isEmpty() && attachments
.isEmpty() && sticker
== null && quote
== null) {
206 throw new UserErrorException(
207 "Sending empty message is not allowed, either a message, attachment or sticker must be given.");
210 final var editTimestamp
= ns
.getLong("edit-timestamp");
213 final var message
= new Message(messageText
,
216 Optional
.ofNullable(quote
),
217 Optional
.ofNullable(sticker
),
219 Optional
.ofNullable((storyReply
)),
221 var results
= editTimestamp
!= null
222 ? m
.sendEditMessage(message
, recipientIdentifiers
, editTimestamp
)
223 : m
.sendMessage(message
, recipientIdentifiers
);
224 outputResult(outputWriter
, results
);
225 } catch (AttachmentInvalidException
| IOException e
) {
226 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
227 .getSimpleName() + ")", e
);
228 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
229 throw new UserErrorException(e
.getMessage());
230 } catch (UnregisteredRecipientException e
) {
231 throw new UserErrorException("The user " + e
.getSender().getIdentifier() + " is not registered.");
232 } catch (InvalidStickerException e
) {
233 throw new UserErrorException("Failed to send sticker: " + e
.getMessage(), e
);
237 private List
<Message
.Mention
> parseMentions(
238 final Manager m
, final List
<String
> mentionStrings
239 ) throws UserErrorException
{
240 List
<Message
.Mention
> mentions
;
241 final Pattern mentionPattern
= Pattern
.compile("(\\d+):(\\d+):(.+)");
242 mentions
= new ArrayList
<>();
243 for (final var mention
: mentionStrings
) {
244 final var matcher
= mentionPattern
.matcher(mention
);
245 if (!matcher
.matches()) {
246 throw new UserErrorException("Invalid mention syntax ("
248 + ") expected 'start:end:recipientNumber'");
250 mentions
.add(new Message
.Mention(CommandUtil
.getSingleRecipientIdentifier(matcher
.group(3),
251 m
.getSelfNumber()), Integer
.parseInt(matcher
.group(1)), Integer
.parseInt(matcher
.group(2))));
256 private List
<TextStyle
> parseTextStyles(
257 final List
<String
> textStylesStrings
258 ) throws UserErrorException
{
259 List
<TextStyle
> textStyles
;
260 final Pattern textStylePattern
= Pattern
.compile("(\\d+):(\\d+):(.+)");
261 textStyles
= new ArrayList
<>();
262 for (final var textStyle
: textStylesStrings
) {
263 final var matcher
= textStylePattern
.matcher(textStyle
);
264 if (!matcher
.matches()) {
265 throw new UserErrorException("Invalid textStyle syntax ("
267 + ") expected 'start:length:STYLE'");
269 final var style
= TextStyle
.Style
.from(matcher
.group(3));
271 throw new UserErrorException("Invalid style: " + matcher
.group(3));
273 textStyles
.add(new TextStyle(style
,
274 Integer
.parseInt(matcher
.group(1)),
275 Integer
.parseInt(matcher
.group(2))));
280 private Message
.Sticker
parseSticker(final String stickerString
) throws UserErrorException
{
281 final Pattern stickerPattern
= Pattern
.compile("([\\da-f]+):(\\d+)");
282 final var matcher
= stickerPattern
.matcher(stickerString
);
283 if (!matcher
.matches() || matcher
.group(1).length() % 2 != 0) {
284 throw new UserErrorException("Invalid sticker syntax ("
286 + ") expected 'stickerPackId:stickerId'");
288 return new Message
.Sticker(Hex
.toByteArray(matcher
.group(1)), Integer
.parseInt(matcher
.group(2)));