1 package org
.asamk
.signal
.commands
;
3 import net
.sourceforge
.argparse4j
.impl
.Arguments
;
4 import net
.sourceforge
.argparse4j
.inf
.Namespace
;
5 import net
.sourceforge
.argparse4j
.inf
.Subparser
;
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
.Manager
;
11 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
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
;
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
;
34 import static org
.asamk
.signal
.util
.SendMessageResultUtils
.outputResult
;
36 public class SendCommand
implements JsonRpcLocalCommand
{
38 private final static Logger logger
= LoggerFactory
.getLogger(SendCommand
.class);
41 public String
getName() {
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());
54 var mut
= subparser
.addMutuallyExclusiveGroup();
55 mut
.addArgument("-m", "--message").help("Specify the message to be sent.");
56 mut
.addArgument("--message-from-stdin")
57 .action(Arguments
.storeTrue())
58 .help("Read the message from standard input.");
59 subparser
.addArgument("-a", "--attachment").nargs("*").help("Add file as attachment");
60 subparser
.addArgument("-e", "--end-session", "--endsession")
61 .help("Clear session state and send end session message.")
62 .action(Arguments
.storeTrue());
63 subparser
.addArgument("--mention")
65 .help("Mention another group member (syntax: start:length:recipientNumber)");
66 subparser
.addArgument("--quote-timestamp")
68 .help("Specify the timestamp of a previous message with the recipient or group to add a quote to the new message.");
69 subparser
.addArgument("--quote-author").help("Specify the number of the author of the original message.");
70 subparser
.addArgument("--quote-message").help("Specify the message of the original message.");
71 subparser
.addArgument("--quote-mention")
73 .help("Quote with mention of another group member (syntax: start:length:recipientNumber)");
74 subparser
.addArgument("--sticker").help("Send a sticker (syntax: stickerPackId:stickerId)");
78 public void handleCommand(
79 final Namespace ns
, final Manager m
, final OutputWriter outputWriter
80 ) throws CommandException
{
81 final var isNoteToSelf
= Boolean
.TRUE
.equals(ns
.getBoolean("note-to-self"));
82 final var recipientStrings
= ns
.<String
>getList("recipient");
83 final var groupIdStrings
= ns
.<String
>getList("group-id");
85 final var recipientIdentifiers
= CommandUtil
.getRecipientIdentifiers(m
,
90 final var isEndSession
= Boolean
.TRUE
.equals(ns
.getBoolean("end-session"));
92 final var singleRecipients
= recipientIdentifiers
.stream()
93 .filter(r
-> r
instanceof RecipientIdentifier
.Single
)
94 .map(RecipientIdentifier
.Single
.class::cast
)
95 .collect(Collectors
.toSet());
96 if (singleRecipients
.isEmpty()) {
97 throw new UserErrorException("No recipients given");
101 final var results
= m
.sendEndSessionMessage(singleRecipients
);
102 outputResult(outputWriter
, results
);
104 } catch (IOException e
) {
105 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
106 .getSimpleName() + ")", e
);
110 final var stickerString
= ns
.getString("sticker");
111 final var sticker
= stickerString
== null ?
null : parseSticker(stickerString
);
113 var messageText
= ns
.getString("message");
114 final var readMessageFromStdin
= ns
.getBoolean("message-from-stdin") == Boolean
.TRUE
;
115 if (readMessageFromStdin
|| (messageText
== null && sticker
== null)) {
116 logger
.debug("Reading message from stdin...");
118 messageText
= IOUtils
.readAll(System
.in, Charset
.defaultCharset());
119 } catch (IOException e
) {
120 throw new UserErrorException("Failed to read message from stdin: " + e
.getMessage());
124 List
<String
> attachments
= ns
.getList("attachment");
125 if (attachments
== null) {
126 attachments
= List
.of();
129 List
<String
> mentionStrings
= ns
.getList("mention");
130 final var mentions
= mentionStrings
== null ? List
.<Message
.Mention
>of() : parseMentions(m
, mentionStrings
);
132 final Message
.Quote quote
;
133 final var quoteTimestamp
= ns
.getLong("quote-timestamp");
134 if (quoteTimestamp
!= null) {
135 final var quoteAuthor
= ns
.getString("quote-author");
136 final var quoteMessage
= ns
.getString("quote-message");
137 List
<String
> quoteMentionStrings
= ns
.getList("quote-mention");
138 final var quoteMentions
= quoteMentionStrings
== null
139 ? List
.<Message
.Mention
>of()
140 : parseMentions(m
, quoteMentionStrings
);
141 quote
= new Message
.Quote(quoteTimestamp
,
142 CommandUtil
.getSingleRecipientIdentifier(quoteAuthor
, m
.getSelfNumber()),
143 quoteMessage
== null ?
"" : quoteMessage
,
150 var results
= m
.sendMessage(new Message(messageText
== null ?
"" : messageText
,
153 Optional
.ofNullable(quote
),
154 Optional
.ofNullable(sticker
)), recipientIdentifiers
);
155 outputResult(outputWriter
, results
);
156 } catch (AttachmentInvalidException
| IOException e
) {
157 throw new UnexpectedErrorException("Failed to send message: " + e
.getMessage() + " (" + e
.getClass()
158 .getSimpleName() + ")", e
);
159 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
160 throw new UserErrorException(e
.getMessage());
161 } catch (UnregisteredRecipientException e
) {
162 throw new UserErrorException("The user " + e
.getSender().getIdentifier() + " is not registered.");
163 } catch (InvalidStickerException e
) {
164 throw new UserErrorException("Failed to send sticker: " + e
.getMessage(), e
);
168 private List
<Message
.Mention
> parseMentions(
169 final Manager m
, final List
<String
> mentionStrings
170 ) throws UserErrorException
{
171 List
<Message
.Mention
> mentions
;
172 final Pattern mentionPattern
= Pattern
.compile("([0-9]+):([0-9]+):(.+)");
173 mentions
= new ArrayList
<>();
174 for (final var mention
: mentionStrings
) {
175 final var matcher
= mentionPattern
.matcher(mention
);
176 if (!matcher
.matches()) {
177 throw new UserErrorException("Invalid mention syntax ("
179 + ") expected 'start:end:recipientNumber'");
181 mentions
.add(new Message
.Mention(CommandUtil
.getSingleRecipientIdentifier(matcher
.group(3),
182 m
.getSelfNumber()), Integer
.parseInt(matcher
.group(1)), Integer
.parseInt(matcher
.group(2))));
187 private Message
.Sticker
parseSticker(final String stickerString
) throws UserErrorException
{
188 final Pattern stickerPattern
= Pattern
.compile("([0-9a-f]+):([0-9]+)");
189 final var matcher
= stickerPattern
.matcher(stickerString
);
190 if (!matcher
.matches() || matcher
.group(1).length() % 2 != 0) {
191 throw new UserErrorException("Invalid sticker syntax ("
193 + ") expected 'stickerPackId:stickerId'");
195 return new Message
.Sticker(Hex
.toByteArray(matcher
.group(1)), Integer
.parseInt(matcher
.group(2)));