Skip to content

Commit

Permalink
Add choose of the folder option
Browse files Browse the repository at this point in the history
  • Loading branch information
galushko committed Feb 20, 2024
1 parent 64325fc commit 4292b6a
Show file tree
Hide file tree
Showing 18 changed files with 206 additions and 52 deletions.
2 changes: 1 addition & 1 deletion bot/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ dependencies {
implementation 'org.slf4j:slf4j-log4j12:+'
implementation fileTree(dir: System.getenv('CORE_LOCATION'), include: ['*.jar'])
implementation 'org.projectlombok:lombok:+'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.1'
implementation 'com.fasterxml.jackson.core:jackson-databind:+'
}

repositories {
Expand Down
2 changes: 2 additions & 0 deletions config/dockerfiles/Dockerfile-file
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
FROM openjdk:20-ea-35-jdk-slim
RUN apt-get update && apt-get install -f -y transmission-cli
RUN mkdir -p /tmp/unapproved && chmod -R 777 /tmp/unapproved
COPY file-*.jar /home/app/app.jar
COPY ./src/main/resources/log_properties /home/app
COPY ./src/main/resources/scripts /home/app
Expand Down
5 changes: 3 additions & 2 deletions config/examples/docker-compose/docker-compose-bot_debug.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ services:
restart: always
container_name: "file_debug"
volumes:
- ./workdir/config/files_from_telegram:/home/torrent_files/
- ./workdir/config/logs:/home/app/logs
- ./workdir/config/files_from_telegram:/home/torrent_files/
- ./workdir/config/files_from_telegram_hdd:/home/torrent_files_hdd/
- ./workdir/config/logs:/home/app/logs
networks:
bot_network_debug:
networks:
Expand Down
6 changes: 5 additions & 1 deletion core/src/main/java/com/halushko/kinocat/core/Commands.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@ interface Torrent {
String PAUSE = "/pause_";
String RESUME_ALL = "/resume_all";
String PAUSE_ALL = "/pause_all";
String TORRENT_INFO = "/full_info_";
String TORRENT_INFO = "/info_";
String REMOVE_WITH_FILES = "/approve_with_files_";
String REMOVE_JUST_TORRENT = "/approve_just_torrent_";
String LIST_FILES = "/files_";
String REMOVE_COMMAND = "/remove_";
}

interface File {
String SELECT_DESTINATION = "/start_";
}
}
5 changes: 5 additions & 0 deletions core/src/main/java/com/halushko/kinocat/core/Queues.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,9 @@ interface Torrent {
interface Text {
String HELP = "DISPLAY_ALL_COMMANDS";
}

interface File {
String CHOOSE_THE_DESTINATION = "FILE_CHOOSE_THE_DESTINATION";
String MOVE_TO_FOLDER = "FILE_MOVE_TO_FOLDER";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ public abstract class CliCommandExecutor extends InputMessageHandler {
@Override
protected String getDeliverCallbackPrivate(SmartJson rabbitMessage) {
long userId = rabbitMessage.getUserId();
String script = rabbitMessage.getText();

String script = getScript(rabbitMessage);
log.debug("[ExternalCliCommandExecutor] userId:{}, script:{}", userId, script);

try {
Expand All @@ -34,11 +33,11 @@ protected String getResultString(List<String> lines, SmartJson rabbitMessage) {
}

protected List<String> executeViaCLI(String script) {
String command = String.format("sh %s%s", "/home/app/", script);
log.debug("[executeViaCLI] Execute script: {}", command);
// String command = String.format("sh %s%s", "/home/app/", script);
log.debug("[executeViaCLI] Execute script: {}", script);
List<String> result = new ArrayList<>();

ProcessBuilder processBuilder = new ProcessBuilder(command);
ProcessBuilder processBuilder = new ProcessBuilder(script);
processBuilder.redirectErrorStream(true);

try {
Expand All @@ -60,4 +59,8 @@ protected List<String> executeViaCLI(String script) {
result.forEach(log::debug);
return result;
}

protected String getScript(SmartJson rabbitMessage){
return rabbitMessage.getText();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ private void getDeliverCallbackLog(SmartJson message) {
protected String printResult(long chatId, String text){
String replacedString = text.replaceAll(OUTPUT_SEPARATOR + "(?=" + OUTPUT_SEPARATOR + ")", ",");
RabbitUtils.postMessage(chatId, replacedString, Queues.Telegram.TELEGRAM_OUTPUT_TEXT);
return "";
return replacedString;
}

@SuppressWarnings("unused")
Expand Down
16 changes: 16 additions & 0 deletions file/src/main/java/com/halushko/kinocat/file/Constants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.halushko.kinocat.file;

import java.util.Map;
import java.util.stream.Collectors;

public interface Constants {
String PATH_TO_UNAPPROVED_FOLDER = "/tmp/unapproved";
String PATH_TO_DESTINATION_FOLDER = "/home/torrent_files";
String EMPTY_SERVICE_DEFAULT_NAME = "main";
Map<String, String> FOLDERS = new FoldersProcessor(System.getenv("TORRENT_IP"))
.values.keySet().stream()
.collect(Collectors.toMap(key -> key, key -> String.format(PATH_TO_DESTINATION_FOLDER + "%s", !key.isEmpty() ? "_" + key : "")));
String NAME_LINE = "^\\s+Name:\\s+";
String SIZE_LINE = "^\\s+Total Size:\\s+";

}
30 changes: 30 additions & 0 deletions file/src/main/java/com/halushko/kinocat/file/FoldersProcessor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.halushko.kinocat.file;

import com.halushko.kinocat.core.JsonConstants;
import com.halushko.kinocat.core.prcessors.ServicesInfoProcessor;
import com.halushko.kinocat.core.prcessors.ValueProcessor;

import java.util.ArrayList;
import java.util.List;

public class FoldersProcessor extends ServicesInfoProcessor {

public FoldersProcessor(String json) {
super(json);
}

@Override
public ValueProcessor getNameProcessor() {
return new ValueProcessor(JsonConstants.WebKeys.KEY_NAME, "");
}

@Override
public List<ValueProcessor> getServiceProcessors() {
return new ArrayList<>();
}

@Override
public String getUrlTemplate() {
return "";
}
}
2 changes: 2 additions & 0 deletions file/src/main/java/com/halushko/kinocat/file/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ public static void main(String[] args) {
System.out.println("Hello world! I'm fileConsumer!");
org.apache.log4j.BasicConfigurator.configure();
new UserMessageHandler().run();
new PrintDestinations().run();
new MoveToDestinationFolder().run();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.halushko.kinocat.file;

import com.halushko.kinocat.core.JsonConstants.SmartJsonKeys;
import com.halushko.kinocat.core.Queues;
import com.halushko.kinocat.core.handlers.input.CliCommandExecutor;
import com.halushko.kinocat.core.rabbit.SmartJson;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.UUID;

@Slf4j
public class MoveToDestinationFolder extends CliCommandExecutor {
@Override
protected String getQueue() {
return Queues.File.MOVE_TO_FOLDER;
}

@Override
protected String getScript(SmartJson rabbitMessage) {
List<Object> arguments = rabbitMessage.getSubMessage(SmartJsonKeys.COMMAND_ARGUMENTS).convertToList();
String folder = (String) arguments.get(0);
String file = (String) arguments.get(1);

return String.format("mv -f %s/%s.torrent %s/%s.torrent",
Constants.PATH_TO_UNAPPROVED_FOLDER,
file,
Constants.FOLDERS.get(folder),
UUID.randomUUID()
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.halushko.kinocat.file;

import com.halushko.kinocat.core.Commands;
import com.halushko.kinocat.core.JsonConstants.SmartJsonKeys;
import com.halushko.kinocat.core.Queues;
import com.halushko.kinocat.core.handlers.input.CliCommandExecutor;
import com.halushko.kinocat.core.rabbit.SmartJson;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class PrintDestinations extends CliCommandExecutor {
@Override
protected String getResultString(List<String> lines, SmartJson rabbitMessage) {
String[] result = new String[4];
result[0] = "(";
result[2] = ") ";
for (String line : lines) {
if (line.matches(Constants.NAME_LINE)) {
result[3] = line.replaceFirst(Constants.NAME_LINE, "");
}
if (line.matches(Constants.SIZE_LINE)) {
result[1] = line.replaceFirst(Constants.SIZE_LINE, "");
}
}
String fileName = rabbitMessage.getValue(SmartJsonKeys.FILE_ID).replaceAll("\\.torrent$", "");
return String.format("%s%s",
String.join("", result),
Constants.FOLDERS.keySet().stream()
.map(folder ->
String.format("\\n%s: %s_%s_%s",
getServiceLable(folder),
Commands.File.SELECT_DESTINATION,
getServiceLable(folder),
fileName
)
)
.collect(Collectors.joining(""))
);
}

private static String getServiceLable(String folder) {
return folder.isEmpty() ? Constants.EMPTY_SERVICE_DEFAULT_NAME : folder;
}

@Override
protected String getQueue() {
return Queues.File.CHOOSE_THE_DESTINATION;
}

@Override
protected String getScript(SmartJson rabbitMessage) {
return String.format("transmission-show %s", rabbitMessage.getValue(SmartJsonKeys.FILE_PATH));
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
package com.halushko.kinocat.file;

import com.halushko.kinocat.core.JsonConstants.SmartJsonKeys;
import com.halushko.kinocat.core.JsonConstants.WebKeys;
import com.halushko.kinocat.core.Queues;
import com.halushko.kinocat.core.handlers.input.InputMessageHandler;
import com.halushko.kinocat.core.rabbit.RabbitUtils;
import com.halushko.kinocat.core.rabbit.SmartJson;
import com.halushko.kinocat.core.prcessors.ServicesInfoProcessor;
import com.halushko.kinocat.core.prcessors.ValueProcessor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

Expand All @@ -16,13 +13,11 @@
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class UserMessageHandler extends InputMessageHandler {
private final static List<String> folders = new FoldersProcessor(System.getenv("TORRENT_IP")).values.keySet().stream().toList();
private final static String FILE_URL_PREFIX = String.format("%s%s/", "https://api.telegram.org/file/bot", System.getenv("BOT_TOKEN"));

@Override
protected String getDeliverCallbackPrivate(SmartJson rabbitMessage) {
try {
Expand All @@ -38,24 +33,41 @@ protected String getDeliverCallbackPrivate(SmartJson rabbitMessage) {

protected void handleTorrent(SmartJson rm) throws MalformedURLException {
long fileSize = Long.parseLong(rm.getValue(SmartJsonKeys.SIZE));
long userId = rm.getUserId();
if (fileSize > 5242880L) {
log.warn(String.format("The file size is too big for .torrent (more than 0.5 Mb). Size = %s bytes", fileSize));
String error = String.format("The file size is too big for .torrent (more than 5 Mb). Size = %s Mb", ((double) fileSize) / (1024 * 1024));
log.warn(error);
RabbitUtils.postMessage(userId, error, Queues.Telegram.TELEGRAM_OUTPUT_TEXT);
return;
}
URL fileUrl = java.net.URI.create(FILE_URL_PREFIX + rm.getValue(SmartJsonKeys.FILE_PATH)).toURL();
long userId = rm.getUserId();
String fileName = String.format("%s%s", rm.getValue(SmartJsonKeys.FILE_ID), ".torrent");
String message = rm.getValue(SmartJsonKeys.CAPTION);

if(message == null || message.trim().isEmpty()) {
message = "";
if (Constants.FOLDERS.size() > 1) {
sendToChoose(userId, fileUrl);
} else {
sendToDownload(fileName, fileUrl, userId);
}
message = message.trim().toLowerCase();
message = folders.contains(message) ? "_" + message : "";
}

private static void sendToDownload(String fileName, URL fileUrl, long userId) {
File localFile = new File(String.format("%s/%s", Constants.PATH_TO_DESTINATION_FOLDER, fileName));
try (InputStream is = fileUrl.openStream()) {
FileUtils.copyInputStreamToFile(is, localFile);
} catch (IOException e) {
RabbitUtils.postMessage(userId, e.getMessage(), Queues.Telegram.TELEGRAM_OUTPUT_TEXT);
}
}

File localFile = new File(String.format("/home/torrent_files%s/%s", message, fileName));
private static void sendToChoose(long userId, URL fileUrl) {
String fileName = fileUrl.getFile().replaceAll(".*/", "");
File localFile = new File(String.format("%s/%s", Constants.PATH_TO_UNAPPROVED_FOLDER, fileName));
try (InputStream is = fileUrl.openStream()) {
FileUtils.copyInputStreamToFile(is, localFile);
SmartJson message = new SmartJson(userId)
.addValue(SmartJsonKeys.FILE_PATH, localFile.getAbsolutePath())
.addValue(SmartJsonKeys.FILE_ID, fileName);
RabbitUtils.postMessage(message, Queues.File.CHOOSE_THE_DESTINATION);
} catch (IOException e) {
RabbitUtils.postMessage(userId, e.getMessage(), Queues.Telegram.TELEGRAM_OUTPUT_TEXT);
}
Expand All @@ -65,26 +77,4 @@ protected void handleTorrent(SmartJson rm) throws MalformedURLException {
protected String getQueue() {
return Queues.Telegram.TELEGRAM_INPUT_FILE;
}

private static class FoldersProcessor extends ServicesInfoProcessor{

public FoldersProcessor(String json) {
super(json);
}

@Override
public ValueProcessor getNameProcessor() {
return new ValueProcessor(WebKeys.KEY_NAME, "");
}

@Override
public List<ValueProcessor> getServiceProcessors() {
return new ArrayList<>();
}

@Override
public String getUrlTemplate() {
return "";
}
}
}
5 changes: 5 additions & 0 deletions text/src/main/java/com/halushko/kinocat/text/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,5 +70,10 @@ public interface Constants {
Queues.Text.HELP,
"вивести інформацію по всім командам"
);

addValue(Commands.File.SELECT_DESTINATION,
Queues.File.MOVE_TO_FOLDER,
"<папка> <файл> обрати в яку папку буде завантаження"
);
}};
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class CommandsCollection {

public void addValue(String command, String queue, String description, CommandProperties... additionalProperties) {
values.add(new Command(command, queue, description, additionalProperties));
if (Arrays.stream(additionalProperties).anyMatch(x -> x == CommandProperties.CONTAINS_SERVER_NUMBER)) {
if (!command.endsWith("_") && Arrays.stream(additionalProperties).anyMatch(x -> x == CommandProperties.CONTAINS_SERVER_NUMBER)) {
values.add(new Command(command + "_", queue, description, additionalProperties));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,18 @@ public TorrentEntity(Object obj) {
files.forEach(file -> this.files.add(new SubTorrentEntity(file, id)));

this.lastActivityDate = getDate(torrent.getValue("activityDate"));
this.dateCreated = getDate(torrent.getValue("dateCreated"));
this.dateCreated = getDate(torrent.getValue("dateCreated")); //TODO check
this.addedDate = getDate(torrent.getValue("addedDate"));
}

private static String getDate(String strValue) {
if(strValue.isEmpty()) return "";
val timestamp = Long.parseLong(strValue);
long timestamp;
try {
timestamp = Long.parseLong(strValue);
} catch (NumberFormatException e) {
timestamp = 0;
}
Instant instant = Instant.ofEpochSecond(timestamp);
ZonedDateTime date = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
return date.format(FORMATTER);
Expand Down
Loading

0 comments on commit 4292b6a

Please sign in to comment.