]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/SendCommand.java
39be74ee1eaa4b34a6c5479265c7d6041e8075c6
[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,
112 final Manager m,
113 final OutputWriter outputWriter
114 ) throws CommandException {
115 final var notifySelf = Boolean.TRUE.equals(ns.getBoolean("notify-self"));
116 final var isNoteToSelf = Boolean.TRUE.equals(ns.getBoolean("note-to-self"));
117 final var recipientStrings = ns.<String>getList("recipient");
118 final var groupIdStrings = ns.<String>getList("group-id");
119 final var usernameStrings = ns.<String>getList("username");
120
121 final var recipientIdentifiers = CommandUtil.getRecipientIdentifiers(m,
122 isNoteToSelf,
123 recipientStrings,
124 groupIdStrings,
125 usernameStrings);
126
127 final var isEndSession = Boolean.TRUE.equals(ns.getBoolean("end-session"));
128 if (isEndSession) {
129 final var singleRecipients = recipientIdentifiers.stream()
130 .filter(r -> r instanceof RecipientIdentifier.Single)
131 .map(RecipientIdentifier.Single.class::cast)
132 .collect(Collectors.toSet());
133 if (singleRecipients.isEmpty()) {
134 throw new UserErrorException("No recipients given");
135 }
136
137 try {
138 final var results = m.sendEndSessionMessage(singleRecipients);
139 outputResult(outputWriter, results);
140 return;
141 } catch (IOException e) {
142 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
143 .getSimpleName() + ")", e);
144 }
145 }
146
147 final var stickerString = ns.getString("sticker");
148 final var sticker = stickerString == null ? null : parseSticker(stickerString);
149
150 var messageText = ns.getString("message");
151 final var readMessageFromStdin = ns.getBoolean("message-from-stdin") == Boolean.TRUE;
152 if (readMessageFromStdin) {
153 logger.debug("Reading message from stdin...");
154 try {
155 messageText = IOUtils.readAll(System.in, IOUtils.getConsoleCharset());
156 } catch (IOException e) {
157 throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
158 }
159 } else if (messageText == null) {
160 messageText = "";
161 }
162
163 var attachments = ns.<String>getList("attachment");
164 if (attachments == null) {
165 attachments = List.of();
166 }
167
168 final var selfNumber = m.getSelfNumber();
169
170 final var mentionStrings = ns.<String>getList("mention");
171 final var mentions = mentionStrings == null
172 ? List.<Message.Mention>of()
173 : parseMentions(selfNumber, mentionStrings);
174
175 final var textStyleStrings = ns.<String>getList("text-style");
176 final var textStyles = textStyleStrings == null ? List.<TextStyle>of() : parseTextStyles(textStyleStrings);
177
178 final Message.Quote quote;
179 final var quoteTimestamp = ns.getLong("quote-timestamp");
180 if (quoteTimestamp != null) {
181 final var quoteAuthor = ns.getString("quote-author");
182 if (quoteAuthor == null) {
183 throw new UserErrorException("Quote author parameter is missing");
184 }
185 final var quoteMessage = ns.getString("quote-message");
186 final var quoteMentionStrings = ns.<String>getList("quote-mention");
187 final var quoteMentions = quoteMentionStrings == null
188 ? List.<Message.Mention>of()
189 : parseMentions(selfNumber, quoteMentionStrings);
190 final var quoteTextStyleStrings = ns.<String>getList("quote-text-style");
191 final var quoteAttachmentStrings = ns.<String>getList("quote-attachment");
192 final var quoteTextStyles = quoteTextStyleStrings == null
193 ? List.<TextStyle>of()
194 : parseTextStyles(quoteTextStyleStrings);
195 final var quoteAttachments = quoteAttachmentStrings == null
196 ? List.<Message.Quote.Attachment>of()
197 : parseQuoteAttachments(quoteAttachmentStrings);
198 quote = new Message.Quote(quoteTimestamp,
199 CommandUtil.getSingleRecipientIdentifier(quoteAuthor, selfNumber),
200 quoteMessage == null ? "" : quoteMessage,
201 quoteMentions,
202 quoteTextStyles,
203 quoteAttachments);
204 } else {
205 quote = null;
206 }
207
208 final List<Message.Preview> previews;
209 final var previewUrl = ns.getString("preview-url");
210 if (previewUrl != null) {
211 final var previewTitle = ns.getString("preview-title");
212 final var previewDescription = ns.getString("preview-description");
213 final var previewImage = ns.getString("preview-image");
214 previews = List.of(new Message.Preview(previewUrl,
215 Optional.ofNullable(previewTitle).orElse(""),
216 Optional.ofNullable(previewDescription).orElse(""),
217 Optional.ofNullable(previewImage)));
218 } else {
219 previews = List.of();
220 }
221
222 final Message.StoryReply storyReply;
223 final var storyReplyTimestamp = ns.getLong("story-timestamp");
224 if (storyReplyTimestamp != null) {
225 final var storyAuthor = ns.getString("story-author");
226 storyReply = new Message.StoryReply(storyReplyTimestamp,
227 CommandUtil.getSingleRecipientIdentifier(storyAuthor, selfNumber));
228 } else {
229 storyReply = null;
230 }
231
232 if (messageText.isEmpty() && attachments.isEmpty() && sticker == null && quote == null) {
233 throw new UserErrorException(
234 "Sending empty message is not allowed, either a message, attachment or sticker must be given.");
235 }
236
237 final var editTimestamp = ns.getLong("edit-timestamp");
238
239 try {
240 final var message = new Message(messageText,
241 attachments,
242 mentions,
243 Optional.ofNullable(quote),
244 Optional.ofNullable(sticker),
245 previews,
246 Optional.ofNullable((storyReply)),
247 textStyles);
248 var results = editTimestamp != null
249 ? m.sendEditMessage(message, recipientIdentifiers, editTimestamp)
250 : m.sendMessage(message, recipientIdentifiers, notifySelf);
251 outputResult(outputWriter, results);
252 } catch (AttachmentInvalidException | IOException e) {
253 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
254 .getSimpleName() + ")", e);
255 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
256 throw new UserErrorException(e.getMessage());
257 } catch (UnregisteredRecipientException e) {
258 throw new UserErrorException("The user " + e.getSender().getIdentifier() + " is not registered.");
259 } catch (InvalidStickerException e) {
260 throw new UserErrorException("Failed to send sticker: " + e.getMessage(), e);
261 }
262 }
263
264 private List<Message.Mention> parseMentions(
265 final String selfNumber,
266 final List<String> mentionStrings
267 ) throws UserErrorException {
268 final var mentionPattern = Pattern.compile("(\\d+):(\\d+):(.+)");
269 final var mentions = new ArrayList<Message.Mention>();
270 for (final var mention : mentionStrings) {
271 final var matcher = mentionPattern.matcher(mention);
272 if (!matcher.matches()) {
273 throw new UserErrorException("Invalid mention syntax ("
274 + mention
275 + ") expected 'start:length:recipientNumber'");
276 }
277 mentions.add(new Message.Mention(CommandUtil.getSingleRecipientIdentifier(matcher.group(3), selfNumber),
278 Integer.parseInt(matcher.group(1)),
279 Integer.parseInt(matcher.group(2))));
280 }
281 return mentions;
282 }
283
284 private List<TextStyle> parseTextStyles(
285 final List<String> textStylesStrings
286 ) throws UserErrorException {
287 final var textStylePattern = Pattern.compile("(\\d+):(\\d+):(.+)");
288 final var textStyles = new ArrayList<TextStyle>();
289 for (final var textStyle : textStylesStrings) {
290 final var matcher = textStylePattern.matcher(textStyle);
291 if (!matcher.matches()) {
292 throw new UserErrorException("Invalid textStyle syntax ("
293 + textStyle
294 + ") expected 'start:length:STYLE'");
295 }
296 final var style = TextStyle.Style.from(matcher.group(3));
297 if (style == null) {
298 throw new UserErrorException("Invalid style: " + matcher.group(3));
299 }
300 textStyles.add(new TextStyle(style,
301 Integer.parseInt(matcher.group(1)),
302 Integer.parseInt(matcher.group(2))));
303 }
304 return textStyles;
305 }
306
307 private Message.Sticker parseSticker(final String stickerString) throws UserErrorException {
308 final var stickerPattern = Pattern.compile("([\\da-f]+):(\\d+)");
309 final var matcher = stickerPattern.matcher(stickerString);
310 if (!matcher.matches() || matcher.group(1).length() % 2 != 0) {
311 throw new UserErrorException("Invalid sticker syntax ("
312 + stickerString
313 + ") expected 'stickerPackId:stickerId'");
314 }
315 return new Message.Sticker(Hex.toByteArray(matcher.group(1)), Integer.parseInt(matcher.group(2)));
316 }
317
318 private List<Message.Quote.Attachment> parseQuoteAttachments(
319 final List<String> attachmentStrings
320 ) throws UserErrorException {
321 final var attachmentPattern = Pattern.compile("([^:]+)(:([^:]+)(:(.+))?)?");
322 final var attachments = new ArrayList<Message.Quote.Attachment>();
323 for (final var attachment : attachmentStrings) {
324 final var matcher = attachmentPattern.matcher(attachment);
325 if (!matcher.matches()) {
326 throw new UserErrorException("Invalid attachment syntax ("
327 + attachment
328 + ") expected 'contentType[:filename[:previewFile]]'");
329 }
330 attachments.add(new Message.Quote.Attachment(matcher.group(1), matcher.group(3), matcher.group(5)));
331 }
332 return attachments;
333 }
334 }