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