]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/SendCommand.java
Extract AttachmentHelper and SyncHelper
[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());
89 }
90 }
91
92 var messageText = ns.getString("message");
93 if (messageText == null) {
94 try {
95 messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
96 } catch (IOException e) {
97 throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
98 }
99 }
100
101 List<String> attachments = ns.getList("attachment");
102 if (attachments == null) {
103 attachments = List.of();
104 }
105
106 try {
107 var results = m.sendMessage(new Message(messageText, attachments), recipientIdentifiers);
108 outputResult(outputWriter, results.getTimestamp());
109 ErrorUtils.handleSendMessageResults(results.getResults());
110 } catch (AttachmentInvalidException | IOException e) {
111 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage());
112 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
113 throw new UserErrorException(e.getMessage());
114 }
115 }
116
117 @Override
118 public void handleCommand(
119 final Namespace ns, final Signal signal, final OutputWriter outputWriter
120 ) throws CommandException {
121 final var recipients = ns.<String>getList("recipient");
122 final var isEndSession = ns.getBoolean("end-session");
123 final var groupIdStrings = ns.<String>getList("group-id");
124 final var isNoteToSelf = ns.getBoolean("note-to-self");
125
126 final var noRecipients = recipients == null || recipients.isEmpty();
127 final var noGroups = groupIdStrings == null || groupIdStrings.isEmpty();
128 if ((noRecipients && isEndSession) || (noRecipients && noGroups && !isNoteToSelf)) {
129 throw new UserErrorException("No recipients given");
130 }
131 if (!noRecipients && !noGroups) {
132 throw new UserErrorException("You cannot specify recipients by phone number and groups at the same time");
133 }
134 if (!noRecipients && isNoteToSelf) {
135 throw new UserErrorException(
136 "You cannot specify recipients by phone number and note to self at the same time");
137 }
138
139 if (isEndSession) {
140 try {
141 signal.sendEndSessionMessage(recipients);
142 return;
143 } catch (Signal.Error.UntrustedIdentity e) {
144 throw new UntrustedKeyErrorException("Failed to send message: " + e.getMessage());
145 } catch (DBusExecutionException e) {
146 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage());
147 }
148 }
149
150 var messageText = ns.getString("message");
151 if (messageText == null) {
152 try {
153 messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
154 } catch (IOException e) {
155 throw new UserErrorException("Failed to read message from stdin: " + e.getMessage());
156 }
157 }
158
159 List<String> attachments = ns.getList("attachment");
160 if (attachments == null) {
161 attachments = List.of();
162 }
163
164 if (!noGroups) {
165 final var groupIds = CommandUtil.getGroupIds(groupIdStrings);
166
167 try {
168 long timestamp = 0;
169 for (final var groupId : groupIds) {
170 timestamp = signal.sendGroupMessage(messageText, attachments, groupId.serialize());
171 }
172 outputResult(outputWriter, timestamp);
173 return;
174 } catch (DBusExecutionException e) {
175 throw new UnexpectedErrorException("Failed to send group message: " + e.getMessage());
176 }
177 }
178
179 if (isNoteToSelf) {
180 try {
181 var timestamp = signal.sendNoteToSelfMessage(messageText, attachments);
182 outputResult(outputWriter, timestamp);
183 return;
184 } catch (Signal.Error.UntrustedIdentity e) {
185 throw new UntrustedKeyErrorException("Failed to send message: " + e.getMessage());
186 } catch (DBusExecutionException e) {
187 throw new UnexpectedErrorException("Failed to send note to self message: " + e.getMessage());
188 }
189 }
190
191 try {
192 var timestamp = signal.sendMessage(messageText, attachments, recipients);
193 outputResult(outputWriter, timestamp);
194 } catch (UnknownObject e) {
195 throw new UserErrorException("Failed to find dbus object, maybe missing the -u flag: " + e.getMessage());
196 } catch (Signal.Error.UntrustedIdentity e) {
197 throw new UntrustedKeyErrorException("Failed to send message: " + e.getMessage());
198 } catch (DBusExecutionException e) {
199 throw new UnexpectedErrorException("Failed to send message: " + e.getMessage());
200 }
201 }
202
203 private void outputResult(final OutputWriter outputWriter, final long timestamp) {
204 if (outputWriter instanceof PlainTextWriter) {
205 final var writer = (PlainTextWriter) outputWriter;
206 writer.println("{}", timestamp);
207 } else {
208 final var writer = (JsonWriter) outputWriter;
209 writer.write(Map.of("timestamp", timestamp));
210 }
211 }
212 }