]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/SendCommand.java
2a47ab8d0794d4d9e5212f56536290fdbad8f305
[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.UnregisteredRecipientException;
16 import org.asamk.signal.manager.groups.GroupNotFoundException;
17 import org.asamk.signal.manager.groups.GroupSendingNotAllowedException;
18 import org.asamk.signal.manager.groups.NotAGroupMemberException;
19 import org.asamk.signal.output.OutputWriter;
20 import org.asamk.signal.util.CommandUtil;
21 import org.asamk.signal.util.Hex;
22 import org.asamk.signal.util.IOUtils;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Optional;
30 import java.util.regex.Pattern;
31 import java.util.stream.Collectors;
32
33 import static org.asamk.signal.util.SendMessageResultUtils.outputResult;
34
35 public class SendCommand implements JsonRpcLocalCommand {
36
37 private final static Logger logger = LoggerFactory.getLogger(SendCommand.class);
38
39 @Override
40 public String getName() {
41 return "send";
42 }
43
44 @Override
45 public void attachToSubparser(final Subparser subparser) {
46 subparser.help("Send a message to another user or group.");
47 subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
48 subparser.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.").nargs("*");
49 subparser.addArgument("--note-to-self")
50 .help("Send the message to self without notification.")
51 .action(Arguments.storeTrue());
52
53 var mut = subparser.addMutuallyExclusiveGroup();
54 mut.addArgument("-m", "--message").help("Specify the message to be sent.");
55 mut.addArgument("--message-from-stdin")
56 .action(Arguments.storeTrue())
57 .help("Read the message from standard input.");
58 subparser.addArgument("-a", "--attachment")
59 .nargs("*")
60 .help("Add an attachment. "
61 + "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. "
62 + "data:<MIME-TYPE>;filename=<FILENAME>;base64,<BASE64 ENCODED DATA>.");
63 subparser.addArgument("-e", "--end-session", "--endsession")
64 .help("Clear session state and send end session message.")
65 .action(Arguments.storeTrue());
66 subparser.addArgument("--mention")
67 .nargs("*")
68 .help("Mention another group member (syntax: start:length:recipientNumber)");
69 subparser.addArgument("--quote-timestamp")
70 .type(long.class)
71 .help("Specify the timestamp of a previous message with the recipient or group to add a quote to the new message.");
72 subparser.addArgument("--quote-author").help("Specify the number of the author of the original message.");
73 subparser.addArgument("--quote-message").help("Specify the message of the original message.");
74 subparser.addArgument("--quote-mention")
75 .nargs("*")
76 .help("Quote with mention of another group member (syntax: start:length:recipientNumber)");
77 subparser.addArgument("--sticker").help("Send a sticker (syntax: stickerPackId:stickerId)");
78 subparser.addArgument("--preview-url")
79 .help("Specify the url for the link preview (the same url must also appear in the message body).");
80 subparser.addArgument("--preview-title").help("Specify the title for the link preview (mandatory).");
81 subparser.addArgument("--preview-description").help("Specify the description for the link preview (optional).");
82 subparser.addArgument("--preview-image").help("Specify the image file for the link preview (optional).");
83 subparser.addArgument("--story-timestamp")
84 .type(long.class)
85 .help("Specify the timestamp of a story to reply to.");
86 subparser.addArgument("--story-author").help("Specify the number of the author of the story.");
87 }
88
89 @Override
90 public void handleCommand(
91 final Namespace ns, final Manager m, final OutputWriter outputWriter
92 ) throws CommandException {
93 final var isNoteToSelf = Boolean.TRUE.equals(ns.getBoolean("note-to-self"));
94 final var recipientStrings = ns.<String>getList("recipient");
95 final var groupIdStrings = ns.<String>getList("group-id");
96
97 final var recipientIdentifiers = CommandUtil.getRecipientIdentifiers(m,
98 isNoteToSelf,
99 recipientStrings,
100 groupIdStrings);
101
102 final var isEndSession = Boolean.TRUE.equals(ns.getBoolean("end-session"));
103 if (isEndSession) {
104 final var singleRecipients = recipientIdentifiers.stream()
105 .filter(r -> r instanceof RecipientIdentifier.Single)
106 .map(RecipientIdentifier.Single.class::cast)
107 .collect(Collectors.toSet());
108 if (singleRecipients.isEmpty()) {
109 throw new UserErrorException("No recipients given");
110 }
111
112 try {
113 final var results = m.sendEndSessionMessage(singleRecipients);
114 outputResult(outputWriter, results);
115 return;
116 } catch (IOException e) {
117 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
118 .getSimpleName() + ")", e);
119 }
120 }
121
122 final var stickerString = ns.getString("sticker");
123 final var sticker = stickerString == null ? null : parseSticker(stickerString);
124
125 var messageText = ns.getString("message");
126 final var readMessageFromStdin = ns.getBoolean("message-from-stdin") == Boolean.TRUE;
127 if (readMessageFromStdin) {
128 logger.debug("Reading message from stdin...");
129 try {
130 messageText = IOUtils.readAll(System.in, IOUtils.getConsoleCharset());
131 } catch (IOException e) {
132 throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
133 }
134 } else if (messageText == null) {
135 messageText = "";
136 }
137
138 List<String> attachments = ns.getList("attachment");
139 if (attachments == null) {
140 attachments = List.of();
141 }
142
143 List<String> mentionStrings = ns.getList("mention");
144 final var mentions = mentionStrings == null ? List.<Message.Mention>of() : parseMentions(m, mentionStrings);
145
146 final Message.Quote quote;
147 final var quoteTimestamp = ns.getLong("quote-timestamp");
148 if (quoteTimestamp != null) {
149 final var quoteAuthor = ns.getString("quote-author");
150 final var quoteMessage = ns.getString("quote-message");
151 List<String> quoteMentionStrings = ns.getList("quote-mention");
152 final var quoteMentions = quoteMentionStrings == null
153 ? List.<Message.Mention>of()
154 : parseMentions(m, quoteMentionStrings);
155 quote = new Message.Quote(quoteTimestamp,
156 CommandUtil.getSingleRecipientIdentifier(quoteAuthor, m.getSelfNumber()),
157 quoteMessage == null ? "" : quoteMessage,
158 quoteMentions);
159 } else {
160 quote = null;
161 }
162
163 final List<Message.Preview> previews;
164 String previewUrl = ns.getString("preview-url");
165 if (previewUrl != null) {
166 String previewTitle = ns.getString("preview-title");
167 String previewDescription = ns.getString("preview-description");
168 String previewImage = ns.getString("preview-image");
169 previews = List.of(new Message.Preview(previewUrl,
170 Optional.ofNullable(previewTitle).orElse(""),
171 Optional.ofNullable(previewDescription).orElse(""),
172 Optional.ofNullable(previewImage)));
173 } else {
174 previews = List.of();
175 }
176
177 final Message.StoryReply storyReply;
178 final var storyReplyTimestamp = ns.getLong("story-timestamp");
179 if (storyReplyTimestamp != null) {
180 final var storyAuthor = ns.getString("story-author");
181 storyReply = new Message.StoryReply(storyReplyTimestamp,
182 CommandUtil.getSingleRecipientIdentifier(storyAuthor, m.getSelfNumber()));
183 } else {
184 storyReply = null;
185 }
186
187 if (messageText.isEmpty() && attachments.isEmpty() && sticker == null && quote == null) {
188 throw new UserErrorException(
189 "Sending empty message is not allowed, either a message, attachment or sticker must be given.");
190 }
191
192 try {
193 final var message = new Message(messageText,
194 attachments,
195 mentions,
196 Optional.ofNullable(quote),
197 Optional.ofNullable(sticker),
198 previews,
199 Optional.ofNullable((storyReply)));
200 var results = m.sendMessage(message, recipientIdentifiers);
201 outputResult(outputWriter, results);
202 } catch (AttachmentInvalidException | IOException e) {
203 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
204 .getSimpleName() + ")", e);
205 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
206 throw new UserErrorException(e.getMessage());
207 } catch (UnregisteredRecipientException e) {
208 throw new UserErrorException("The user " + e.getSender().getIdentifier() + " is not registered.");
209 } catch (InvalidStickerException e) {
210 throw new UserErrorException("Failed to send sticker: " + e.getMessage(), e);
211 }
212 }
213
214 private List<Message.Mention> parseMentions(
215 final Manager m, final List<String> mentionStrings
216 ) throws UserErrorException {
217 List<Message.Mention> mentions;
218 final Pattern mentionPattern = Pattern.compile("(\\d+):(\\d+):(.+)");
219 mentions = new ArrayList<>();
220 for (final var mention : mentionStrings) {
221 final var matcher = mentionPattern.matcher(mention);
222 if (!matcher.matches()) {
223 throw new UserErrorException("Invalid mention syntax ("
224 + mention
225 + ") expected 'start:end:recipientNumber'");
226 }
227 mentions.add(new Message.Mention(CommandUtil.getSingleRecipientIdentifier(matcher.group(3),
228 m.getSelfNumber()), Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2))));
229 }
230 return mentions;
231 }
232
233 private Message.Sticker parseSticker(final String stickerString) throws UserErrorException {
234 final Pattern stickerPattern = Pattern.compile("([\\da-f]+):(\\d+)");
235 final var matcher = stickerPattern.matcher(stickerString);
236 if (!matcher.matches() || matcher.group(1).length() % 2 != 0) {
237 throw new UserErrorException("Invalid sticker syntax ("
238 + stickerString
239 + ") expected 'stickerPackId:stickerId'");
240 }
241 return new Message.Sticker(Hex.toByteArray(matcher.group(1)), Integer.parseInt(matcher.group(2)));
242 }
243 }