]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/SendCommand.java
Use console charset for reading/writing to stdin/out
[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").nargs("*").help("Add file as attachment");
59 subparser.addArgument("-e", "--end-session", "--endsession")
60 .help("Clear session state and send end session message.")
61 .action(Arguments.storeTrue());
62 subparser.addArgument("--mention")
63 .nargs("*")
64 .help("Mention another group member (syntax: start:length:recipientNumber)");
65 subparser.addArgument("--quote-timestamp")
66 .type(long.class)
67 .help("Specify the timestamp of a previous message with the recipient or group to add a quote to the new message.");
68 subparser.addArgument("--quote-author").help("Specify the number of the author of the original message.");
69 subparser.addArgument("--quote-message").help("Specify the message of the original message.");
70 subparser.addArgument("--quote-mention")
71 .nargs("*")
72 .help("Quote with mention of another group member (syntax: start:length:recipientNumber)");
73 subparser.addArgument("--sticker").help("Send a sticker (syntax: stickerPackId:stickerId)");
74 subparser.addArgument("--preview-url")
75 .help("Specify the url for the link preview (the same url must also appear in the message body).");
76 subparser.addArgument("--preview-title").help("Specify the title for the link preview (mandatory).");
77 subparser.addArgument("--preview-description").help("Specify the description for the link preview (optional).");
78 subparser.addArgument("--preview-image").help("Specify the image file for the link preview (optional).");
79 }
80
81 @Override
82 public void handleCommand(
83 final Namespace ns, final Manager m, final OutputWriter outputWriter
84 ) throws CommandException {
85 final var isNoteToSelf = Boolean.TRUE.equals(ns.getBoolean("note-to-self"));
86 final var recipientStrings = ns.<String>getList("recipient");
87 final var groupIdStrings = ns.<String>getList("group-id");
88
89 final var recipientIdentifiers = CommandUtil.getRecipientIdentifiers(m,
90 isNoteToSelf,
91 recipientStrings,
92 groupIdStrings);
93
94 final var isEndSession = Boolean.TRUE.equals(ns.getBoolean("end-session"));
95 if (isEndSession) {
96 final var singleRecipients = recipientIdentifiers.stream()
97 .filter(r -> r instanceof RecipientIdentifier.Single)
98 .map(RecipientIdentifier.Single.class::cast)
99 .collect(Collectors.toSet());
100 if (singleRecipients.isEmpty()) {
101 throw new UserErrorException("No recipients given");
102 }
103
104 try {
105 final var results = m.sendEndSessionMessage(singleRecipients);
106 outputResult(outputWriter, results);
107 return;
108 } catch (IOException e) {
109 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
110 .getSimpleName() + ")", e);
111 }
112 }
113
114 final var stickerString = ns.getString("sticker");
115 final var sticker = stickerString == null ? null : parseSticker(stickerString);
116
117 var messageText = ns.getString("message");
118 final var readMessageFromStdin = ns.getBoolean("message-from-stdin") == Boolean.TRUE;
119 if (readMessageFromStdin || (messageText == null && sticker == null)) {
120 logger.debug("Reading message from stdin...");
121 try {
122 messageText = IOUtils.readAll(System.in, IOUtils.getConsoleCharset());
123 } catch (IOException e) {
124 throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
125 }
126 }
127
128 List<String> attachments = ns.getList("attachment");
129 if (attachments == null) {
130 attachments = List.of();
131 }
132
133 List<String> mentionStrings = ns.getList("mention");
134 final var mentions = mentionStrings == null ? List.<Message.Mention>of() : parseMentions(m, mentionStrings);
135
136 final Message.Quote quote;
137 final var quoteTimestamp = ns.getLong("quote-timestamp");
138 if (quoteTimestamp != null) {
139 final var quoteAuthor = ns.getString("quote-author");
140 final var quoteMessage = ns.getString("quote-message");
141 List<String> quoteMentionStrings = ns.getList("quote-mention");
142 final var quoteMentions = quoteMentionStrings == null
143 ? List.<Message.Mention>of()
144 : parseMentions(m, quoteMentionStrings);
145 quote = new Message.Quote(quoteTimestamp,
146 CommandUtil.getSingleRecipientIdentifier(quoteAuthor, m.getSelfNumber()),
147 quoteMessage == null ? "" : quoteMessage,
148 quoteMentions);
149 } else {
150 quote = null;
151 }
152
153 final List<Message.Preview> previews;
154 String previewUrl = ns.getString("preview-url");
155 if (previewUrl != null) {
156 String previewTitle = ns.getString("preview-title");
157 String previewDescription = ns.getString("preview-description");
158 String previewImage = ns.getString("preview-image");
159 previews = List.of(new Message.Preview(previewUrl,
160 Optional.ofNullable(previewTitle).orElse(""),
161 Optional.ofNullable(previewDescription).orElse(""),
162 Optional.ofNullable(previewImage)));
163 } else {
164 previews = List.of();
165 }
166
167 try {
168 var results = m.sendMessage(new Message(messageText == null ? "" : messageText,
169 attachments,
170 mentions,
171 Optional.ofNullable(quote),
172 Optional.ofNullable(sticker),
173 previews), recipientIdentifiers);
174 outputResult(outputWriter, results);
175 } catch (AttachmentInvalidException | IOException e) {
176 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
177 .getSimpleName() + ")", e);
178 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
179 throw new UserErrorException(e.getMessage());
180 } catch (UnregisteredRecipientException e) {
181 throw new UserErrorException("The user " + e.getSender().getIdentifier() + " is not registered.");
182 } catch (InvalidStickerException e) {
183 throw new UserErrorException("Failed to send sticker: " + e.getMessage(), e);
184 }
185 }
186
187 private List<Message.Mention> parseMentions(
188 final Manager m, final List<String> mentionStrings
189 ) throws UserErrorException {
190 List<Message.Mention> mentions;
191 final Pattern mentionPattern = Pattern.compile("(\\d+):(\\d+):(.+)");
192 mentions = new ArrayList<>();
193 for (final var mention : mentionStrings) {
194 final var matcher = mentionPattern.matcher(mention);
195 if (!matcher.matches()) {
196 throw new UserErrorException("Invalid mention syntax ("
197 + mention
198 + ") expected 'start:end:recipientNumber'");
199 }
200 mentions.add(new Message.Mention(CommandUtil.getSingleRecipientIdentifier(matcher.group(3),
201 m.getSelfNumber()), Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2))));
202 }
203 return mentions;
204 }
205
206 private Message.Sticker parseSticker(final String stickerString) throws UserErrorException {
207 final Pattern stickerPattern = Pattern.compile("([\\da-f]+):(\\d+)");
208 final var matcher = stickerPattern.matcher(stickerString);
209 if (!matcher.matches() || matcher.group(1).length() % 2 != 0) {
210 throw new UserErrorException("Invalid sticker syntax ("
211 + stickerString
212 + ") expected 'stickerPackId:stickerId'");
213 }
214 return new Message.Sticker(Hex.toByteArray(matcher.group(1)), Integer.parseInt(matcher.group(2)));
215 }
216 }