]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/SendCommand.java
Show better error message when sending fails due to missing pre keys
[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 if (e instanceof IOException io && io.getMessage().contains("No prekeys available")) {
254 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
255 .getSimpleName() + "), maybe one of the devices of the recipient wasn't online for a while.",
256 e);
257 } else {
258 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
259 .getSimpleName() + ")", e);
260 }
261 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
262 throw new UserErrorException(e.getMessage());
263 } catch (UnregisteredRecipientException e) {
264 throw new UserErrorException("The user " + e.getSender().getIdentifier() + " is not registered.");
265 } catch (InvalidStickerException e) {
266 throw new UserErrorException("Failed to send sticker: " + e.getMessage(), e);
267 }
268 }
269
270 private List<Message.Mention> parseMentions(
271 final String selfNumber,
272 final List<String> mentionStrings
273 ) throws UserErrorException {
274 final var mentionPattern = Pattern.compile("(\\d+):(\\d+):(.+)");
275 final var mentions = new ArrayList<Message.Mention>();
276 for (final var mention : mentionStrings) {
277 final var matcher = mentionPattern.matcher(mention);
278 if (!matcher.matches()) {
279 throw new UserErrorException("Invalid mention syntax ("
280 + mention
281 + ") expected 'start:length:recipientNumber'");
282 }
283 mentions.add(new Message.Mention(CommandUtil.getSingleRecipientIdentifier(matcher.group(3), selfNumber),
284 Integer.parseInt(matcher.group(1)),
285 Integer.parseInt(matcher.group(2))));
286 }
287 return mentions;
288 }
289
290 private List<TextStyle> parseTextStyles(
291 final List<String> textStylesStrings
292 ) throws UserErrorException {
293 final var textStylePattern = Pattern.compile("(\\d+):(\\d+):(.+)");
294 final var textStyles = new ArrayList<TextStyle>();
295 for (final var textStyle : textStylesStrings) {
296 final var matcher = textStylePattern.matcher(textStyle);
297 if (!matcher.matches()) {
298 throw new UserErrorException("Invalid textStyle syntax ("
299 + textStyle
300 + ") expected 'start:length:STYLE'");
301 }
302 final var style = TextStyle.Style.from(matcher.group(3));
303 if (style == null) {
304 throw new UserErrorException("Invalid style: " + matcher.group(3));
305 }
306 textStyles.add(new TextStyle(style,
307 Integer.parseInt(matcher.group(1)),
308 Integer.parseInt(matcher.group(2))));
309 }
310 return textStyles;
311 }
312
313 private Message.Sticker parseSticker(final String stickerString) throws UserErrorException {
314 final var stickerPattern = Pattern.compile("([\\da-f]+):(\\d+)");
315 final var matcher = stickerPattern.matcher(stickerString);
316 if (!matcher.matches() || matcher.group(1).length() % 2 != 0) {
317 throw new UserErrorException("Invalid sticker syntax ("
318 + stickerString
319 + ") expected 'stickerPackId:stickerId'");
320 }
321 return new Message.Sticker(Hex.toByteArray(matcher.group(1)), Integer.parseInt(matcher.group(2)));
322 }
323
324 private List<Message.Quote.Attachment> parseQuoteAttachments(
325 final List<String> attachmentStrings
326 ) throws UserErrorException {
327 final var attachmentPattern = Pattern.compile("([^:]+)(:([^:]+)(:(.+))?)?");
328 final var attachments = new ArrayList<Message.Quote.Attachment>();
329 for (final var attachment : attachmentStrings) {
330 final var matcher = attachmentPattern.matcher(attachment);
331 if (!matcher.matches()) {
332 throw new UserErrorException("Invalid attachment syntax ("
333 + attachment
334 + ") expected 'contentType[:filename[:previewFile]]'");
335 }
336 attachments.add(new Message.Quote.Attachment(matcher.group(1), matcher.group(3), matcher.group(5)));
337 }
338 return attachments;
339 }
340 }