Skip to content

Hw5 2 #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
9521829
Перенос проекта в новую ветку
Ray-Not Mar 25, 2023
5f4eac2
Перенос проекта в новую ветку
Ray-Not Mar 25, 2023
e900370
"Добавление дополнительной валидации"
Ray-Not Mar 25, 2023
045daf8
Небольшие исрпавления логики работы парсера
Ray-Not Mar 25, 2023
10004a7
Вторая практика (сырая)
Ray-Not Mar 28, 2023
a80dd02
Исправление планировщика
Ray-Not Apr 2, 2023
fa4c560
Добавление клиентов (сырая)
Ray-Not Apr 2, 2023
7815ad8
Клиент + мелкие поправки
Ray-Not Apr 2, 2023
76f1a45
Клиент с prop
Ray-Not Apr 3, 2023
07e9597
Клиент с prop [clean]
Ray-Not Apr 3, 2023
e05a259
+ тест для парсера
Ray-Not Apr 3, 2023
759d171
+ тест для парсера
Ray-Not Apr 3, 2023
693685e
+ бот
Ray-Not Apr 4, 2023
1ec7b83
Переименование директории
Ray-Not Apr 5, 2023
151b07f
Переделанный бот + меню для бота + DB + добавлена логика отслеживания…
Ray-Not Apr 5, 2023
dd8b30a
Добавление удаленного теста
Ray-Not Apr 5, 2023
0059fca
Добавление html-формата для сообщений и теста для бота
Ray-Not Apr 5, 2023
ab6f625
Добавление теста на формат и неизвестную команду
Ray-Not Apr 5, 2023
d7d6f7c
Добавление условной базы для хранения tgChatId, реализация API через …
Ray-Not Apr 5, 2023
787a423
Проверка
Ray-Not Apr 8, 2023
b05d5be
Докер компос + схема бд
Ray-Not Apr 11, 2023
1a69f01
Переделанная схема + переделанный compose (рабочий)
Apr 12, 2023
de3a82c
Добавление тестов
Ray-Not Apr 12, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

# IJ IDEA #
# idea
.idea
88 changes: 88 additions & 0 deletions FP/bot/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.example</groupId>
<artifactId>FP</artifactId>
<version>1.0</version>
</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>bot</artifactId>

<properties>
<starter-validation.version>3.0.1</starter-validation.version>
<starter-web.version>2.7.6</starter-web.version>
</properties>

<dependencies>
<!--Swagger UI-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
<!--Swagger UI-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>${starter-validation.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${starter-web.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--Для бота-->
<dependency>
<groupId>com.github.pengrad</groupId>
<artifactId>java-telegram-bot-api</artifactId>
<version>6.6.0</version>
</dependency>
<!--Для бота-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</dependency>
</dependencies>
</project>
21 changes: 21 additions & 0 deletions FP/bot/src/main/java/ru/tinkoff/edu/java/bot/BotApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ru.tinkoff.edu.java.bot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import ru.tinkoff.edu.java.bot.configuration.ApplicationConfig;
import ru.tinkoff.edu.java.bot.firstBot.BotMain;


@SpringBootApplication
@EnableConfigurationProperties(ApplicationConfig.class)
public class BotApplication
{
public static void main(String[] args){
var ctx = SpringApplication.run(BotApplication.class, args);
ApplicationConfig config = ctx.getBean(ApplicationConfig.class);

BotMain bot = new BotMain(config.bot().token());
bot.start();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package ru.tinkoff.edu.java.bot.api;

import org.springframework.web.bind.annotation.*;
import ru.tinkoff.edu.java.bot.api.model.LinkUpdate;

@RestController
@RequestMapping("/update")
public class BotController {

@PostMapping
public String updateChat(@RequestBody LinkUpdate update) {
return update.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package ru.tinkoff.edu.java.bot.api.exceptionHandler;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import ru.tinkoff.edu.java.bot.api.model.ApiErrorResponse;

@RestControllerAdvice
public class BotExceptionHandler {

private String getDescription(String message) {
ApiErrorResponse errorObj = new ApiErrorResponse(
message,
null,
null,
null,
null
);
return errorObj.description();
}

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String MessageNotReadable(HttpMessageNotReadableException Exception) {
return getDescription("Некорректные значения параметров или их нет!");
}

@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String MethodNotSupported(HttpRequestMethodNotSupportedException Exception) {
return getDescription("Метод не разрешен!");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ru.tinkoff.edu.java.bot.api.model;

import java.util.List;

public record ApiErrorResponse(
String description,
String code,
String exceptionName,
String exceptionMessage,
List<String> stacktrace
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package ru.tinkoff.edu.java.bot.api.model;

import java.util.List;

public record LinkUpdate(long id, String url, String description, List<Long> tgChatIds) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package ru.tinkoff.edu.java.bot.configuration;

import jakarta.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.validation.annotation.Validated;
import ru.tinkoff.edu.java.bot.configuration.configRecords.Bot;
import ru.tinkoff.edu.java.bot.configuration.configRecords.Scheduler;

@Validated
@EnableScheduling
@ConfigurationProperties(prefix = "app", ignoreUnknownFields = false)
public record ApplicationConfig(
@NotNull String test,
@NotNull Scheduler scheduler,
Bot bot
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package ru.tinkoff.edu.java.bot.configuration.configRecords;

public record Bot(String token, String name) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package ru.tinkoff.edu.java.bot.configuration.configRecords;

import java.time.Duration;

public record Scheduler(Duration interval) {}
36 changes: 36 additions & 0 deletions FP/bot/src/main/java/ru/tinkoff/edu/java/bot/firstBot/BotMain.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package ru.tinkoff.edu.java.bot.firstBot;

import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.request.SendMessage;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import ru.tinkoff.edu.java.bot.configuration.ApplicationConfig;


@EnableConfigurationProperties(ApplicationConfig.class)
public class BotMain {

String token;
static TelegramBot bot;

public BotMain(String token) {
this.token = token;
}

public void start() {
bot = new TelegramBot(token);
bot.setUpdatesListener(new Updater(bot));
}

public void end() {
bot.removeGetUpdatesListener();
}

public static void apiCommand(long tgChatId, String command) {

MessageHandler handler = new MessageHandler();
String[] parse = command.split(" ");
if(parse.length > 1) command = handler.call_command(parse[0], parse[1]);
else command = handler.call_command(parse[0]);
bot.execute(new SendMessage(tgChatId, command));
}
}
42 changes: 42 additions & 0 deletions FP/bot/src/main/java/ru/tinkoff/edu/java/bot/firstBot/DB.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package ru.tinkoff.edu.java.bot.firstBot;

import java.util.ArrayList;

public class DB {

static ArrayList<String> list = new ArrayList();

public static void addLink(String link) {
list.add(link);
}

public static void rmLink(String link) {
list.remove(link);
}

public static String getListParse() {

int i = 1;

String out_list = "";

for(String element: list){

out_list += element;

if(i != list.size()) {
out_list += ", ";
}
i++;
}
return out_list;
}

public static boolean listIsEmpty() {
return list.isEmpty();
}

public static boolean linkContain(String link) {
return list.contains(link);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package ru.tinkoff.edu.java.bot.firstBot;

import ru.tinkoff.edu.java.bot.firstBot.commands.All;

public class MessageHandler extends All {

public boolean is_command(String message) {
return message.startsWith("/");
}

public String call_command(String command, String arg) {
return switch (command) {
case "/start" -> start();
case "/help" -> help();
case "/track" -> track(arg);
case "/list" -> list();
case "/untrack" -> untrack(arg);
default -> unknow();
};
}

public String call_command(String command) {
return switch (command) {
case "/start" -> start();
case "/help" -> help();
case "/list" -> list();
default -> unknow();
};
}
}
39 changes: 39 additions & 0 deletions FP/bot/src/main/java/ru/tinkoff/edu/java/bot/firstBot/Updater.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package ru.tinkoff.edu.java.bot.firstBot;

import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.UpdatesListener;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.*;
import com.pengrad.telegrambot.request.SendMessage;

import java.util.List;

public class Updater implements UpdatesListener {

MessageHandler handler = new MessageHandler();
String command;
TelegramBot bot;

public Updater(TelegramBot bot) {
this.bot = bot;
}

@Override
public int process(List<Update> updates) {
Update update = updates.get(0);
if(handler.is_command(update.message().text())) {
String[] parse = update.message().text().split(" ");
if(parse.length > 1) command = handler.call_command(parse[0], parse[1]);
else command = handler.call_command(parse[0]);
bot.execute(
new SendMessage(update.message().chat().id(), command)
.replyMarkup(new ReplyKeyboardMarkup(new String[][]{
{"/start", "/help"},
{"/track testlink", "/untrack testlink", "/list"}
}).resizeKeyboard(true)
).parseMode(ParseMode.HTML)
);
}
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package ru.tinkoff.edu.java.bot.firstBot.commands;

public class All implements List, Start, Track, Untrack, Help {
protected String unknow() {
return "<b>Неизвестная команда</b>";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ru.tinkoff.edu.java.bot.firstBot.commands;

public interface Help {
default String help() {
return "<i>/start</i> -- зарегистрировать пользователя\n" +
"<i>/help</i> -- вывести окно с командами\n" +
"<i>/track [link]</i> -- начать отслеживание ссылки\n" +
"<i>/untrack [link]</i> -- прекратить отслеживание ссылки\n" +
"<i>/list</i> -- показать список отслеживаемых ссылок";
}
}
Loading