]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/SendCommand.java
Implement textStyles for sending and receiving
[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 List<String> mentionStrings = ns.getList("mention");
154 final var mentions = mentionStrings == null ? List.<Message.Mention>of() : parseMentions(m, mentionStrings);
155
156 List<String> textStyleStrings = ns.getList("text-style");
157 final var textStyles = textStyleStrings == null ? List.<TextStyle>of() : parseTextStyles(textStyleStrings);
158
159 final Message.Quote quote;
160 final var quoteTimestamp = ns.getLong("quote-timestamp");
161 if (quoteTimestamp != null) {
162 final var quoteAuthor = ns.getString("quote-author");
163 final var quoteMessage = ns.getString("quote-message");
164 List<String> quoteMentionStrings = ns.getList("quote-mention");
165 final var quoteMentions = quoteMentionStrings == null
166 ? List.<Message.Mention>of()
167 : parseMentions(m, quoteMentionStrings);
168 List<String> quoteTextStyleStrings = ns.getList("quote-text-style");
169 final var quoteTextStyles = quoteTextStyleStrings == null
170 ? List.<TextStyle>of()
171 : parseTextStyles(quoteTextStyleStrings);
172 quote = new Message.Quote(quoteTimestamp,
173 CommandUtil.getSingleRecipientIdentifier(quoteAuthor, m.getSelfNumber()),
174 quoteMessage == null ? "" : quoteMessage,
175 quoteMentions,
176 quoteTextStyles);
177 } else {
178 quote = null;
179 }
180
181 final List<Message.Preview> previews;
182 String previewUrl = ns.getString("preview-url");
183 if (previewUrl != null) {
184 String previewTitle = ns.getString("preview-title");
185 String previewDescription = ns.getString("preview-description");
186 String previewImage = ns.getString("preview-image");
187 previews = List.of(new Message.Preview(previewUrl,
188 Optional.ofNullable(previewTitle).orElse(""),
189 Optional.ofNullable(previewDescription).orElse(""),
190 Optional.ofNullable(previewImage)));
191 } else {
192 previews = List.of();
193 }
194
195 final Message.StoryReply storyReply;
196 final var storyReplyTimestamp = ns.getLong("story-timestamp");
197 if (storyReplyTimestamp != null) {
198 final var storyAuthor = ns.getString("story-author");
199 storyReply = new Message.StoryReply(storyReplyTimestamp,
200 CommandUtil.getSingleRecipientIdentifier(storyAuthor, m.getSelfNumber()));
201 } else {
202 storyReply = null;
203 }
204
205 if (messageText.isEmpty() && attachments.isEmpty() && sticker == null && quote == null) {
206 throw new UserErrorException(
207 "Sending empty message is not allowed, either a message, attachment or sticker must be given.");
208 }
209
210 final var editTimestamp = ns.getLong("edit-timestamp");
211
212 try {
213 final var message = new Message(messageText,
214 attachments,
215 mentions,
216 Optional.ofNullable(quote),
217 Optional.ofNullable(sticker),
218 previews,
219 Optional.ofNullable((storyReply)),
220 textStyles);
221 var results = editTimestamp != null
222 ? m.sendEditMessage(message, recipientIdentifiers, editTimestamp)
223 : m.sendMessage(message, recipientIdentifiers);
224 outputResult(outputWriter, results);
225 } catch (AttachmentInvalidException | IOException e) {
226 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
227 .getSimpleName() + ")", e);
228 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
229 throw new UserErrorException(e.getMessage());
230 } catch (UnregisteredRecipientException e) {
231 throw new UserErrorException("The user " + e.getSender().getIdentifier() + " is not registered.");
232 } catch (InvalidStickerException e) {
233 throw new UserErrorException("Failed to send sticker: " + e.getMessage(), e);
234 }
235 }
236
237 private List<Message.Mention> parseMentions(
238 final Manager m, final List<String> mentionStrings
239 ) throws UserErrorException {
240 List<Message.Mention> mentions;
241 final Pattern mentionPattern = Pattern.compile("(\\d+):(\\d+):(.+)");
242 mentions = new ArrayList<>();
243 for (final var mention : mentionStrings) {
244 final var matcher = mentionPattern.matcher(mention);
245 if (!matcher.matches()) {
246 throw new UserErrorException("Invalid mention syntax ("
247 + mention
248 + ") expected 'start:end:recipientNumber'");
249 }
250 mentions.add(new Message.Mention(CommandUtil.getSingleRecipientIdentifier(matcher.group(3),
251 m.getSelfNumber()), Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2))));
252 }
253 return mentions;
254 }
255
256 private List<TextStyle> parseTextStyles(
257 final List<String> textStylesStrings
258 ) throws UserErrorException {
259 List<TextStyle> textStyles;
260 final Pattern textStylePattern = Pattern.compile("(\\d+):(\\d+):(.+)");
261 textStyles = new ArrayList<>();
262 for (final var textStyle : textStylesStrings) {
263 final var matcher = textStylePattern.matcher(textStyle);
264 if (!matcher.matches()) {
265 throw new UserErrorException("Invalid textStyle syntax ("
266 + textStyle
267 + ") expected 'start:length:STYLE'");
268 }
269 final var style = TextStyle.Style.from(matcher.group(3));
270 if (style == null) {
271 throw new UserErrorException("Invalid style: " + matcher.group(3));
272 }
273 textStyles.add(new TextStyle(style,
274 Integer.parseInt(matcher.group(1)),
275 Integer.parseInt(matcher.group(2))));
276 }
277 return textStyles;
278 }
279
280 private Message.Sticker parseSticker(final String stickerString) throws UserErrorException {
281 final Pattern stickerPattern = Pattern.compile("([\\da-f]+):(\\d+)");
282 final var matcher = stickerPattern.matcher(stickerString);
283 if (!matcher.matches() || matcher.group(1).length() % 2 != 0) {
284 throw new UserErrorException("Invalid sticker syntax ("
285 + stickerString
286 + ") expected 'stickerPackId:stickerId'");
287 }
288 return new Message.Sticker(Hex.toByteArray(matcher.group(1)), Integer.parseInt(matcher.group(2)));
289 }
290 }