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