Skip to content

Hw5 1 #7

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 39 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 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
209e617
Добавление конфига ДБ, проверка работоспособности
Ray-Not Apr 23, 2023
5baa743
Рефактор
Ray-Not Apr 23, 2023
c9faffa
Рефакторинг кода
Ray-Not Apr 25, 2023
4556bee
Обновлена логика работы
Ray-Not Apr 25, 2023
657b91a
Фулл операции
Ray-Not Apr 30, 2023
2bb8570
GET запрос WELCOME
Ray-Not Apr 30, 2023
48c4d86
Добавлена проверка на существование через клиента
Ray-Not Apr 30, 2023
f25114d
Добавление шедула на ссылки
Ray-Not Apr 30, 2023
f04c2a7
Удаление левой папки
Ray-Not Apr 30, 2023
581e529
MOd
Ray-Not May 12, 2023
a10730d
Наводим порядок
May 18, 2023
bc06ded
Удаление промежуточных директорий
Ray-Not May 18, 2023
15a9c45
Проверка там ли gitignore
Ray-Not May 18, 2023
8de8c0f
Проверка
Ray-Not May 18, 2023
6b8385d
Измененный gitignore
Ray-Not May 18, 2023
0dd46b1
ДОбавление реадми
Ray-Not May 18, 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
9 changes: 7 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Compiled class file
*.class


# Log file
*.log

Expand All @@ -22,5 +23,9 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

# IJ IDEA #
.idea
# idea
FP/.idea/

# volumes
FP/migrations/
FP/rabbitmq/
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,78 @@
package ru.tinkoff.edu.java.bot.configuration;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.ClassMapper;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.tinkoff.edu.java.bot.api.model.LinkUpdate;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfiguration {

private final ApplicationConfig config;

public RabbitMQConfiguration(ApplicationConfig config) {
this.config = config;
}

@Bean
Queue queue() {
return QueueBuilder.durable(config.queueName())
.withArgument("x-dead-letter-exchange", config.exchangeName())
.withArgument("x-dead-letter-routing-key", config.routingKey() + ".dlq")
.build();
}


@Bean
Queue deadLetterQueue() {
return new Queue(config.queueName() + ".dlq", true);
}

@Bean
DirectExchange exchange() {
return new DirectExchange(config.exchangeName());
}

@Bean
Binding binding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(config.routingKey());
}

@Bean
Binding dlqBinding(Queue deadLetterQueue, DirectExchange exchange) {
return BindingBuilder.bind(deadLetterQueue).to(exchange).with(config.routingKey() + ".dlq");
}

@Bean
public ClassMapper classMapper() {
Map<String, Class<?>> mappings = new HashMap<>();
mappings.put("ru.tinkoff.edu.java.bot.api.model.LinkUpdate", LinkUpdate.class);

DefaultClassMapper classMapper = new DefaultClassMapper();
classMapper.setTrustedPackages("ru.tinkoff.edu.java.bot.api.model.*");
classMapper.setIdClassMapping(mappings);
return classMapper;
}

@Bean
public MessageConverter jsonMessageConverter(ClassMapper classMapper) {
Jackson2JsonMessageConverter jsonConverter = new Jackson2JsonMessageConverter();
jsonConverter.setClassMapper(classMapper);
return jsonConverter;
}


@Bean
public ScrapperQueueListener scrapperQueueListener(AmqpTemplate rabbitTemplate, UpdateService updateService) {
return new ScrapperQueueListener(rabbitTemplate, updateService);
}


}
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);
}
}
Loading