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