From 29085adc6e4e5d9e63da5184a75ed16cf4a565ac Mon Sep 17 00:00:00 2001 From: Dmytro Galushko Date: Tue, 16 Jan 2024 23:21:56 +0200 Subject: [PATCH] Add two torrent folders and two media folders --- config/dockerfiles/docker-compose.yml | 2 +- config/examples/docker-compose/constants.yml | 19 +++ .../docker-compose/docker-compose-bot.yml | 21 +--- .../docker-compose-bot_debug.yml | 21 +--- .../web/InputMessageHandlerApiRequest.java | 39 ++++-- .../torrent/requests/common/GetTorrent.java | 2 +- .../common/TransmissionWebApiExecutor.java | 111 +++++++++--------- .../requests/common/VoidTorrentOperator.java | 2 +- 8 files changed, 116 insertions(+), 101 deletions(-) create mode 100644 config/examples/docker-compose/constants.yml diff --git a/config/dockerfiles/docker-compose.yml b/config/dockerfiles/docker-compose.yml index 9aede8ff..f2dc9992 100644 --- a/config/dockerfiles/docker-compose.yml +++ b/config/dockerfiles/docker-compose.yml @@ -33,7 +33,7 @@ services: - 15672:15672 media: image: lscr.io/linuxserver/plex:latest - container_name: "media" + container_name: "media1" depends_on: - rabbitmq environment: diff --git a/config/examples/docker-compose/constants.yml b/config/examples/docker-compose/constants.yml new file mode 100644 index 00000000..cf30f07d --- /dev/null +++ b/config/examples/docker-compose/constants.yml @@ -0,0 +1,19 @@ +common-variables: &common-variables + RABBITMQ_DEFAULT_USER: rabbit_user + RABBITMQ_DEFAULT_PASS: rabbit_pswrd + RABBIT_PORT: 5672 + RABBIT_IP: + BOT_NAME: + BOT_TRUSTED_USERS: + + LONG_PAUSE_MILIS: 10000 + MEDIUM_PAUSE_MILIS: 5000 + SMALL_PAUSE_MILIS: 500 + + PING: /ping + PONG: pong + + LOGS_LEVEL: info \ No newline at end of file diff --git a/config/examples/docker-compose/docker-compose-bot.yml b/config/examples/docker-compose/docker-compose-bot.yml index 2750393b..93e803e1 100644 --- a/config/examples/docker-compose/docker-compose-bot.yml +++ b/config/examples/docker-compose/docker-compose-bot.yml @@ -1,24 +1,9 @@ version: '3.7' x-common-variables: &common-variables - RABBITMQ_DEFAULT_USER: rabbit_user - RABBITMQ_DEFAULT_PASS: rabbit_pswrd - RABBIT_PORT: 5672 - RABBIT_IP: 192.168.50.132 - TORRENT_IP: 192.168.50.132 - - BOT_TOKEN: 6103416881:AAFSQ_hGImrAI05FaAGnx4Yez2eZM9M5uJc - BOT_NAME: halushko_video_bot - BOT_TRUSTED_USERS: 43504868 - - LONG_PAUSE_MILIS: 10000 - MEDIUM_PAUSE_MILIS: 5000 - SMALL_PAUSE_MILIS: 500 - - PING: /ping - PONG: pong - - LOGS_LEVEL: info + extends: + file: constants.yml + service: common-variables services: torrent: image: halushko/cinema-torrent:alpha diff --git a/config/examples/docker-compose/docker-compose-bot_debug.yml b/config/examples/docker-compose/docker-compose-bot_debug.yml index c35568b3..07a3a769 100644 --- a/config/examples/docker-compose/docker-compose-bot_debug.yml +++ b/config/examples/docker-compose/docker-compose-bot_debug.yml @@ -1,24 +1,9 @@ version: '3.7' x-common-variables: &common-variables - RABBITMQ_DEFAULT_USER: rabbit_user - RABBITMQ_DEFAULT_PASS: rabbit_pswrd - RABBIT_PORT: 5672 - RABBIT_IP: 192.168.50.132 - TORRENT_IP: 192.168.50.132 - - BOT_TOKEN: 6103416881:AAFSQ_hGImrAI05FaAGnx4Yez2eZM9M5uJc - BOT_NAME: halushko_video_bot - BOT_TRUSTED_USERS: 43504868 - - LONG_PAUSE_MILIS: 10000 - MEDIUM_PAUSE_MILIS: 5000 - SMALL_PAUSE_MILIS: 500 - - PING: /ping - PONG: pong - - LOGS_LEVEL: debug + extends: + file: constants.yml + service: common-variables services: torrent_debug: image: halushko/cinema-torrent:beta diff --git a/core/src/main/java/com/halushko/kinocat/core/web/InputMessageHandlerApiRequest.java b/core/src/main/java/com/halushko/kinocat/core/web/InputMessageHandlerApiRequest.java index 8e2e8eba..b509cf84 100644 --- a/core/src/main/java/com/halushko/kinocat/core/web/InputMessageHandlerApiRequest.java +++ b/core/src/main/java/com/halushko/kinocat/core/web/InputMessageHandlerApiRequest.java @@ -1,6 +1,7 @@ package com.halushko.kinocat.core.web; import com.halushko.kinocat.core.handlers.input.InputMessageHandler; +import com.halushko.kinocat.core.rabbit.SmartJson; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.http.HttpResponse; @@ -18,19 +19,39 @@ @SuppressWarnings("unused") @Slf4j public abstract class InputMessageHandlerApiRequest extends InputMessageHandler { - private final String serverUrl; + private final Map serverUrls = new LinkedHashMap<>(); public InputMessageHandlerApiRequest(String protocol, String ip, int port, String suffix) { - this.serverUrl = String.format("%s://%s:%s/%s", protocol, ip, port, suffix); + this.serverUrls.put("default", String.format("%s://%s:%s/%s", protocol, ip, port, suffix)); } - protected ApiResponce send(String body, Map headers) { - return new ApiResponce(requestPrivate(body, headers)); + public InputMessageHandlerApiRequest(String urls) { + //noinspection unchecked + new SmartJson(urls) + .convertToList() + .stream() + .map((x -> (Map) x)) + .forEach( + x -> this.serverUrls.put( + String.valueOf(x.containsValue("name") ? x.get("name") : "default"), + String.format("%s://%s:%s/%s", + x.containsValue("protocol") ? x.get("protocol") : "http", + x.get("ip"), + x.get("port"), + x.containsValue("suffix") ? x.get("suffix") : "transmission/rpc" + ) + ) + ); } - private HttpResponse requestPrivate(String body, Map headers) { + + protected ApiResponce send(String serverName, String body, Map headers) { + return new ApiResponce(requestPrivate(body, headers, serverUrls.get(serverName))); + } + + private HttpResponse requestPrivate(String body, Map headers, String url) { log.debug("[request] headers=[{}], body=[{}]", headers, body); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpPost postRequest = new HttpPost(serverUrl); + HttpPost postRequest = new HttpPost(url); if (headers != null) { headers.forEach(postRequest::addHeader); } @@ -41,17 +62,17 @@ private HttpResponse requestPrivate(String body, Map headers) { log.debug("[request] output={}", response); return response; } catch (IOException e) { - log.error(String.format("[request] Error during sending request to %s", serverUrl), e); + log.error(String.format("[request] Error during sending request to %s", url), e); } return null; } - protected ApiResponce send(String body, String... headers) { + protected ApiResponce send(String serverName, String body, String... headers) { val headerMap = IntStream.iterate(0, i -> i < headers.length, i -> i + 2). filter(i -> i + 1 < headers.length). boxed(). collect(Collectors.toMap(i -> headers[i], i -> headers[i + 1], (a, b) -> b, LinkedHashMap::new)); - return send(body, headerMap); + return send(serverName, body, headerMap); } protected abstract String getRequest(); diff --git a/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/GetTorrent.java b/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/GetTorrent.java index 3789f2fd..95e2f39e 100644 --- a/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/GetTorrent.java +++ b/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/GetTorrent.java @@ -11,7 +11,7 @@ public abstract class GetTorrent extends TransmissionWebApiExecutor { @Override - protected final List parceResponce(SmartJson json) { + protected final List parseResponce(SmartJson json) { return json.getSubMessage(SmartJson.KEYS.OUTPUT) .getSubMessage("arguments") .getSubMessage("torrents") diff --git a/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/TransmissionWebApiExecutor.java b/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/TransmissionWebApiExecutor.java index c534ca18..1cd37779 100644 --- a/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/TransmissionWebApiExecutor.java +++ b/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/TransmissionWebApiExecutor.java @@ -7,86 +7,91 @@ import lombok.extern.slf4j.Slf4j; import lombok.val; +import java.util.HashMap; import java.util.List; +import java.util.Map; // https://github.com/transmission/transmission/blob/main/docs/rpc-spec.md @Slf4j public abstract class TransmissionWebApiExecutor extends InputMessageHandlerApiRequest { - private static String sessionIdValue; + private final static Map sessionIdValues = new HashMap<>(); protected final static String sessionIdKey = "X-Transmission-Session-Id"; public static final String TRANSMISSION_IP = System.getenv("TORRENT_IP"); public TransmissionWebApiExecutor() { - super("http", TRANSMISSION_IP, 9091, "transmission/rpc"); + super(TRANSMISSION_IP); } @Override protected final String getDeliverCallbackPrivate(SmartJson message) { log.debug("[getDeliverCallbackPrivate] Message:\n{}", message.getRabbitMessageText()); long chatId = message.getUserId(); - if (sessionIdValue == null) { - //new session - log.debug("[getDeliverCallbackPrivate] Create a new session"); + StringBuilder output = new StringBuilder(); - val responce = send("", "Content-Type", "application/json"); - TransmissionWebApiExecutor.sessionIdValue = responce.getHeader(sessionIdKey); - } - String requestBodyFormat = ResourceReader.readResourceContent(String.format("transmission_requests/%s", getRequest())); - Object[] requestBodyFormatArguments = getRequestArguments(message.getSubMessage(SmartJson.KEYS.COMMAND_ARGUMENTS)); - log.debug("[getDeliverCallbackPrivate] Request body format:\n{}\nRequest body format arguments:\n{}", requestBodyFormat, requestBodyFormatArguments); - String requestBody = String.format(requestBodyFormat, requestBodyFormatArguments); - log.debug("[getDeliverCallbackPrivate] Request body:\n{}", requestBody); + for(val session: sessionIdValues.entrySet()) { + if (session.getValue() == null) { + //new session + log.debug("[getDeliverCallbackPrivate] Create a new session"); - ApiResponce responce = send(requestBody, "Content-Type", "application/json", sessionIdKey, sessionIdValue); - String responceBody = responce.getBody(); - if (responceBody.contains("409: Conflict")) { - //expired session - log.debug("[getDeliverCallbackPrivate] Recreate a session"); - TransmissionWebApiExecutor.sessionIdValue = responce.getHeader(sessionIdKey); - responce = send(requestBody, "Content-Type", "application/json", sessionIdKey, sessionIdValue); - responceBody = responce.getBody(); - } + val responce = send("", "Content-Type", "application/json", ""); + TransmissionWebApiExecutor.sessionIdValues.put(session.getKey(), responce.getHeader(sessionIdKey)); + } + String requestBodyFormat = ResourceReader.readResourceContent(String.format("transmission_requests/%s", getRequest())); + Object[] requestBodyFormatArguments = getRequestArguments(message.getSubMessage(SmartJson.KEYS.COMMAND_ARGUMENTS)); + log.debug("[getDeliverCallbackPrivate] Request body format:\n{}\nRequest body format arguments:\n{}", requestBodyFormat, requestBodyFormatArguments); + String requestBody = String.format(requestBodyFormat, requestBodyFormatArguments); + log.debug("[getDeliverCallbackPrivate] Request body:\n{}", requestBody); - log.debug("[getDeliverCallbackPrivate] Responce body:\n{}", responceBody); - SmartJson json = new SmartJson(SmartJson.KEYS.INPUT, message.getRabbitMessageText()).addValue(SmartJson.KEYS.OUTPUT, responceBody); - StringBuilder output = new StringBuilder(); + ApiResponce responce = send(requestBody, session.getKey(), "Content-Type", "application/json", sessionIdKey, session.getValue()); + String responceBody = responce.getBody(); + if (responceBody.contains("409: Conflict")) { + //expired session + log.debug("[getDeliverCallbackPrivate] Recreate a session"); + TransmissionWebApiExecutor.sessionIdValues.put(session.getKey(), responce.getHeader(sessionIdKey)); + responce = send(session.getKey(), requestBody, "Content-Type", "application/json", sessionIdKey, session.getValue()); + responceBody = responce.getBody(); + } - if (isResultValid(json)) { - val result = parceResponce(json); - StringBuilder sb = null; - for (int i = 1; i <= result.size(); i++) { - String answer = result.get(i-1); - log.debug("[getDeliverCallbackPrivate] answer={}", answer); - if (i == 1 || i % 10 == 0) { - log.debug("[getDeliverCallbackPrivate] New message created"); - if (sb != null) { - log.debug("[getDeliverCallbackPrivate] Print result:\n{}", sb); - output.append(printResult(chatId, sb.toString())).append(OUTPUT_SEPARATOR); - } - sb = new StringBuilder(); - if (addDescription()) { - sb.append(textOfMessageBegin()).append(i).append("-").append(result.size() < i + 10 ? result.size() : (i == 1 ? 9 : i + 9)).append("\n\n"); + log.debug("[getDeliverCallbackPrivate] Responce body:\n{}", responceBody); + SmartJson json = new SmartJson(SmartJson.KEYS.INPUT, message.getRabbitMessageText()).addValue(SmartJson.KEYS.OUTPUT, responceBody); + + if (isResultValid(json)) { + val result = parseResponce(json); + StringBuilder sb = null; + for (int i = 1; i <= result.size(); i++) { + String answer = result.get(i - 1); + log.debug("[getDeliverCallbackPrivate] answer={}", answer); + if (i == 1 || i % 10 == 0) { + log.debug("[getDeliverCallbackPrivate] New message created"); + if (sb != null) { + log.debug("[getDeliverCallbackPrivate] Print result:\n{}", sb); + output.append(printResult(chatId, sb.toString())).append(OUTPUT_SEPARATOR); + } + sb = new StringBuilder(); + if (addDescription()) { + sb.append(session.getKey()).append(": ").append(textOfMessageBegin()).append(i).append("-").append(result.size() < i + 10 ? result.size() : (i == 1 ? 9 : i + 9)).append("\n\n"); + } } + sb.append(answer).append(OUTPUT_SEPARATOR); + log.debug("[getDeliverCallbackPrivate] Message:\n{}", sb); + } + if (sb != null) { + log.debug("[getDeliverCallbackPrivate] Print result:\n{}", sb); + output.append(printResult(chatId, sb.toString())); + } else { + log.debug("[getDeliverCallbackPrivate] Result is empty"); + output.append(printResult(chatId, "Нажаль результат запиту порожній")); } - sb.append(answer).append(OUTPUT_SEPARATOR); - log.debug("[getDeliverCallbackPrivate] Message:\n{}", sb); - } - if (sb != null) { - log.debug("[getDeliverCallbackPrivate] Print result:\n{}", sb); - output.append(printResult(chatId, sb.toString())); } else { - log.debug("[getDeliverCallbackPrivate] Result is empty"); - output.append(printResult(chatId, "Нажаль результат запиту порожній")); + String errorText = String.format("Server: %s result of request is: %s", session.getKey(), responceBody); + output.append(errorText); + printResult(chatId, errorText); } - } else { - String errorText = String.format("result of request is: %s", responceBody); - output.append(errorText); - printResult(chatId, errorText); } return output.toString(); } - protected abstract List parceResponce(SmartJson message); + protected abstract List parseResponce(SmartJson message); protected boolean isResultValid(SmartJson result) { return "success".equalsIgnoreCase(result.getSubMessage(SmartJson.KEYS.OUTPUT).getValue("result")); diff --git a/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/VoidTorrentOperator.java b/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/VoidTorrentOperator.java index dc841630..372bcac5 100644 --- a/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/VoidTorrentOperator.java +++ b/torrent/src/main/java/com/halushko/kinocat/torrent/requests/common/VoidTorrentOperator.java @@ -9,7 +9,7 @@ @Slf4j public abstract class VoidTorrentOperator extends TransmissionWebApiExecutor { @Override - protected List parceResponce(SmartJson message) { + protected List parseResponce(SmartJson message) { List result = new ArrayList<>(); result.add(String.format("Операція %s виконана без помилок", getCommandNameForOutputText())); return result;