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