]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/SendCommand.java
Print stack trace of exception causes in verbose mode
[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;
8 import org.asamk.signal.JsonWriter;
9 import org.asamk.signal.OutputWriter;
10 import org.asamk.signal.PlainTextWriter;
11 import org.asamk.signal.commands.exceptions.CommandException;
12 import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
13 import org.asamk.signal.commands.exceptions.UntrustedKeyErrorException;
14 import org.asamk.signal.commands.exceptions.UserErrorException;
15 import org.asamk.signal.manager.AttachmentInvalidException;
16 import org.asamk.signal.manager.Manager;
17 import org.asamk.signal.manager.api.Message;
18 import org.asamk.signal.manager.api.RecipientIdentifier;
19 import org.asamk.signal.manager.groups.GroupNotFoundException;
20 import org.asamk.signal.manager.groups.GroupSendingNotAllowedException;
21 import org.asamk.signal.manager.groups.NotAGroupMemberException;
22 import org.asamk.signal.util.CommandUtil;
23 import org.asamk.signal.util.ErrorUtils;
24 import org.asamk.signal.util.IOUtils;
25 import org.freedesktop.dbus.errors.UnknownObject;
26 import org.freedesktop.dbus.exceptions.DBusExecutionException;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 import java.io.IOException;
31 import java.nio.charset.Charset;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.stream.Collectors;
35
36 public class SendCommand implements DbusCommand, 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 }
60
61 @Override
62 public void handleCommand(
63 final Namespace ns, final Manager m, final OutputWriter outputWriter
64 ) throws CommandException {
65 final var isNoteToSelf = ns.getBoolean("note-to-self");
66 final var recipientStrings = ns.<String>getList("recipient");
67 final var groupIdStrings = ns.<String>getList("group-id");
68
69 final var recipientIdentifiers = CommandUtil.getRecipientIdentifiers(m,
70 isNoteToSelf,
71 recipientStrings,
72 groupIdStrings);
73
74 final var isEndSession = ns.getBoolean("end-session");
75 if (isEndSession) {
76 final var singleRecipients = recipientIdentifiers.stream()
77 .filter(r -> r instanceof RecipientIdentifier.Single)
78 .map(RecipientIdentifier.Single.class::cast)
79 .collect(Collectors.toSet());
80 if (singleRecipients.isEmpty()) {
81 throw new UserErrorException("No recipients given");
82 }
83
84 try {
85 m.sendEndSessionMessage(singleRecipients);
86 return;
87 } catch (IOException e) {
88 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
89 .getSimpleName() + ")", e);
90 }
91 }
92
93 var messageText = ns.getString("message");
94 if (messageText == null) {
95 try {
96 messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
97 } catch (IOException e) {
98 throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
99 }
100 }
101
102 List<String> attachments = ns.getList("attachment");
103 if (attachments == null) {
104 attachments = List.of();
105 }
106
107 try {
108 var results = m.sendMessage(new Message(messageText, attachments), recipientIdentifiers);
109 outputResult(outputWriter, results.getTimestamp());
110 ErrorUtils.handleSendMessageResults(results.getResults());
111 } catch (AttachmentInvalidException | IOException e) {
112 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
113 .getSimpleName() + ")", e);
114 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
115 throw new UserErrorException(e.getMessage());
116 }
117 }
118
119 @Override
120 public void handleCommand(
121 final Namespace ns, final Signal signal, final OutputWriter outputWriter
122 ) throws CommandException {
123 final var recipients = ns.<String>getList("recipient");
124 final var isEndSession = ns.getBoolean("end-session");
125 final var groupIdStrings = ns.<String>getList("group-id");
126 final var isNoteToSelf = ns.getBoolean("note-to-self");
127
128 final var noRecipients = recipients == null || recipients.isEmpty();
129 final var noGroups = groupIdStrings == null || groupIdStrings.isEmpty();
130 if ((noRecipients && isEndSession) || (noRecipients && noGroups && !isNoteToSelf)) {
131 throw new UserErrorException("No recipients given");
132 }
133 if (!noRecipients && !noGroups) {
134 throw new UserErrorException("You cannot specify recipients by phone number and groups at the same time");
135 }
136 if (!noRecipients && isNoteToSelf) {
137 throw new UserErrorException(
138 "You cannot specify recipients by phone number and note to self at the same time");
139 }
140
141 if (isEndSession) {
142 try {
143 signal.sendEndSessionMessage(recipients);
144 return;
145 } catch (Signal.Error.UntrustedIdentity e) {
146 throw new UntrustedKeyErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
147 .getSimpleName() + ")");
148 } catch (DBusExecutionException e) {
149 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
150 .getSimpleName() + ")", e);
151 }
152 }
153
154 var messageText = ns.getString("message");
155 if (messageText == null) {
156 try {
157 messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
158 } catch (IOException e) {
159 throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
160 }
161 }
162
163 List<String> attachments = ns.getList("attachment");
164 if (attachments == null) {
165 attachments = List.of();
166 }
167
168 if (!noGroups) {
169 final var groupIds = CommandUtil.getGroupIds(groupIdStrings);
170
171 try {
172 long timestamp = 0;
173 for (final var groupId : groupIds) {
174 timestamp = signal.sendGroupMessage(messageText, attachments, groupId.serialize());
175 }
176 outputResult(outputWriter, timestamp);
177 return;
178 } catch (DBusExecutionException e) {
179 throw new UnexpectedErrorException("Failed to send group message: " + e.getMessage(), e);
180 }
181 }
182
183 if (isNoteToSelf) {
184 try {
185 var timestamp = signal.sendNoteToSelfMessage(messageText, attachments);
186 outputResult(outputWriter, timestamp);
187 return;
188 } catch (Signal.Error.UntrustedIdentity e) {
189 throw new UntrustedKeyErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
190 .getSimpleName() + ")");
191 } catch (DBusExecutionException e) {
192 throw new UnexpectedErrorException("Failed to send note to self message: " + e.getMessage(), e);
193 }
194 }
195
196 try {
197 var timestamp = signal.sendMessage(messageText, attachments, recipients);
198 outputResult(outputWriter, timestamp);
199 } catch (UnknownObject e) {
200 throw new UserErrorException("Failed to find dbus object, maybe missing the -u flag: " + e.getMessage());
201 } catch (Signal.Error.UntrustedIdentity e) {
202 throw new UntrustedKeyErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
203 .getSimpleName() + ")");
204 } catch (DBusExecutionException e) {
205 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage() + " (" + e.getClass()
206 .getSimpleName() + ")", e);
207 }
208 }
209
210 private void outputResult(final OutputWriter outputWriter, final long timestamp) {
211 if (outputWriter instanceof PlainTextWriter) {
212 final var writer = (PlainTextWriter) outputWriter;
213 writer.println("{}", timestamp);
214 } else {
215 final var writer = (JsonWriter) outputWriter;
216 writer.write(Map.of("timestamp", timestamp));
217 }
218 }
219 }