1 package org
.asamk
.signal
.commands
;
3 import com
.fasterxml
.jackson
.core
.TreeNode
;
4 import com
.fasterxml
.jackson
.databind
.JsonMappingException
;
5 import com
.fasterxml
.jackson
.databind
.JsonNode
;
6 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
7 import com
.fasterxml
.jackson
.databind
.node
.ContainerNode
;
9 import net
.sourceforge
.argparse4j
.impl
.Arguments
;
10 import net
.sourceforge
.argparse4j
.inf
.Namespace
;
11 import net
.sourceforge
.argparse4j
.inf
.Subparser
;
13 import org
.asamk
.signal
.JsonReceiveMessageHandler
;
14 import org
.asamk
.signal
.JsonWriter
;
15 import org
.asamk
.signal
.OutputType
;
16 import org
.asamk
.signal
.OutputWriter
;
17 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
18 import org
.asamk
.signal
.commands
.exceptions
.IOErrorException
;
19 import org
.asamk
.signal
.commands
.exceptions
.UntrustedKeyErrorException
;
20 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
21 import org
.asamk
.signal
.jsonrpc
.JsonRpcException
;
22 import org
.asamk
.signal
.jsonrpc
.JsonRpcReader
;
23 import org
.asamk
.signal
.jsonrpc
.JsonRpcRequest
;
24 import org
.asamk
.signal
.jsonrpc
.JsonRpcResponse
;
25 import org
.asamk
.signal
.jsonrpc
.JsonRpcSender
;
26 import org
.asamk
.signal
.manager
.Manager
;
27 import org
.asamk
.signal
.util
.Util
;
28 import org
.slf4j
.Logger
;
29 import org
.slf4j
.LoggerFactory
;
31 import java
.io
.BufferedReader
;
32 import java
.io
.IOException
;
33 import java
.io
.InputStreamReader
;
36 import java
.util
.concurrent
.TimeUnit
;
38 public class JsonRpcDispatcherCommand
implements LocalCommand
{
40 private final static Logger logger
= LoggerFactory
.getLogger(JsonRpcDispatcherCommand
.class);
42 private static final int USER_ERROR
= -1;
43 private static final int IO_ERROR
= -3;
44 private static final int UNTRUSTED_KEY_ERROR
= -4;
46 private final OutputWriter outputWriter
;
48 public static void attachToSubparser(final Subparser subparser
) {
49 subparser
.help("Take commands from standard input as line-delimited JSON RPC while receiving messages.");
50 subparser
.addArgument("--ignore-attachments")
51 .help("Don’t download attachments of received messages.")
52 .action(Arguments
.storeTrue());
55 public JsonRpcDispatcherCommand(final OutputWriter outputWriter
) {
56 this.outputWriter
= outputWriter
;
60 public Set
<OutputType
> getSupportedOutputTypes() {
61 return Set
.of(OutputType
.JSON
);
65 public void handleCommand(final Namespace ns
, final Manager m
) throws CommandException
{
66 final boolean ignoreAttachments
= ns
.getBoolean("ignore-attachments");
68 final var objectMapper
= Util
.createJsonObjectMapper();
69 final var jsonRpcSender
= new JsonRpcSender((JsonWriter
) outputWriter
);
71 final var receiveThread
= receiveMessages(s
-> jsonRpcSender
.sendRequest(JsonRpcRequest
.forNotification(
73 objectMapper
.valueToTree(s
),
74 null)), m
, ignoreAttachments
);
76 final BufferedReader reader
= new BufferedReader(new InputStreamReader(System
.in));
78 final var jsonRpcReader
= new JsonRpcReader(jsonRpcSender
, () -> {
80 return reader
.readLine();
81 } catch (IOException e
) {
82 throw new AssertionError(e
);
85 jsonRpcReader
.readRequests((method
, params
) -> handleRequest(m
, objectMapper
, method
, params
),
86 response
-> logger
.debug("Received unexpected response for id {}", response
.getId()));
88 receiveThread
.interrupt();
91 } catch (InterruptedException ignored
) {
95 private JsonNode
handleRequest(
96 final Manager m
, final ObjectMapper objectMapper
, final String method
, ContainerNode
<?
> params
97 ) throws JsonRpcException
{
98 final Object
[] result
= {null};
99 final JsonWriter commandOutputWriter
= s
-> {
100 if (result
[0] != null) {
101 throw new AssertionError("Command may only write one json result");
107 var command
= Commands
.getCommand(method
, commandOutputWriter
);
108 if (!(command
instanceof JsonRpcCommand
)) {
109 throw new JsonRpcException(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.METHOD_NOT_FOUND
,
110 "Method not implemented",
115 parseParamsAndRunCommand(m
, objectMapper
, params
, (JsonRpcCommand
<?
>) command
);
116 } catch (JsonMappingException e
) {
117 throw new JsonRpcException(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.INVALID_REQUEST
,
120 } catch (UserErrorException e
) {
121 throw new JsonRpcException(new JsonRpcResponse
.Error(USER_ERROR
, e
.getMessage(), null));
122 } catch (IOErrorException e
) {
123 throw new JsonRpcException(new JsonRpcResponse
.Error(IO_ERROR
, e
.getMessage(), null));
124 } catch (UntrustedKeyErrorException e
) {
125 throw new JsonRpcException(new JsonRpcResponse
.Error(UNTRUSTED_KEY_ERROR
, e
.getMessage(), null));
126 } catch (Throwable e
) {
127 logger
.error("Command execution failed", e
);
128 throw new JsonRpcException(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.INTERNAL_ERROR
,
133 Object output
= result
[0] == null ? Map
.of() : result
[0];
134 return objectMapper
.valueToTree(output
);
137 private <T
> void parseParamsAndRunCommand(
138 final Manager m
, final ObjectMapper objectMapper
, final TreeNode params
, final JsonRpcCommand
<T
> command
139 ) throws CommandException
, JsonMappingException
{
140 T requestParams
= null;
141 final var requestType
= command
.getRequestType();
142 if (params
!= null && requestType
!= null) {
144 requestParams
= objectMapper
.readValue(objectMapper
.treeAsTokens(params
), requestType
);
145 } catch (JsonMappingException e
) {
147 } catch (IOException e
) {
148 throw new AssertionError(e
);
151 command
.handleCommand(requestParams
, m
);
154 private Thread
receiveMessages(
155 JsonWriter jsonWriter
, Manager m
, boolean ignoreAttachments
157 final var thread
= new Thread(() -> {
158 while (!Thread
.interrupted()) {
160 final var receiveMessageHandler
= new JsonReceiveMessageHandler(m
, jsonWriter
);
161 m
.receiveMessages(1, TimeUnit
.HOURS
, false, ignoreAttachments
, receiveMessageHandler
);
163 } catch (IOException e
) {
164 logger
.warn("Receiving messages failed, retrying", e
);
165 } catch (InterruptedException e
) {