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