]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/SendCommand.java
Add verbose logging for decryption errors of incoming messages
[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.Message;
13 import org.asamk.signal.manager.api.RecipientIdentifier;
14 import org.asamk.signal.manager.api.UnregisteredRecipientException;
15 import org.asamk.signal.manager.groups.GroupNotFoundException;
16 import org.asamk.signal.manager.groups.GroupSendingNotAllowedException;
17 import org.asamk.signal.manager.groups.NotAGroupMemberException;
18 import org.asamk.signal.output.OutputWriter;
19 import org.asamk.signal.util.CommandUtil;
20 import org.asamk.signal.util.IOUtils;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 import java.io.IOException;
25 import java.nio.charset.Charset;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.regex.Pattern;
30 import java.util.stream.Collectors;
31
32 import static org.asamk.signal.util.SendMessageResultUtils.outputResult;
33
34 public class SendCommand implements JsonRpcLocalCommand {
35
36 private final static Logger logger = LoggerFactory.getLogger(SendCommand.class);
37
38 @Override
39 public String getName() {
40 return "send";
41 }
42
43 @Override
44 public void attachToSubparser(final Subparser subparser) {
45 subparser.help("Send a message to another user or group.");
46 subparser.addArgument("recipient").help("Specify the recipients' phone number.").nargs("*");
47 subparser.addArgument("-g", "--group-id", "--group").help("Specify the recipient group ID.").nargs("*");
48 subparser.addArgument("--note-to-self")
49 .help("Send the message to self without notification.")
50 .action(Arguments.storeTrue());
51
52 subparser.addArgument("-m", "--message").help("Specify the message, if missing standard input is used.");
53 subparser.addArgument("-a", "--attachment").nargs("*").help("Add file as attachment");
54 subparser.addArgument("-e", "--end-session", "--endsession")
55 .help("Clear session state and send end session message.")
56 .action(Arguments.storeTrue());
57 subparser.addArgument("--mention")
58 .nargs("*")
59 .help("Mention another group member (syntax: start:length:recipientNumber)");
60 subparser.addArgument("--quote-timestamp")
61 .type(long.class)
62 .help("Specify the timestamp of a previous message with the recipient or group to add a quote to the new message.");
63 subparser.addArgument("--quote-author").help("Specify the number of the author of the original message.");
64 subparser.addArgument("--quote-message").help("Specify the message of the original message.");
65 subparser.addArgument("--quote-mention")
66 .nargs("*")
67 .help("Quote with mention of another group member (syntax: start:length:recipientNumber)");
68 }
69
70 @Override
71 public void handleCommand(
72 final Namespace ns, final Manager m, final OutputWriter outputWriter
73 ) throws CommandException {
74 final var isNoteToSelf = Boolean.TRUE.equals(ns.getBoolean("note-to-self"));
75 final var recipientStrings = ns.<String>getList("recipient");
76 final var groupIdStrings = ns.<String>getList("group-id");
77
78 final var recipientIdentifiers = CommandUtil.getRecipientIdentifiers(m,
79 isNoteToSelf,
80 recipientStrings,
81 groupIdStrings);
82
83 final var isEndSession = Boolean.TRUE.equals(ns.getBoolean("end-session"));
84 if (isEndSession) {
85 final var singleRecipients = recipientIdentifiers.stream()
86 .filter(r -> r instanceof RecipientIdentifier.Single)
87 .map(RecipientIdentifier.Single.class::cast)
88 .collect(Collectors.toSet());
89 if (singleRecipients.isEmpty()) {
90 throw new UserErrorException("No recipients given");
91 }
92
93 try {
94 final var results = m.sendEndSessionMessage(singleRecipients);
95 outputResult(outputWriter, results);
96 return;
97 } catch (IOException e) {
98 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
99 .getSimpleName() + ")", e);
100 }
101 }
102
103 var messageText = ns.getString("message");
104 if (messageText == null) {
105 logger.debug("Reading message from stdin...");
106 try {
107 messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
108 } catch (IOException e) {
109 throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
110 }
111 }
112
113 List<String> attachments = ns.getList("attachment");
114 if (attachments == null) {
115 attachments = List.of();
116 }
117
118 List<String> mentionStrings = ns.getList("mention");
119 final var mentions = mentionStrings == null ? List.<Message.Mention>of() : parseMentions(m, mentionStrings);
120
121 final Message.Quote quote;
122 final var quoteTimestamp = ns.getLong("quote-timestamp");
123 if (quoteTimestamp != null) {
124 final var quoteAuthor = ns.getString("quote-author");
125 final var quoteMessage = ns.getString("quote-message");
126 List<String> quoteMentionStrings = ns.getList("quote-mention");
127 final var quoteMentions = quoteMentionStrings == null
128 ? List.<Message.Mention>of()
129 : parseMentions(m, quoteMentionStrings);
130 quote = new Message.Quote(quoteTimestamp,
131 CommandUtil.getSingleRecipientIdentifier(quoteAuthor, m.getSelfNumber()),
132 quoteMessage,
133 quoteMentions);
134 } else {
135 quote = null;
136 }
137
138 try {
139 var results = m.sendMessage(new Message(messageText, attachments, mentions, Optional.ofNullable(quote)),
140 recipientIdentifiers);
141 outputResult(outputWriter, results);
142 } catch (AttachmentInvalidException | IOException e) {
143 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
144 .getSimpleName() + ")", e);
145 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
146 throw new UserErrorException(e.getMessage());
147 } catch (UnregisteredRecipientException e) {
148 throw new UserErrorException("The user " + e.getSender().getIdentifier() + " is not registered.");
149 }
150 }
151
152 private List<Message.Mention> parseMentions(
153 final Manager m, final List<String> mentionStrings
154 ) throws UserErrorException {
155 List<Message.Mention> mentions;
156 final Pattern mentionPattern = Pattern.compile("([0-9]+):([0-9]+):(.+)");
157 mentions = new ArrayList<>();
158 for (final var mention : mentionStrings) {
159 final var matcher = mentionPattern.matcher(mention);
160 if (!matcher.matches()) {
161 throw new UserErrorException("Invalid mention syntax ("
162 + mention
163 + ") expected 'start:end:recipientNumber'");
164 }
165 mentions.add(new Message.Mention(CommandUtil.getSingleRecipientIdentifier(matcher.group(3),
166 m.getSelfNumber()), Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2))));
167 }
168 return mentions;
169 }
170 }