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