Skip to content

Commit

Permalink
Add two torrent folders and two media folders
Browse files Browse the repository at this point in the history
  • Loading branch information
Dmytro Galushko committed Jan 16, 2024
1 parent de2a77a commit 29085ad
Show file tree
Hide file tree
Showing 8 changed files with 116 additions and 101 deletions.
2 changes: 1 addition & 1 deletion config/dockerfiles/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ services:
- 15672:15672
media:
image: lscr.io/linuxserver/plex:latest
container_name: "media"
container_name: "media1"
depends_on:
- rabbitmq
environment:
Expand Down
19 changes: 19 additions & 0 deletions config/examples/docker-compose/constants.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
common-variables: &common-variables
RABBITMQ_DEFAULT_USER: rabbit_user
RABBITMQ_DEFAULT_PASS: rabbit_pswrd
RABBIT_PORT: 5672
RABBIT_IP: <input
TORRENT_IP: [{"ip"="<input>","port"="9093"},{"name"="hdd","ip"="<input>","port"="9092"}]

BOT_TOKEN: <input>
BOT_NAME: <input>
BOT_TRUSTED_USERS: <input>

LONG_PAUSE_MILIS: 10000
MEDIUM_PAUSE_MILIS: 5000
SMALL_PAUSE_MILIS: 500

PING: /ping
PONG: pong

LOGS_LEVEL: info
21 changes: 3 additions & 18 deletions config/examples/docker-compose/docker-compose-bot.yml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
21 changes: 3 additions & 18 deletions config/examples/docker-compose/docker-compose-bot_debug.yml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -18,19 +19,39 @@
@SuppressWarnings("unused")
@Slf4j
public abstract class InputMessageHandlerApiRequest extends InputMessageHandler {
private final String serverUrl;
private final Map<String, String> 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<String, String> headers) {
return new ApiResponce(requestPrivate(body, headers));
public InputMessageHandlerApiRequest(String urls) {
//noinspection unchecked
new SmartJson(urls)
.convertToList()
.stream()
.map((x -> (Map<String, Object>) 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<String, String> headers) {

protected ApiResponce send(String serverName, String body, Map<String, String> headers) {
return new ApiResponce(requestPrivate(body, headers, serverUrls.get(serverName)));
}

private HttpResponse requestPrivate(String body, Map<String, String> 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);
}
Expand All @@ -41,17 +62,17 @@ private HttpResponse requestPrivate(String body, Map<String, String> 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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

public abstract class GetTorrent extends TransmissionWebApiExecutor {
@Override
protected final List<String> parceResponce(SmartJson json) {
protected final List<String> parseResponce(SmartJson json) {
return json.getSubMessage(SmartJson.KEYS.OUTPUT)
.getSubMessage("arguments")
.getSubMessage("torrents")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, String> 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<String> parceResponce(SmartJson message);
protected abstract List<String> parseResponce(SmartJson message);

protected boolean isResultValid(SmartJson result) {
return "success".equalsIgnoreCase(result.getSubMessage(SmartJson.KEYS.OUTPUT).getValue("result"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
@Slf4j
public abstract class VoidTorrentOperator extends TransmissionWebApiExecutor {
@Override
protected List<String> parceResponce(SmartJson message) {
protected List<String> parseResponce(SmartJson message) {
List<String> result = new ArrayList<>();
result.add(String.format("Операція %s виконана без помилок", getCommandNameForOutputText()));
return result;
Expand Down

0 comments on commit 29085ad

Please sign in to comment.