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