X-Git-Url: https://git.nmode.ca/signal-cli/blobdiff_plain/4a1af0786c938f887a109a17dcc879da21704a8b..f2005593ecefd37c7e1666c2dc0c71b259271af0:/src/main/java/org/asamk/signal/jsonrpc/SignalJsonRpcDispatcherHandler.java diff --git a/src/main/java/org/asamk/signal/jsonrpc/SignalJsonRpcDispatcherHandler.java b/src/main/java/org/asamk/signal/jsonrpc/SignalJsonRpcDispatcherHandler.java index 112bc5a9..5d3fa261 100644 --- a/src/main/java/org/asamk/signal/jsonrpc/SignalJsonRpcDispatcherHandler.java +++ b/src/main/java/org/asamk/signal/jsonrpc/SignalJsonRpcDispatcherHandler.java @@ -1,55 +1,51 @@ package org.asamk.signal.jsonrpc; -import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ContainerNode; +import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import org.asamk.signal.JsonReceiveMessageHandler; -import org.asamk.signal.JsonWriter; import org.asamk.signal.commands.Command; import org.asamk.signal.commands.Commands; import org.asamk.signal.commands.JsonRpcMultiCommand; import org.asamk.signal.commands.JsonRpcSingleCommand; import org.asamk.signal.commands.exceptions.CommandException; -import org.asamk.signal.commands.exceptions.IOErrorException; -import org.asamk.signal.commands.exceptions.UntrustedKeyErrorException; import org.asamk.signal.commands.exceptions.UserErrorException; +import org.asamk.signal.json.JsonReceiveMessageHandler; import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.MultiAccountManager; +import org.asamk.signal.manager.api.Pair; +import org.asamk.signal.output.JsonWriter; import org.asamk.signal.util.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; +import java.nio.channels.ClosedChannelException; import java.util.HashMap; +import java.util.List; import java.util.Map; -import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; public class SignalJsonRpcDispatcherHandler { - private final static Logger logger = LoggerFactory.getLogger(SignalJsonRpcDispatcherHandler.class); - - private static final int USER_ERROR = -1; - private static final int IO_ERROR = -3; - private static final int UNTRUSTED_KEY_ERROR = -4; + private static final Logger logger = LoggerFactory.getLogger(SignalJsonRpcDispatcherHandler.class); private final ObjectMapper objectMapper; private final JsonRpcSender jsonRpcSender; private final JsonRpcReader jsonRpcReader; private final boolean noReceiveOnStart; - private MultiAccountManager c; - private final Map receiveHandlers = new HashMap<>(); - - private Manager m; + private final Map>> receiveHandlers = new HashMap<>(); + private SignalJsonRpcCommandHandler commandHandler; public SignalJsonRpcDispatcherHandler( - final JsonWriter jsonWriter, final Supplier lineSupplier, final boolean noReceiveOnStart + final JsonWriter jsonWriter, + final Supplier lineSupplier, + final boolean noReceiveOnStart ) { this.noReceiveOnStart = noReceiveOnStart; this.objectMapper = Util.createJsonObjectMapper(); @@ -58,101 +54,100 @@ public class SignalJsonRpcDispatcherHandler { } public void handleConnection(final MultiAccountManager c) { - this.c = c; + this.commandHandler = new SignalJsonRpcCommandHandler(c, this::getCommand); if (!noReceiveOnStart) { - c.getAccountNumbers().stream().map(c::getManager).filter(Objects::nonNull).forEach(this::subscribeReceive); + this.subscribeReceive(c.getManagers(), true); + c.addOnManagerAddedHandler(m -> subscribeReceive(m, true)); + c.addOnManagerRemovedHandler(this::unsubscribeReceive); } handleConnection(); } public void handleConnection(final Manager m) { - this.m = m; + this.commandHandler = new SignalJsonRpcCommandHandler(m, this::getCommand); if (!noReceiveOnStart) { - subscribeReceive(m); + subscribeReceive(m, true); } + final var currentThread = Thread.currentThread(); + m.addClosedListener(currentThread::interrupt); + handleConnection(); } - private void subscribeReceive(final Manager m) { - if (receiveHandlers.containsKey(m)) { - return; - } + private static final AtomicInteger nextSubscriptionId = new AtomicInteger(0); - final var receiveMessageHandler = new JsonReceiveMessageHandler(m, - s -> jsonRpcSender.sendRequest(JsonRpcRequest.forNotification("receive", - objectMapper.valueToTree(s), - null))); - m.addReceiveHandler(receiveMessageHandler); - receiveHandlers.put(m, receiveMessageHandler); - - while (!m.hasCaughtUpWithOldMessages()) { - try { - synchronized (m) { - m.wait(); + private int subscribeReceive(final Manager manager, boolean internalSubscription) { + return subscribeReceive(List.of(manager), internalSubscription); + } + + private int subscribeReceive(final List managers, boolean internalSubscription) { + final var subscriptionId = nextSubscriptionId.getAndIncrement(); + final var handlers = managers.stream().map(m -> { + final var receiveMessageHandler = new JsonReceiveMessageHandler(m, s -> { + ContainerNode params; + if (internalSubscription) { + params = objectMapper.valueToTree(s); + } else { + final var paramsNode = new ObjectNode(objectMapper.getNodeFactory()); + paramsNode.set("subscription", IntNode.valueOf(subscriptionId)); + paramsNode.set("result", objectMapper.valueToTree(s)); + params = paramsNode; } - } catch (InterruptedException ignored) { - } - } + final var jsonRpcRequest = JsonRpcRequest.forNotification("receive", params, null); + try { + jsonRpcSender.sendRequest(jsonRpcRequest); + } catch (AssertionError e) { + if (e.getCause() instanceof ClosedChannelException) { + unsubscribeReceive(subscriptionId); + } + } + }); + m.addReceiveHandler(receiveMessageHandler); + return new Pair<>(m, (Manager.ReceiveMessageHandler) receiveMessageHandler); + }).toList(); + receiveHandlers.put(subscriptionId, handlers); + + return subscriptionId; } - void unsubscribeReceive(final Manager m) { - final var receiveMessageHandler = receiveHandlers.remove(m); - if (receiveMessageHandler != null) { - m.removeReceiveHandler(receiveMessageHandler); + private boolean unsubscribeReceive(final int subscriptionId) { + final var handlers = receiveHandlers.remove(subscriptionId); + if (handlers == null) { + return false; + } + for (final var pair : handlers) { + unsubscribeReceiveHandler(pair); } + return true; + } + + private void unsubscribeReceive(final Manager m) { + final var subscriptionId = receiveHandlers.entrySet() + .stream() + .filter(e -> e.getValue().size() == 1 && e.getValue().getFirst().first().equals(m)) + .map(Map.Entry::getKey) + .findFirst(); + subscriptionId.ifPresent(this::unsubscribeReceive); } private void handleConnection() { try { - jsonRpcReader.readMessages((method, params) -> handleRequest(objectMapper, method, params), + jsonRpcReader.readMessages((method, params) -> commandHandler.handleRequest(objectMapper, method, params), response -> logger.debug("Received unexpected response for id {}", response.getId())); } finally { - receiveHandlers.forEach(Manager::removeReceiveHandler); + receiveHandlers.forEach((_subscriptionId, handlers) -> handlers.forEach(this::unsubscribeReceiveHandler)); receiveHandlers.clear(); } } - private JsonNode handleRequest( - final ObjectMapper objectMapper, final String method, ContainerNode params - ) throws JsonRpcException { - var command = getCommand(method); - // TODO implement register, verify, link - if (c != null) { - if (command instanceof JsonRpcMultiCommand jsonRpcCommand) { - return runCommand(objectMapper, params, new MultiCommandRunnerImpl<>(c, jsonRpcCommand)); - } - } - if (command instanceof JsonRpcSingleCommand jsonRpcCommand) { - if (m != null) { - return runCommand(objectMapper, params, new CommandRunnerImpl<>(m, jsonRpcCommand)); - } - - final var manager = getManagerFromParams(params); - if (manager != null) { - return runCommand(objectMapper, params, new CommandRunnerImpl<>(manager, jsonRpcCommand)); - } else { - throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_PARAMS, - "Method requires valid account parameter", - null)); - } - } - - throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.METHOD_NOT_FOUND, - "Method not implemented", - null)); - } - - private Manager getManagerFromParams(final ContainerNode params) { - if (params.has("account")) { - final var manager = c.getManager(params.get("account").asText()); - ((ObjectNode) params).remove("account"); - return manager; - } - return null; + private void unsubscribeReceiveHandler(final Pair pair) { + final var m = pair.first(); + final var handler = pair.second(); + m.removeReceiveHandler(handler); } private Command getCommand(final String method) { @@ -165,123 +160,84 @@ public class SignalJsonRpcDispatcherHandler { return Commands.getCommand(method); } - private record CommandRunnerImpl(Manager m, JsonRpcSingleCommand command) implements CommandRunner { - - @Override - public void handleCommand(final T request, final JsonWriter jsonWriter) throws CommandException { - command.handleCommand(request, m, jsonWriter); - } + private class SubscribeReceiveCommand implements JsonRpcSingleCommand, JsonRpcMultiCommand { @Override - public TypeReference getRequestType() { - return command.getRequestType(); + public String getName() { + return "subscribeReceive"; } - } - - private record MultiCommandRunnerImpl( - MultiAccountManager c, JsonRpcMultiCommand command - ) implements CommandRunner { @Override - public void handleCommand(final T request, final JsonWriter jsonWriter) throws CommandException { - command.handleCommand(request, c, jsonWriter); + public void handleCommand( + final Void request, + final Manager m, + final JsonWriter jsonWriter + ) throws CommandException { + final var subscriptionId = subscribeReceive(m, false); + jsonWriter.write(subscriptionId); } @Override - public TypeReference getRequestType() { - return command.getRequestType(); - } - } - - interface CommandRunner { - - void handleCommand(T request, JsonWriter jsonWriter) throws CommandException; - - TypeReference getRequestType(); - } - - private JsonNode runCommand( - final ObjectMapper objectMapper, final ContainerNode params, final CommandRunner command - ) throws JsonRpcException { - final Object[] result = {null}; - final JsonWriter commandJsonWriter = s -> { - if (result[0] != null) { - throw new AssertionError("Command may only write one json result"); - } - - result[0] = s; - }; - - try { - parseParamsAndRunCommand(objectMapper, params, commandJsonWriter, command); - } catch (JsonMappingException e) { - throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST, - e.getMessage(), - null)); - } catch (UserErrorException e) { - throw new JsonRpcException(new JsonRpcResponse.Error(USER_ERROR, e.getMessage(), null)); - } catch (IOErrorException e) { - throw new JsonRpcException(new JsonRpcResponse.Error(IO_ERROR, e.getMessage(), null)); - } catch (UntrustedKeyErrorException e) { - throw new JsonRpcException(new JsonRpcResponse.Error(UNTRUSTED_KEY_ERROR, e.getMessage(), null)); - } catch (Throwable e) { - logger.error("Command execution failed", e); - throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INTERNAL_ERROR, - e.getMessage(), - null)); - } - - Object output = result[0] == null ? Map.of() : result[0]; - return objectMapper.valueToTree(output); - } - - private void parseParamsAndRunCommand( - final ObjectMapper objectMapper, - final TreeNode params, - final JsonWriter jsonWriter, - final CommandRunner command - ) throws CommandException, JsonMappingException { - T requestParams = null; - final var requestType = command.getRequestType(); - if (params != null && requestType != null) { - try { - requestParams = objectMapper.readValue(objectMapper.treeAsTokens(params), requestType); - } catch (JsonMappingException e) { - throw e; - } catch (IOException e) { - throw new AssertionError(e); - } + public void handleCommand( + final Void request, + final MultiAccountManager c, + final JsonWriter jsonWriter + ) throws CommandException { + final var subscriptionId = subscribeReceive(c.getManagers(), false); + jsonWriter.write(subscriptionId); } - command.handleCommand(requestParams, jsonWriter); } - private class SubscribeReceiveCommand implements JsonRpcSingleCommand { + private class UnsubscribeReceiveCommand implements JsonRpcSingleCommand, JsonRpcMultiCommand { @Override public String getName() { - return "subscribeReceive"; + return "unsubscribeReceive"; } @Override - public void handleCommand( - final Void request, final Manager m, final JsonWriter jsonWriter - ) throws CommandException { - subscribeReceive(m); + public TypeReference getRequestType() { + return new TypeReference<>() {}; } - } - - private class UnsubscribeReceiveCommand implements JsonRpcSingleCommand { @Override - public String getName() { - return "unsubscribeReceive"; + public void handleCommand( + final JsonNode request, + final Manager m, + final JsonWriter jsonWriter + ) throws CommandException { + final var subscriptionId = getSubscriptionId(request); + if (subscriptionId == null) { + unsubscribeReceive(m); + } else { + if (!unsubscribeReceive(subscriptionId)) { + throw new UserErrorException("Unknown subscription id"); + } + } } @Override public void handleCommand( - final Void request, final Manager m, final JsonWriter jsonWriter + final JsonNode request, + final MultiAccountManager c, + final JsonWriter jsonWriter ) throws CommandException { - unsubscribeReceive(m); + final var subscriptionId = getSubscriptionId(request); + if (subscriptionId == null) { + throw new UserErrorException("Missing subscription parameter with subscription id"); + } else { + if (!unsubscribeReceive(subscriptionId)) { + throw new UserErrorException("Unknown subscription id"); + } + } + } + + private Integer getSubscriptionId(final JsonNode request) { + return switch (request) { + case ArrayNode req -> req.get(0).asInt(); + case ObjectNode req -> req.get("subscription").asInt(); + case null, default -> null; + }; } } }