]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/SendCommand.java
Document the unit of "start" and "length" for mentions and text styles (#1505)
[signal-cli] / src / main / java / org / asamk / signal / commands / SendCommand.java
1 package org.asamk.signal.commands;
2
3 import net.sourceforge.argparse4j.impl.Arguments;
4 import net.sourceforge.argparse4j.inf.Namespace;
5 import net.sourceforge.argparse4j.inf.Subparser;
6
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;
26
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;
33
34 import static org.asamk.signal.util.SendMessageResultUtils.outputResult;
35
36 public class SendCommand implements JsonRpcLocalCommand {
37
38 private static final Logger logger = LoggerFactory.getLogger(SendCommand.class);
39
40 @Override
41 public String getName() {
42 return "send";
43 }
44
45 @Override
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());
57
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.");
63
64 subparser.addArgument("-a", "--attachment")
65 .nargs("*")
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")
73 .nargs("*")
74 .help("Mention another group member (syntax: start:length:recipientNumber). "
75 + "Unit of start and length is UTF-16 code units, NOT Unicode code points.");
76 subparser.addArgument("--text-style")
77 .nargs("*")
78 .help("Style parts of the message text (syntax: start:length:STYLE). "
79 + "Unit of start and length is UTF-16 code units, NOT Unicode code points.");
80 subparser.addArgument("--quote-timestamp")
81 .type(long.class)
82 .help("Specify the timestamp of a previous message with the recipient or group to add a quote to the new message.");
83 subparser.addArgument("--quote-author").help("Specify the number of the author of the original message.");
84 subparser.addArgument("--quote-message").help("Specify the message of the original message.");
85 subparser.addArgument("--quote-mention")
86 .nargs("*")
87 .help("Quote with mention of another group member (syntax: start:length:recipientNumber)");
88 subparser.addArgument("--quote-attachment")
89 .nargs("*")
90 .help("Specify the attachments of the original message (syntax: contentType[:filename[:previewFile]]), e.g. 'audio/aac' or 'image/png:test.png:/tmp/preview.jpg'.");
91 subparser.addArgument("--quote-text-style")
92 .nargs("*")
93 .help("Quote with style parts of the message text (syntax: start:length:STYLE)");
94 subparser.addArgument("--sticker").help("Send a sticker (syntax: stickerPackId:stickerId)");
95 subparser.addArgument("--preview-url")
96 .help("Specify the url for the link preview (the same url must also appear in the message body).");
97 subparser.addArgument("--preview-title").help("Specify the title for the link preview (mandatory).");
98 subparser.addArgument("--preview-description").help("Specify the description for the link preview (optional).");
99 subparser.addArgument("--preview-image").help("Specify the image file for the link preview (optional).");
100 subparser.addArgument("--story-timestamp")
101 .type(long.class)
102 .help("Specify the timestamp of a story to reply to.");
103 subparser.addArgument("--story-author").help("Specify the number of the author of the story.");
104 subparser.addArgument("--edit-timestamp")
105 .type(long.class)
106 .help("Specify the timestamp of a previous message with the recipient or group to send an edited message.");
107 }
108
109 @Override
110 public void handleCommand(
111 final Namespace ns, final Manager m, final OutputWriter outputWriter
112 ) throws CommandException {
113 final var notifySelf = Boolean.TRUE.equals(ns.getBoolean("notify-self"));
114 final var isNoteToSelf = Boolean.TRUE.equals(ns.getBoolean("note-to-self"));
115 final var recipientStrings = ns.<String>getList("recipient");
116 final var groupIdStrings = ns.<String>getList("group-id");
117 final var usernameStrings = ns.<String>getList("username");
118
119 final var recipientIdentifiers = CommandUtil.getRecipientIdentifiers(m,
120 isNoteToSelf,
121 recipientStrings,
122 groupIdStrings,
123 usernameStrings);
124
125 final var isEndSession = Boolean.TRUE.equals(ns.getBoolean("end-session"));
126 if (isEndSession) {
127 final var singleRecipients = recipientIdentifiers.stream()
128 .filter(r -> r instanceof RecipientIdentifier.Single)
129 .map(RecipientIdentifier.Single.class::cast)
130 .collect(Collectors.toSet());
131 if (singleRecipients.isEmpty()) {
132 throw new UserErrorException("No recipients given");
133 }
134
135 try {
136 final var results = m.sendEndSessionMessage(singleRecipients);
137 outputResult(outputWriter, results);
138 return;
139 } catch (IOException e) {
140 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
141 .getSimpleName() + ")", e);
142 }
143 }
144
145 final var stickerString = ns.getString("sticker");
146 final var sticker = stickerString == null ? null : parseSticker(stickerString);
147
148 var messageText = ns.getString("message");
149 final var readMessageFromStdin = ns.getBoolean("message-from-stdin") == Boolean.TRUE;
150 if (readMessageFromStdin) {
151 logger.debug("Reading message from stdin...");
152 try {
153 messageText = IOUtils.readAll(System.in, IOUtils.getConsoleCharset());
154 } catch (IOException e) {
155 throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
156 }
157 } else if (messageText == null) {
158 messageText = "";
159 }
160
161 var attachments = ns.<String>getList("attachment");
162 if (attachments == null) {
163 attachments = List.of();
164 }
165
166 final var selfNumber = m.getSelfNumber();
167
168 final var mentionStrings = ns.<String>getList("mention");
169 final var mentions = mentionStrings == null
170 ? List.<Message.Mention>of()
171 : parseMentions(selfNumber, mentionStrings);
172
173 final var textStyleStrings = ns.<String>getList("text-style");
174 final var textStyles = textStyleStrings == null ? List.<TextStyle>of() : parseTextStyles(textStyleStrings);
175
176 final Message.Quote quote;
177 final var quoteTimestamp = ns.getLong("quote-timestamp");
178 if (quoteTimestamp != null) {
179 final var quoteAuthor = ns.getString("quote-author");
180 final var quoteMessage = ns.getString("quote-message");
181 final var quoteMentionStrings = ns.<String>getList("quote-mention");
182 final var quoteMentions = quoteMentionStrings == null
183 ? List.<Message.Mention>of()
184 : parseMentions(selfNumber, quoteMentionStrings);
185 final var quoteTextStyleStrings = ns.<String>getList("quote-text-style");
186 final var quoteAttachmentStrings = ns.<String>getList("quote-attachment");
187 final var quoteTextStyles = quoteTextStyleStrings == null
188 ? List.<TextStyle>of()
189 : parseTextStyles(quoteTextStyleStrings);
190 final var quoteAttachments = quoteAttachmentStrings == null
191 ? List.<Message.Quote.Attachment>of()
192 : parseQuoteAttachments(quoteAttachmentStrings);
193 quote = new Message.Quote(quoteTimestamp,
194 CommandUtil.getSingleRecipientIdentifier(quoteAuthor, selfNumber),
195 quoteMessage == null ? "" : quoteMessage,
196 quoteMentions,
197 quoteTextStyles,
198 quoteAttachments);
199 } else {
200 quote = null;
201 }
202
203 final List<Message.Preview> previews;
204 final var previewUrl = ns.getString("preview-url");
205 if (previewUrl != null) {
206 final var previewTitle = ns.getString("preview-title");
207 final var previewDescription = ns.getString("preview-description");
208 final var previewImage = ns.getString("preview-image");
209 previews = List.of(new Message.Preview(previewUrl,
210 Optional.ofNullable(previewTitle).orElse(""),
211 Optional.ofNullable(previewDescription).orElse(""),
212 Optional.ofNullable(previewImage)));
213 } else {
214 previews = List.of();
215 }
216
217 final Message.StoryReply storyReply;
218 final var storyReplyTimestamp = ns.getLong("story-timestamp");
219 if (storyReplyTimestamp != null) {
220 final var storyAuthor = ns.getString("story-author");
221 storyReply = new Message.StoryReply(storyReplyTimestamp,
222 CommandUtil.getSingleRecipientIdentifier(storyAuthor, selfNumber));
223 } else {
224 storyReply = null;
225 }
226
227 if (messageText.isEmpty() && attachments.isEmpty() && sticker == null && quote == null) {
228 throw new UserErrorException(
229 "Sending empty message is not allowed, either a message, attachment or sticker must be given.");
230 }
231
232 final var editTimestamp = ns.getLong("edit-timestamp");
233
234 try {
235 final var message = new Message(messageText,
236 attachments,
237 mentions,
238 Optional.ofNullable(quote),
239 Optional.ofNullable(sticker),
240 previews,
241 Optional.ofNullable((storyReply)),
242 textStyles);
243 var results = editTimestamp != null
244 ? m.sendEditMessage(message, recipientIdentifiers, editTimestamp)
245 : m.sendMessage(message, recipientIdentifiers, notifySelf);
246 outputResult(outputWriter, results);
247 } catch (AttachmentInvalidException | IOException e) {
248 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
249 .getSimpleName() + ")", e);
250 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
251 throw new UserErrorException(e.getMessage());
252 } catch (UnregisteredRecipientException e) {
253 throw new UserErrorException("The user " + e.getSender().getIdentifier() + " is not registered.");
254 } catch (InvalidStickerException e) {
255 throw new UserErrorException("Failed to send sticker: " + e.getMessage(), e);
256 }
257 }
258
259 private List<Message.Mention> parseMentions(
260 final String selfNumber, final List<String> mentionStrings
261 ) throws UserErrorException {
262 final var mentionPattern = Pattern.compile("(\\d+):(\\d+):(.+)");
263 final var mentions = new ArrayList<Message.Mention>();
264 for (final var mention : mentionStrings) {
265 final var matcher = mentionPattern.matcher(mention);
266 if (!matcher.matches()) {
267 throw new UserErrorException("Invalid mention syntax ("
268 + mention
269 + ") expected 'start:length:recipientNumber'");
270 }
271 mentions.add(new Message.Mention(CommandUtil.getSingleRecipientIdentifier(matcher.group(3), selfNumber),
272 Integer.parseInt(matcher.group(1)),
273 Integer.parseInt(matcher.group(2))));
274 }
275 return mentions;
276 }
277
278 private List<TextStyle> parseTextStyles(
279 final List<String> textStylesStrings
280 ) throws UserErrorException {
281 final var textStylePattern = Pattern.compile("(\\d+):(\\d+):(.+)");
282 final var textStyles = new ArrayList<TextStyle>();
283 for (final var textStyle : textStylesStrings) {
284 final var matcher = textStylePattern.matcher(textStyle);
285 if (!matcher.matches()) {
286 throw new UserErrorException("Invalid textStyle syntax ("
287 + textStyle
288 + ") expected 'start:length:STYLE'");
289 }
290 final var style = TextStyle.Style.from(matcher.group(3));
291 if (style == null) {
292 throw new UserErrorException("Invalid style: " + matcher.group(3));
293 }
294 textStyles.add(new TextStyle(style,
295 Integer.parseInt(matcher.group(1)),
296 Integer.parseInt(matcher.group(2))));
297 }
298 return textStyles;
299 }
300
301 private Message.Sticker parseSticker(final String stickerString) throws UserErrorException {
302 final var stickerPattern = Pattern.compile("([\\da-f]+):(\\d+)");
303 final var matcher = stickerPattern.matcher(stickerString);
304 if (!matcher.matches() || matcher.group(1).length() % 2 != 0) {
305 throw new UserErrorException("Invalid sticker syntax ("
306 + stickerString
307 + ") expected 'stickerPackId:stickerId'");
308 }
309 return new Message.Sticker(Hex.toByteArray(matcher.group(1)), Integer.parseInt(matcher.group(2)));
310 }
311
312 private List<Message.Quote.Attachment> parseQuoteAttachments(
313 final List<String> attachmentStrings
314 ) throws UserErrorException {
315 final var attachmentPattern = Pattern.compile("([^:]+)(:([^:]+)(:(.+))?)?");
316 final var attachments = new ArrayList<Message.Quote.Attachment>();
317 for (final var attachment : attachmentStrings) {
318 final var matcher = attachmentPattern.matcher(attachment);
319 if (!matcher.matches()) {
320 throw new UserErrorException("Invalid attachment syntax ("
321 + attachment
322 + ") expected 'contentType[:filename[:previewFile]]'");
323 }
324 attachments.add(new Message.Quote.Attachment(matcher.group(1), matcher.group(3), matcher.group(5)));
325 }
326 return attachments;
327 }
328 }