Merge pull request 'feature/task-38-roles' (#42) from feature/task-38-roles into master
Hedgehog_server_CD/ServerMonitorBot/pipeline/head Something is wrong with the build of this commit
Details
Hedgehog_server_CD/ServerMonitorBot/pipeline/head Something is wrong with the build of this commit
Details
Reviewed-on: #42master
commit
7bdcf10cd2
48
pom.xml
48
pom.xml
|
@ -5,7 +5,7 @@
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>3.1.2</version>
|
<version>3.4.0</version>
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
</parent>
|
</parent>
|
||||||
<groupId>ru.ldeloff</groupId>
|
<groupId>ru.ldeloff</groupId>
|
||||||
|
@ -15,10 +15,6 @@
|
||||||
<description>ServerMonitorBot</description>
|
<description>ServerMonitorBot</description>
|
||||||
<properties>
|
<properties>
|
||||||
<java.version>17</java.version>
|
<java.version>17</java.version>
|
||||||
<flyway.version>9.16.0</flyway.version>
|
|
||||||
<db.url>${database.url}</db.url>
|
|
||||||
<db.user>${database.username}</db.user>
|
|
||||||
<db.password>${database.password}</db.password>
|
|
||||||
<start-class>ru.ldeloff.servermonitorbot.ServerMonitorBotApplication</start-class>
|
<start-class>ru.ldeloff.servermonitorbot.ServerMonitorBotApplication</start-class>
|
||||||
</properties>
|
</properties>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -26,7 +22,6 @@
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter</artifactId>
|
<artifactId>spring-boot-starter</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
|
@ -45,26 +40,13 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.telegram</groupId>
|
<groupId>org.telegram</groupId>
|
||||||
<artifactId>telegrambots</artifactId>
|
<artifactId>telegrambots</artifactId>
|
||||||
<version>6.8.0</version>
|
<version>6.9.7.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.jcraft</groupId>
|
<groupId>com.jcraft</groupId>
|
||||||
<artifactId>jsch</artifactId>
|
<artifactId>jsch</artifactId>
|
||||||
<version>0.1.55</version>
|
<version>0.1.55</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.postgresql</groupId>
|
|
||||||
<artifactId>postgresql</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.flywaydb</groupId>
|
|
||||||
<artifactId>flyway-core</artifactId>
|
|
||||||
<version>${flyway.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -80,32 +62,6 @@
|
||||||
</exclude>
|
</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.flywaydb</groupId>
|
|
||||||
<artifactId>flyway-maven-plugin</artifactId>
|
|
||||||
<version>${flyway.version}</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>migrate</id>
|
|
||||||
<phase>deploy</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>migrate</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
<configuration>
|
|
||||||
<url>${database.url}</url>
|
|
||||||
<user>${database.username}</user>
|
|
||||||
<password>${database.password}</password>
|
|
||||||
<locations>
|
|
||||||
<location>classpath:db/migration</location>
|
|
||||||
</locations>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<goals>
|
<goals>
|
||||||
|
|
|
@ -3,10 +3,12 @@ package ru.ldeloff.servermonitorbot;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
import ru.ldeloff.servermonitorbot.config.SshConfig;
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.server.SshServers;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@EnableConfigurationProperties(SshConfig.class)
|
@EnableScheduling
|
||||||
|
@EnableConfigurationProperties(SshServers.class)
|
||||||
public class ServerMonitorBotApplication {
|
public class ServerMonitorBotApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.command;
|
package ru.ldeloff.servermonitorbot.commands;
|
||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
@ -6,15 +6,13 @@ import lombok.Setter;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
import ru.ldeloff.servermonitorbot.model.user.Role;
|
||||||
import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
||||||
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
import ru.ldeloff.servermonitorbot.model.user.User;
|
||||||
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
||||||
import ru.ldeloff.servermonitorbot.utils.SshServerUtils;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
@ -23,31 +21,32 @@ import java.util.Objects;
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public abstract class CommandTemplate {
|
public abstract class CommandTemplate {
|
||||||
private final UserService userService;
|
|
||||||
private final RoleService roleService;
|
private final UpdateUtil updateUtil;
|
||||||
private final ServerListButtons serverListButtons;
|
private final ServerListButtons serverListButtons;
|
||||||
private final SshService sshService;
|
public final SshService sshService;
|
||||||
|
private final MessagingService messagingService;
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
private long expectedRole = 1L;
|
private List<Role> expectedRole = List.of(Role.ADMIN);
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
public boolean execute(Update update, TelegramBotController bot) {
|
public boolean execute(Update update) {
|
||||||
if (!isExecute(update)) {
|
if (!isExecute(update)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
User user = getUser(update);
|
User user = updateUtil.getUser(update);
|
||||||
String message = getMessage(update);
|
String message = updateUtil.getMessage(update);
|
||||||
SendMessage answer = new SendMessage();
|
SendMessage answer = new SendMessage();
|
||||||
answer.setChatId(user.getTelegramId());
|
answer.setChatId(user.getTelegramId());
|
||||||
answer.setText(message);
|
answer.setText(message);
|
||||||
|
|
||||||
if (!isAuth(update)) {
|
if (!updateUtil.roleChecker(update, expectedRole)) {
|
||||||
logNotAuth(user, message);
|
logNotAuth(user, message);
|
||||||
sendMessage(actionForNotAuth(user, answer), bot);
|
messagingService.send(actionForNotAuth(user, answer));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -55,11 +54,11 @@ public abstract class CommandTemplate {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case "aggregate":
|
case "aggregate":
|
||||||
logSuccess(user, message);
|
logSuccess(user, message);
|
||||||
sendMessage(executeAggregate(user, answer), bot);
|
messagingService.send(executeAggregate(user, answer));
|
||||||
return true;
|
return true;
|
||||||
case "command":
|
case "command":
|
||||||
logSuccess(user, message);
|
logSuccess(user, message);
|
||||||
sendMessage(executeCommand(user, answer), bot);
|
messagingService.send(executeCommand(user, answer));
|
||||||
return true;
|
return true;
|
||||||
default:
|
default:
|
||||||
return false;
|
return false;
|
||||||
|
@ -72,7 +71,7 @@ public abstract class CommandTemplate {
|
||||||
if (update.getMessage().hasText()) {
|
if (update.getMessage().hasText()) {
|
||||||
String messageText = update.getMessage().getText();
|
String messageText = update.getMessage().getText();
|
||||||
if (Objects.equals(messageText, name)) {
|
if (Objects.equals(messageText, name)) {
|
||||||
log.debug("Команда " + messageText + " будет выполнена");
|
log.debug("Команда {} будет выполнена", messageText);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -80,7 +79,7 @@ public abstract class CommandTemplate {
|
||||||
String [] tags = update.getCallbackQuery().getData().split(":");
|
String [] tags = update.getCallbackQuery().getData().split(":");
|
||||||
if (tags.length > 1) {
|
if (tags.length > 1) {
|
||||||
if (Objects.equals(tags[0], name)) {
|
if (Objects.equals(tags[0], name)) {
|
||||||
log.debug("Команда " + tags[0] + " будет выполнена");
|
log.debug("Команда {} будет выполнена", tags[0]);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
@ -106,19 +105,17 @@ public abstract class CommandTemplate {
|
||||||
}
|
}
|
||||||
return "error";
|
return "error";
|
||||||
}
|
}
|
||||||
private boolean isAuth(Update update) {
|
|
||||||
User user = getUser(update);
|
|
||||||
return user.getRole().getId() <= expectedRole;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Методы при верных условиях
|
// Методы при верных условиях
|
||||||
void logSuccess(User user, String message) {
|
void logSuccess(User user, String message) {
|
||||||
log.info("Получена команда '" + message + "' от " + user.getLogin()
|
log.info("Получена команда '{}' от {} ({}). OK", message, user.getLogin(), user.getTelegramId());
|
||||||
+ " (" + user.getTelegramId() + "). OK");
|
|
||||||
}
|
}
|
||||||
SendMessage executeAggregate(User user, SendMessage message) {
|
|
||||||
|
public SendMessage executeAggregate(User user, SendMessage message) {
|
||||||
return serverListButtons.uiForm(message);
|
return serverListButtons.uiForm(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
SendMessage executeCommand(User user, SendMessage message) {
|
SendMessage executeCommand(User user, SendMessage message) {
|
||||||
String [] tags = Arrays.stream(message.getText().split(":"))
|
String [] tags = Arrays.stream(message.getText().split(":"))
|
||||||
.map(String::trim)
|
.map(String::trim)
|
||||||
|
@ -132,7 +129,7 @@ public abstract class CommandTemplate {
|
||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
private String executeCommandAllHost() {
|
private String executeCommandAllHost() {
|
||||||
List<SshServer> servers = SshServerUtils.filterGoodServers(sshService.getSshServers());
|
List<SshServer> servers = sshService.getHealthSshServers();
|
||||||
StringBuilder response = new StringBuilder();
|
StringBuilder response = new StringBuilder();
|
||||||
servers.forEach(server -> response.append(executeCommandSpecificHost(server.getName())).append("\n"));
|
servers.forEach(server -> response.append(executeCommandSpecificHost(server.getName())).append("\n"));
|
||||||
return response.toString();
|
return response.toString();
|
||||||
|
@ -149,44 +146,4 @@ public abstract class CommandTemplate {
|
||||||
+ ") недостаточно прав для выполнения этой команды");
|
+ ") недостаточно прав для выполнения этой команды");
|
||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Общее
|
|
||||||
// TODO: вынести в UpdateUtils
|
|
||||||
User getUser(Update update) {
|
|
||||||
long id = -1L;
|
|
||||||
String login = null;
|
|
||||||
if (update.hasMessage()) {
|
|
||||||
id = update.getMessage().getChat().getId();
|
|
||||||
login = update.getMessage().getChat().getUserName();
|
|
||||||
} else if (update.hasCallbackQuery()) {
|
|
||||||
id = update.getCallbackQuery().getMessage().getChat().getId();
|
|
||||||
login = update.getCallbackQuery().getMessage().getChat().getUserName();
|
|
||||||
}
|
|
||||||
User user = userService.getByTelegramId(id);
|
|
||||||
if (user == null) {
|
|
||||||
user = new User();
|
|
||||||
user.setTelegramId(id);
|
|
||||||
user.setRole(roleService.findRoleById(3L));
|
|
||||||
}
|
|
||||||
user.setLogin(login);
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
String getMessage(Update update) {
|
|
||||||
if (update.hasMessage()) {
|
|
||||||
return update.getMessage().getText();
|
|
||||||
} else if (update.hasCallbackQuery()) {
|
|
||||||
return update.getCallbackQuery().getData();
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: вынести
|
|
||||||
public static void sendMessage(SendMessage message, TelegramBotController bot) {
|
|
||||||
try {
|
|
||||||
bot.execute(message);
|
|
||||||
} catch (TelegramApiException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
log.warn(e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.commands.cpu.temp.service;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
||||||
|
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
|
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class CpuTemp extends CommandTemplate {
|
||||||
|
|
||||||
|
public CpuTemp(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
||||||
|
super(updateUtil, serverListButtons, sshService, messagingService);
|
||||||
|
setName("CPU.temp");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String executeCommandSpecificHost(String serverName) {
|
||||||
|
try {
|
||||||
|
Optional<SshServer> server = sshService.getAllSshServers()
|
||||||
|
.stream()
|
||||||
|
.filter(x -> x.getName().equals(serverName))
|
||||||
|
.findFirst();
|
||||||
|
if (server.isPresent()) {
|
||||||
|
SshCommand result = sshService.execute(new SshCommand("cat /sys/class/thermal/thermal_zone0/temp", 100, server.get()));
|
||||||
|
return server.get().getName() + ": \n" +
|
||||||
|
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" :
|
||||||
|
String.format("%.1f",
|
||||||
|
Double.parseDouble(result.getResponse().replaceAll("\n", ""))/1000))
|
||||||
|
+ "°C";
|
||||||
|
} else {
|
||||||
|
log.error("Ошибка при выполнении команды 'CPUtemp'. Искомый сервер ({}) не найден", serverName);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
log.error("Ошибка при выполнении команды 'CPUtemp'" ,e.getMessage());
|
||||||
|
return "Сервер " + serverName + " не поддерживает команду 'CPUtemp'";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,28 +1,29 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.command;
|
package ru.ldeloff.servermonitorbot.commands.hdd.mdadm.service;
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
||||||
|
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class MdadmStatusCommand extends CommandTemplate {
|
public class MdadmStatus extends CommandTemplate {
|
||||||
final SshService sshService;
|
|
||||||
public MdadmStatusCommand(UserService userService, RoleService roleService, SshService sshService, ServerListButtons serverListButtons) {
|
public MdadmStatus(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
||||||
super(userService, roleService, serverListButtons, sshService);
|
super(updateUtil, serverListButtons, sshService, messagingService);
|
||||||
this.sshService = sshService;
|
|
||||||
setName("MDADM");
|
setName("MDADM");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
public String executeCommandSpecificHost(String serverName) {
|
||||||
Optional<SshServer> server = sshService.getSshServers()
|
Optional<SshServer> server = sshService.getAllSshServers()
|
||||||
.stream()
|
.stream()
|
||||||
.filter(x -> x.getName().equals(serverName))
|
.filter(x -> x.getName().equals(serverName))
|
||||||
.findFirst();
|
.findFirst();
|
||||||
|
@ -40,10 +41,11 @@ public class MdadmStatusCommand extends CommandTemplate {
|
||||||
});
|
});
|
||||||
return server.get().getName() + ": \n" + result;
|
return server.get().getName() + ": \n" + result;
|
||||||
} else {
|
} else {
|
||||||
log.error("Ошибка при выполнении команды 'mdadm'. Искомый сервер (" + serverName + ") не найден");
|
log.error("Ошибка при выполнении команды 'mdadm'. Искомый сервер ({}) не найден", serverName);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<String> parseRaidNames(SshCommand result) {
|
private List<String> parseRaidNames(SshCommand result) {
|
||||||
List<String> names = new ArrayList<>();
|
List<String> names = new ArrayList<>();
|
||||||
Arrays.stream(result.getResponse().split("\n"))
|
Arrays.stream(result.getResponse().split("\n"))
|
||||||
|
@ -53,6 +55,7 @@ public class MdadmStatusCommand extends CommandTemplate {
|
||||||
.forEach(names::add);
|
.forEach(names::add);
|
||||||
return names;
|
return names;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<String> parseHddState(SshCommand result) {
|
private List<String> parseHddState(SshCommand result) {
|
||||||
List<String> names = new ArrayList<>();
|
List<String> names = new ArrayList<>();
|
||||||
names.add("Number Name State");
|
names.add("Number Name State");
|
|
@ -1,29 +1,29 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.command;
|
package ru.ldeloff.servermonitorbot.commands.hdd.temp.service;
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
||||||
|
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class HddTempCommand extends CommandTemplate {
|
public class HddTemp extends CommandTemplate {
|
||||||
final SshService sshService;
|
public HddTemp(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
||||||
public HddTempCommand(UserService userService, RoleService roleService, SshService sshService, ServerListButtons serverListButtons) {
|
super(updateUtil, serverListButtons, sshService, messagingService);
|
||||||
super(userService, roleService, serverListButtons, sshService);
|
|
||||||
this.sshService = sshService;
|
|
||||||
setName("HDD.temp");
|
setName("HDD.temp");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
public String executeCommandSpecificHost(String serverName) {
|
||||||
Optional<SshServer> server = sshService.getSshServers()
|
Optional<SshServer> server = sshService.getAllSshServers()
|
||||||
.stream()
|
.stream()
|
||||||
.filter(x -> x.getName().equals(serverName))
|
.filter(x -> x.getName().equals(serverName))
|
||||||
.findFirst();
|
.findFirst();
|
|
@ -0,0 +1,18 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.commands.statuschecker.scheduler;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CheckSessionStatusScheduler {
|
||||||
|
|
||||||
|
private final SshService sshService;
|
||||||
|
|
||||||
|
@Scheduled(fixedRateString = "${ssh.checkConnectionDelay}")
|
||||||
|
public void updateSessionStatusCheck() {
|
||||||
|
sshService.updateConnection();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.commands.statuschecker.service;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
||||||
|
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
|
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class CheckSessionStatus extends CommandTemplate {
|
||||||
|
|
||||||
|
public CheckSessionStatus(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
||||||
|
super(updateUtil, serverListButtons, sshService, messagingService);
|
||||||
|
setName("Статус");
|
||||||
|
}
|
||||||
|
|
||||||
|
public SendMessage executeAggregate(User user, SendMessage message) {
|
||||||
|
return super.sshService.getStatusSessions(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String executeCommandSpecificHost(String serverName) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,29 +1,30 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.command;
|
package ru.ldeloff.servermonitorbot.commands.uname.service;
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
||||||
|
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
import ru.ldeloff.servermonitorbot.view.ServerListButtons;
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class UnameCommand extends CommandTemplate {
|
public class Uname extends CommandTemplate {
|
||||||
final SshService sshService;
|
|
||||||
public UnameCommand(UserService userService, RoleService roleService, SshService sshService, ServerListButtons serverListButtons) {
|
public Uname(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, MessagingService messagingService) {
|
||||||
super(userService, roleService, serverListButtons, sshService);
|
super(updateUtil, serverListButtons, sshService, messagingService);
|
||||||
this.sshService = sshService;
|
|
||||||
setName("uname");
|
setName("uname");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
public String executeCommandSpecificHost(String serverName) {
|
||||||
Optional<SshServer> server = sshService.getSshServers()
|
Optional<SshServer> server = sshService.getAllSshServers()
|
||||||
.stream()
|
.stream()
|
||||||
.filter(x -> x.getName().equals(serverName))
|
.filter(x -> x.getName().equals(serverName))
|
||||||
.findFirst();
|
.findFirst();
|
||||||
|
@ -32,7 +33,7 @@ public class UnameCommand extends CommandTemplate {
|
||||||
return server.get().getName() + ": " +
|
return server.get().getName() + ": " +
|
||||||
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" : result.getResponse());
|
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" : result.getResponse());
|
||||||
} else {
|
} else {
|
||||||
log.error("Ошибка при выполнении команды 'uname'. Искомый сервер (" + serverName + ") не найден");
|
log.error("Ошибка при выполнении команды 'uname'. Искомый сервер ({}) не найден", serverName);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -2,16 +2,37 @@ package ru.ldeloff.servermonitorbot.config;
|
||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.stereotype.Component;
|
||||||
import ru.ldeloff.servermonitorbot.model.dto.InitUserDto;
|
import ru.ldeloff.servermonitorbot.model.user.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.RoleService;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Configuration
|
@Component
|
||||||
@ConfigurationProperties(prefix = "bot")
|
@ConfigurationProperties(prefix = "bot")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
public class UserConfig {
|
public class UserConfig {
|
||||||
private List<InitUserDto> users;
|
|
||||||
|
private List<UserProperty> users;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RoleService roleService;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public static class UserProperty {
|
||||||
|
private Long telegramId;
|
||||||
|
private String role;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<User> getUsers() {
|
||||||
|
return users.stream().map(user -> new User()
|
||||||
|
.setTelegramId(user.getTelegramId())
|
||||||
|
.setRole(roleService.findRoleByName(user.getRole()))
|
||||||
|
).toList();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,24 +6,28 @@ import org.telegram.telegrambots.bots.TelegramLongPollingBot;
|
||||||
import org.telegram.telegrambots.meta.api.objects.Message;
|
import org.telegram.telegrambots.meta.api.objects.Message;
|
||||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||||
import ru.ldeloff.servermonitorbot.model.TelegramBot;
|
import ru.ldeloff.servermonitorbot.model.TelegramBot;
|
||||||
import ru.ldeloff.servermonitorbot.repository.SshRepository;
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
||||||
import ru.ldeloff.servermonitorbot.service.command.SwitchToMainMenu;
|
import ru.ldeloff.servermonitorbot.view.SwitchToMainMenu;
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class TelegramBotController extends TelegramLongPollingBot {
|
public class TelegramBotController extends TelegramLongPollingBot {
|
||||||
|
|
||||||
private final Map<String, CommandTemplate> commands;
|
private final Map<String, CommandTemplate> commands;
|
||||||
final TelegramBot telegramBot;
|
|
||||||
final SshRepository sshRepository;
|
private final TelegramBot telegramBot;
|
||||||
final SwitchToMainMenu switchToMainMenu;
|
private final SwitchToMainMenu switchToMainMenu;
|
||||||
|
private final SshService sshService;
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onUpdateReceived(Update update) {
|
public void onUpdateReceived(Update update) {
|
||||||
boolean result = false;
|
boolean result = false;
|
||||||
for (Map.Entry<String, CommandTemplate> entry : commands.entrySet()) {
|
for (Map.Entry<String, CommandTemplate> entry : commands.entrySet()) {
|
||||||
result = entry.getValue().execute(update, this);
|
result = entry.getValue().execute(update);
|
||||||
if (result) {
|
if (result) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -34,20 +38,23 @@ public class TelegramBotController extends TelegramLongPollingBot {
|
||||||
message.setText("Not found");
|
message.setText("Not found");
|
||||||
}
|
}
|
||||||
update.setMessage(message);
|
update.setMessage(message);
|
||||||
switchToMainMenu.execute(update, this);
|
switchToMainMenu.execute(update);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getBotUsername() {
|
public String getBotUsername() {
|
||||||
return telegramBot.getBotUsername();
|
return telegramBot.getBotUsername();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getBotToken() {
|
public String getBotToken() {
|
||||||
return telegramBot.getBotToken();
|
return telegramBot.getBotToken();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onClosing() {
|
public void onClosing() {
|
||||||
super.onClosing();
|
super.onClosing();
|
||||||
sshRepository.disconnectSessions();
|
sshService.disconnectAllConnections();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.init;
|
|
||||||
|
|
||||||
public class AddCommands {
|
|
||||||
public static void fillCommandTable() {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,34 +1,26 @@
|
||||||
package ru.ldeloff.servermonitorbot.init;
|
package ru.ldeloff.servermonitorbot.init;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.boot.ApplicationArguments;
|
import org.springframework.boot.ApplicationArguments;
|
||||||
import org.springframework.boot.ApplicationRunner;
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import ru.ldeloff.servermonitorbot.config.UserConfig;
|
import ru.ldeloff.servermonitorbot.config.UserConfig;
|
||||||
import ru.ldeloff.servermonitorbot.mapper.UserMapper;
|
import ru.ldeloff.servermonitorbot.service.UserService;
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.dto.InitUserDto;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Order(2)
|
||||||
public class AddUsers implements ApplicationRunner {
|
public class AddUsers implements ApplicationRunner {
|
||||||
final List<InitUserDto> initUsers;
|
|
||||||
final UserService userService;
|
|
||||||
final UserMapper userMapper;
|
|
||||||
|
|
||||||
@Autowired
|
final UserConfig userConfig;
|
||||||
public AddUsers(UserConfig userConfig, UserService userService, UserMapper userMapper) {
|
final UserService userService;
|
||||||
this.initUsers = userConfig.getUsers();
|
|
||||||
this.userService = userService;
|
|
||||||
this.userMapper = userMapper;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run(ApplicationArguments args) throws Exception {
|
public void run(ApplicationArguments args) {
|
||||||
initUsers.forEach(initUserDto -> {
|
userConfig.getUsers().forEach(userService::saveOrUpdateUser);
|
||||||
User user = userService.saveOrUpdateUser(userMapper.dtoToUser(initUserDto));
|
log.info("Загружены и обновлены пользователи");
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,33 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.init;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.ApplicationArguments;
|
||||||
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.UserService;
|
||||||
|
import ru.ldeloff.servermonitorbot.view.TelegramBotKeyboard;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Order(3)
|
||||||
|
public class ReloadNotification implements ApplicationRunner {
|
||||||
|
|
||||||
|
private final TelegramBotKeyboard telegramBotKeyboard;
|
||||||
|
private final MessagingService messagingService;
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(ApplicationArguments args) {
|
||||||
|
userService.getAllUsers().forEach(user -> {
|
||||||
|
SendMessage sendMessage = new SendMessage();
|
||||||
|
sendMessage.setChatId(user.getTelegramId());
|
||||||
|
sendMessage.setText("Бот перезапущен");
|
||||||
|
messagingService.send(telegramBotKeyboard.uiForm(sendMessage));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,20 +1,21 @@
|
||||||
package ru.ldeloff.servermonitorbot.init;
|
package ru.ldeloff.servermonitorbot.init;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.boot.ApplicationArguments;
|
import org.springframework.boot.ApplicationArguments;
|
||||||
import org.springframework.boot.ApplicationRunner;
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import ru.ldeloff.servermonitorbot.repository.SshRepository;
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Order(4)
|
||||||
public class SshConnect implements ApplicationRunner {
|
public class SshConnect implements ApplicationRunner {
|
||||||
final SshRepository sshRepository;
|
|
||||||
|
|
||||||
public SshConnect(SshRepository sshRepository) {
|
final SshService sshService;
|
||||||
this.sshRepository = sshRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run(ApplicationArguments args) throws Exception {
|
public void run(ApplicationArguments args) {
|
||||||
sshRepository.connectToAllServer();
|
sshService.updateConnection();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,53 +1,33 @@
|
||||||
package ru.ldeloff.servermonitorbot.init;
|
package ru.ldeloff.servermonitorbot.init;
|
||||||
|
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.ApplicationArguments;
|
import org.springframework.boot.ApplicationArguments;
|
||||||
import org.springframework.boot.ApplicationRunner;
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.telegram.telegrambots.meta.TelegramBotsApi;
|
import org.telegram.telegrambots.meta.TelegramBotsApi;
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
||||||
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
|
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
|
||||||
import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
|
import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.TelegramBotKeyboard;
|
|
||||||
|
|
||||||
import static ru.ldeloff.servermonitorbot.init.AddCommands.fillCommandTable;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@NoArgsConstructor
|
@RequiredArgsConstructor
|
||||||
|
@Order(1)
|
||||||
public class StartBot implements ApplicationRunner {
|
public class StartBot implements ApplicationRunner {
|
||||||
private TelegramBotController telegramBot;
|
private final TelegramBotController telegramBot;
|
||||||
private TelegramBotKeyboard telegramBotKeyboard;
|
|
||||||
private UserService userService;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
public StartBot(TelegramBotController telegramBot, TelegramBotKeyboard telegramBotKeyboard, UserService userService) {
|
|
||||||
this.telegramBot = telegramBot;
|
|
||||||
this.telegramBotKeyboard = telegramBotKeyboard;
|
|
||||||
this.userService = userService;
|
|
||||||
}
|
|
||||||
@Override
|
@Override
|
||||||
public void run(ApplicationArguments args) {
|
public void run(ApplicationArguments args) {
|
||||||
try {
|
try {
|
||||||
fillCommandTable();
|
|
||||||
TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
|
TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
|
||||||
botsApi.registerBot(telegramBot);
|
botsApi.registerBot(telegramBot);
|
||||||
userService.getAllUsers().forEach(this::SendInitMessage);
|
|
||||||
log.info("Бот запущен");
|
log.info("Бот запущен");
|
||||||
} catch (TelegramApiException e) {
|
} catch (TelegramApiException e) {
|
||||||
log.error(e.getMessage());
|
log.error(e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private void SendInitMessage(User user) {
|
|
||||||
SendMessage answer = new SendMessage();
|
|
||||||
answer.setChatId(user.getTelegramId());
|
|
||||||
answer.setText("Бот перезапущен");
|
|
||||||
CommandTemplate.sendMessage(telegramBotKeyboard.uiForm(answer), telegramBot);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,22 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.mapper;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.dto.InitUserDto;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
public class UserMapper {
|
|
||||||
final RoleService roleService;
|
|
||||||
|
|
||||||
public UserMapper(RoleService roleService) {
|
|
||||||
this.roleService = roleService;
|
|
||||||
}
|
|
||||||
|
|
||||||
public User dtoToUser(InitUserDto initUserDto) {
|
|
||||||
User user = new User();
|
|
||||||
user.setTelegramId(initUserDto.getTelegramId());
|
|
||||||
user.setRole(roleService.findRoleByName(initUserDto.getRole()));
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,28 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.model;
|
|
||||||
|
|
||||||
|
|
||||||
import jakarta.annotation.PostConstruct;
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.CommandUtil;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class CommandList {
|
|
||||||
private final Map<String, CommandTemplate> services;
|
|
||||||
@Getter
|
|
||||||
private HashMap<String, Long> commands;
|
|
||||||
@PostConstruct
|
|
||||||
private void setCommands() {
|
|
||||||
commands = new HashMap<>();
|
|
||||||
for (Map.Entry<String, CommandTemplate> entry : services.entrySet()) {
|
|
||||||
commands.put(entry.getValue().getName(), entry.getValue().getExpectedRole());
|
|
||||||
}
|
|
||||||
CommandUtil.setCommands(commands);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.model;
|
|
||||||
|
|
||||||
import jakarta.persistence.*;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Data
|
|
||||||
@Table(name = "roles")
|
|
||||||
public class Role {
|
|
||||||
@Id
|
|
||||||
@Column(name = "id")
|
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
|
||||||
private long id;
|
|
||||||
|
|
||||||
@Column(name = "name")
|
|
||||||
private String name;
|
|
||||||
}
|
|
|
@ -4,6 +4,7 @@ import jakarta.validation.constraints.Min;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
|
|
|
@ -1,24 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.model;
|
|
||||||
|
|
||||||
import jakarta.persistence.*;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Data
|
|
||||||
@Table(name = "users")
|
|
||||||
public class User {
|
|
||||||
@Id
|
|
||||||
@Column(name = "id")
|
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
|
||||||
private Long id;
|
|
||||||
|
|
||||||
@Column(name = "telegram_id")
|
|
||||||
private Long telegramId;
|
|
||||||
|
|
||||||
@ManyToOne
|
|
||||||
@JoinColumn(name = "role_id")
|
|
||||||
private Role role;
|
|
||||||
|
|
||||||
@Transient
|
|
||||||
private String login;
|
|
||||||
}
|
|
|
@ -1,14 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.model.dto;
|
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
|
||||||
import lombok.Data;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@Component
|
|
||||||
public class InitUserDto {
|
|
||||||
@NotNull
|
|
||||||
private long telegramId;
|
|
||||||
@NotNull
|
|
||||||
private String role;
|
|
||||||
}
|
|
|
@ -0,0 +1,7 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.model.server;
|
||||||
|
|
||||||
|
public enum ServerStatus {
|
||||||
|
ONLINE,
|
||||||
|
OFFLINE,
|
||||||
|
CONNECTION_LOST
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package ru.ldeloff.servermonitorbot.model;
|
package ru.ldeloff.servermonitorbot.model.server;
|
||||||
|
|
||||||
import com.jcraft.jsch.Session;
|
import com.jcraft.jsch.Session;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
@ -21,4 +21,5 @@ public class SshServer {
|
||||||
@NotNull
|
@NotNull
|
||||||
private String password;
|
private String password;
|
||||||
private Session session;
|
private Session session;
|
||||||
|
private ServerStatus status;
|
||||||
}
|
}
|
|
@ -1,11 +1,9 @@
|
||||||
package ru.ldeloff.servermonitorbot.config;
|
package ru.ldeloff.servermonitorbot.model.server;
|
||||||
|
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
@ -13,6 +11,6 @@ import java.util.List;
|
||||||
@ConfigurationProperties(prefix = "ssh")
|
@ConfigurationProperties(prefix = "ssh")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
public class SshConfig {
|
public class SshServers {
|
||||||
private List<SshServer> servers;
|
private List<SshServer> servers;
|
||||||
}
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.model.user;
|
||||||
|
|
||||||
|
public enum Role {
|
||||||
|
ADMIN,
|
||||||
|
USER,
|
||||||
|
ANONYMOUS
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.model.user;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.experimental.Accessors;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Accessors(chain = true)
|
||||||
|
public class User {
|
||||||
|
private Long telegramId;
|
||||||
|
private Role role;
|
||||||
|
private String login;
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.model.user;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Component
|
||||||
|
public class Users {
|
||||||
|
private final List<User> users = new ArrayList<>();
|
||||||
|
}
|
|
@ -1,13 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.repository;
|
|
||||||
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
import org.springframework.stereotype.Repository;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.Role;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Repository
|
|
||||||
public interface RoleRepository extends JpaRepository<Role, Long> {
|
|
||||||
Optional<Role> findRoleByName(String name);
|
|
||||||
Optional<Role> findRoleById(Long id);
|
|
||||||
}
|
|
|
@ -1,16 +1,12 @@
|
||||||
package ru.ldeloff.servermonitorbot.repository;
|
package ru.ldeloff.servermonitorbot.repository;
|
||||||
|
|
||||||
import com.jcraft.jsch.JSchException;
|
import com.jcraft.jsch.JSchException;
|
||||||
import com.jcraft.jsch.Session;
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public interface SshRepository {
|
public interface SshRepository {
|
||||||
void connectToAllServer();
|
|
||||||
Session connectToServer(SshServer sshServer) throws JSchException;
|
void connect(SshServer sshServer) throws JSchException;
|
||||||
void disconnectSessions();
|
|
||||||
String getStatusSessions();
|
void disconnect(SshServer sshServer);
|
||||||
List<SshServer> getSshServers();
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,106 +3,35 @@ package ru.ldeloff.servermonitorbot.repository;
|
||||||
import com.jcraft.jsch.JSch;
|
import com.jcraft.jsch.JSch;
|
||||||
import com.jcraft.jsch.JSchException;
|
import com.jcraft.jsch.JSchException;
|
||||||
import com.jcraft.jsch.Session;
|
import com.jcraft.jsch.Session;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
import ru.ldeloff.servermonitorbot.config.SshConfig;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
@Slf4j
|
|
||||||
@Repository
|
@Repository
|
||||||
|
@RequiredArgsConstructor
|
||||||
public class SshRepositoryImpl implements SshRepository {
|
public class SshRepositoryImpl implements SshRepository {
|
||||||
|
|
||||||
private final List<SshServer> sshServers;
|
|
||||||
|
|
||||||
@Value("${ssh.timeout:5000}")
|
@Value("${ssh.timeout:5000}")
|
||||||
private int TIMEOUT;
|
private int TIMEOUT;
|
||||||
|
|
||||||
@Autowired
|
|
||||||
public SshRepositoryImpl(SshConfig sshConfig) {
|
|
||||||
this.sshServers = sshConfig.getServers();
|
|
||||||
}
|
|
||||||
|
|
||||||
private Set<Session> sessions = new HashSet<>();
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void connectToAllServer() {
|
public void connect(SshServer sshServer) throws JSchException {
|
||||||
sshServers.forEach(sshServer -> {
|
|
||||||
try {
|
|
||||||
Session session = connectToServer(sshServer);
|
|
||||||
sshServer.setSession(session);
|
|
||||||
log.info("Успешно подключён к " + sshServer.getHost());
|
|
||||||
} catch (JSchException e) {
|
|
||||||
log.warn("Не удалось соединиться с " + sshServer.getHost() + ": " + e.getMessage());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Session connectToServer(SshServer sshServer) throws JSchException {
|
|
||||||
Session session = new JSch().getSession(sshServer.getUser(),
|
Session session = new JSch().getSession(sshServer.getUser(),
|
||||||
sshServer.getHost(),
|
sshServer.getHost(),
|
||||||
sshServer.getPort());
|
sshServer.getPort());
|
||||||
session.setPassword(sshServer.getPassword());
|
session.setPassword(sshServer.getPassword());
|
||||||
session.setConfig("StrictHostKeyChecking", "no");
|
session.setConfig("StrictHostKeyChecking", "no");
|
||||||
session.setTimeout(TIMEOUT);
|
session.setTimeout(TIMEOUT);
|
||||||
|
|
||||||
session.connect();
|
session.connect();
|
||||||
sessions.add(session);
|
|
||||||
return session;
|
sshServer.setSession(session);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void disconnectSessions() {
|
public void disconnect(SshServer sshServer) {
|
||||||
if (!sessions.isEmpty()) {
|
sshServer.getSession().disconnect();
|
||||||
sessions.forEach(Session::disconnect);
|
|
||||||
sessions.forEach(sessions::remove);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getStatusSessions() {
|
|
||||||
StringBuilder text = new StringBuilder("Статус соединения (может выполняться долго): \n");
|
|
||||||
sshServers.forEach(server -> {
|
|
||||||
text.append(server.getName())
|
|
||||||
.append(": ")
|
|
||||||
.append(checkStatusServer(server))
|
|
||||||
.append("\n");
|
|
||||||
});
|
|
||||||
return String.valueOf(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<SshServer> getSshServers() {
|
|
||||||
return sshServers;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String checkStatusServer(SshServer server) {
|
|
||||||
if (Objects.isNull(server.getSession())) {
|
|
||||||
try {
|
|
||||||
connectToServer(server);
|
|
||||||
return "OK";
|
|
||||||
} catch (JSchException e) {
|
|
||||||
log.warn("Не удалось соединиться с " + server.getHost() + ": " + e.getMessage());
|
|
||||||
return "нет соединения";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (server.getSession().isConnected()) {
|
|
||||||
return "OK";
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
connectToServer(server);
|
|
||||||
return "OK";
|
|
||||||
} catch (JSchException e) {
|
|
||||||
log.warn("Не удалось соединиться с " + server.getHost() + ": " + e.getMessage());
|
|
||||||
return "потеряно соединение";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,15 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.repository;
|
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
|
||||||
import org.springframework.data.domain.Example;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
import org.springframework.stereotype.Repository;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Repository
|
|
||||||
public interface UserRepository extends JpaRepository<User, Long> {
|
|
||||||
User getByTelegramId(long id);
|
|
||||||
@NotNull List<User> findAll();
|
|
||||||
}
|
|
|
@ -0,0 +1,11 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service;
|
||||||
|
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
|
||||||
|
public interface MessagingService {
|
||||||
|
void sendMessageToAll(String message);
|
||||||
|
|
||||||
|
void sendMessageToAdmins(String message);
|
||||||
|
|
||||||
|
void send(SendMessage message);
|
||||||
|
}
|
|
@ -0,0 +1,48 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
|
||||||
|
import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
|
||||||
|
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class MessagingServiceImpl implements MessagingService {
|
||||||
|
|
||||||
|
private final UserService userService;
|
||||||
|
private final ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sendMessageToAll(String message) {
|
||||||
|
userService.getAllUsers().forEach(user -> {
|
||||||
|
SendMessage sendMessage = new SendMessage();
|
||||||
|
sendMessage.setChatId(user.getTelegramId());
|
||||||
|
sendMessage.setText(message);
|
||||||
|
send(sendMessage);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sendMessageToAdmins(String message) {
|
||||||
|
userService.getAllAdmins().forEach(user -> {
|
||||||
|
SendMessage sendMessage = new SendMessage();
|
||||||
|
sendMessage.setChatId(user.getTelegramId());
|
||||||
|
sendMessage.setText(message);
|
||||||
|
send(sendMessage);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void send(SendMessage message) {
|
||||||
|
try {
|
||||||
|
applicationContext.getBean(TelegramBotController.class).execute(message);
|
||||||
|
} catch (TelegramApiException e) {
|
||||||
|
log.warn("Ошибка при отправке сообщения", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service;
|
||||||
|
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.Role;
|
||||||
|
|
||||||
|
public interface RoleService {
|
||||||
|
Role findRoleByName(String name);
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.Role;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RoleServiceImpl implements RoleService {
|
||||||
|
@Override
|
||||||
|
public Role findRoleByName(String name) {
|
||||||
|
return Role.valueOf(name);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,16 +1,25 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.ssh;
|
package ru.ldeloff.servermonitorbot.service;
|
||||||
|
|
||||||
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public interface SshService {
|
public interface SshService {
|
||||||
|
|
||||||
|
void updateConnection();
|
||||||
|
|
||||||
|
void disconnectAllConnections();
|
||||||
|
|
||||||
SendMessage getStatusSessions(SendMessage update);
|
SendMessage getStatusSessions(SendMessage update);
|
||||||
|
|
||||||
List<SshServer> getSshServers();
|
List<SshServer> getAllSshServers();
|
||||||
|
|
||||||
|
List<SshServer> getHealthSshServers();
|
||||||
|
|
||||||
SshCommand execute(SshCommand sshCommand);
|
SshCommand execute(SshCommand sshCommand);
|
||||||
|
|
||||||
List<SshCommand> execute(List<SshCommand> sshCommands);
|
List<SshCommand> execute(List<SshCommand> sshCommands);
|
||||||
}
|
}
|
|
@ -0,0 +1,146 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service;
|
||||||
|
|
||||||
|
import com.jcraft.jsch.ChannelExec;
|
||||||
|
import com.jcraft.jsch.JSchException;
|
||||||
|
import com.jcraft.jsch.Session;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.server.ServerStatus;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.server.SshServers;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.server.SshServer;
|
||||||
|
import ru.ldeloff.servermonitorbot.repository.SshRepository;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SshServiceImpl implements SshService {
|
||||||
|
|
||||||
|
private final SshServers sshServers;
|
||||||
|
private final SshRepository sshRepository;
|
||||||
|
private final MessagingService messagingService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void updateConnection() {
|
||||||
|
sshServers.getServers().forEach(sshServer -> {
|
||||||
|
try {
|
||||||
|
sshRepository.connect(sshServer);
|
||||||
|
updateServerStatus(sshServer, ServerStatus.ONLINE);
|
||||||
|
log.info("Успешно подключён к {}", sshServer.getHost());
|
||||||
|
} catch (JSchException e) {
|
||||||
|
if (sshServer.getStatus() == null) {
|
||||||
|
updateServerStatus(sshServer, ServerStatus.OFFLINE);
|
||||||
|
}
|
||||||
|
if (sshServer.getStatus() == ServerStatus.ONLINE) {
|
||||||
|
updateServerStatus(sshServer, ServerStatus.CONNECTION_LOST);
|
||||||
|
}
|
||||||
|
log.warn("Не удалось соединиться с {}: {}", sshServer.getHost(), e.getMessage());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void disconnectAllConnections() {
|
||||||
|
sshServers.getServers().forEach(sshRepository::disconnect);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage getStatusSessions(SendMessage message) {
|
||||||
|
StringBuilder text = new StringBuilder("Статус соединения (может выполняться долго): \n");
|
||||||
|
sshServers.getServers().forEach(server -> text.append(server.getName())
|
||||||
|
.append(": ")
|
||||||
|
.append(checkStatusServer(server))
|
||||||
|
.append("\n"));
|
||||||
|
message.setText(text.toString());
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String checkStatusServer(SshServer server) {
|
||||||
|
if (Objects.isNull(server.getSession())) {
|
||||||
|
return "нет соединения";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (server.getSession().isConnected()) {
|
||||||
|
return "OK";
|
||||||
|
} else {
|
||||||
|
return "потеряно соединение";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean checkHealth(SshServer server) {
|
||||||
|
if (Objects.isNull(server.getSession())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return server.getSession().isConnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SshServer> getAllSshServers() {
|
||||||
|
return sshServers.getServers();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SshServer> getHealthSshServers() {
|
||||||
|
return sshServers.getServers().stream().filter(this::checkHealth).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SshCommand execute(SshCommand sshCommand) {
|
||||||
|
List<SshCommand> sshCommands = new ArrayList<>();
|
||||||
|
sshCommands.add(sshCommand);
|
||||||
|
return execute(sshCommands).get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SshCommand> execute(List<SshCommand> sshCommands) {
|
||||||
|
Session session = sshCommands.get(0).getSshServer().getSession(); // подразумевается, что в листе с командами сервер один и тот же
|
||||||
|
ChannelExec channel = null;
|
||||||
|
try {
|
||||||
|
channel = (ChannelExec) session.openChannel("exec");
|
||||||
|
ChannelExec finalChannel = channel;
|
||||||
|
|
||||||
|
sshCommands.forEach(command -> {
|
||||||
|
try {
|
||||||
|
finalChannel.setCommand(command.getCommand());
|
||||||
|
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
|
||||||
|
finalChannel.setOutputStream(responseStream);
|
||||||
|
finalChannel.connect();
|
||||||
|
while (finalChannel.isConnected()) {
|
||||||
|
Thread.sleep(command.getTimeout());
|
||||||
|
}
|
||||||
|
String responseString = new String(responseStream.toByteArray());
|
||||||
|
command.setResponse(responseString);
|
||||||
|
} catch (JSchException | InterruptedException e) {
|
||||||
|
log.warn(e.getMessage());
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (JSchException e) {
|
||||||
|
log.warn(e.getMessage());
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
} finally {
|
||||||
|
if (channel != null) {
|
||||||
|
channel.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sshCommands;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updateServerStatus(SshServer server, ServerStatus newStatus) {
|
||||||
|
ServerStatus oldStatus = server.getStatus();
|
||||||
|
if (oldStatus != newStatus) {
|
||||||
|
server.setStatus(newStatus);
|
||||||
|
messagingService.sendMessageToAdmins("Server status changed for " + server.getName() +
|
||||||
|
": " + oldStatus + " -> " + newStatus);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service;
|
||||||
|
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.User;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface UserService {
|
||||||
|
|
||||||
|
void saveOrUpdateUser(User user);
|
||||||
|
|
||||||
|
User getByTelegramId(Long id);
|
||||||
|
|
||||||
|
List<User> getAllUsers();
|
||||||
|
|
||||||
|
List<User> getAllAdmins();
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.Role;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.Users;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UserServiceImpl implements UserService {
|
||||||
|
|
||||||
|
private final Users users;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveOrUpdateUser(User user) {
|
||||||
|
if (getByTelegramId(user.getTelegramId()) == null) {
|
||||||
|
users.getUsers().add(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public User getByTelegramId(Long telegramId) {
|
||||||
|
return users.getUsers().stream()
|
||||||
|
.filter(user -> user.getTelegramId().equals(telegramId))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<User> getAllUsers() {return users.getUsers(); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<User> getAllAdmins() {
|
||||||
|
return users.getUsers().stream().filter(user -> user.getRole().equals(Role.ADMIN)).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,43 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.command;
|
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.ServerListButtons;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Slf4j
|
|
||||||
public class CpuTempCommand extends CommandTemplate {
|
|
||||||
final SshService sshService;
|
|
||||||
public CpuTempCommand(UserService userService, RoleService roleService, SshService sshService, ServerListButtons serverListButtons) {
|
|
||||||
super(userService, roleService, serverListButtons, sshService);
|
|
||||||
this.sshService = sshService;
|
|
||||||
setName("CPU.temp");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
Optional<SshServer> server = sshService.getSshServers()
|
|
||||||
.stream()
|
|
||||||
.filter(x -> x.getName().equals(serverName))
|
|
||||||
.findFirst();
|
|
||||||
if (server.isPresent()) {
|
|
||||||
SshCommand result = sshService.execute(new SshCommand("cat /sys/class/thermal/thermal_zone0/temp", 100, server.get()));
|
|
||||||
return server.get().getName() + ": \n" +
|
|
||||||
(Objects.isNull(result.getResponse()) ? "ошибка при выполнении команды" :
|
|
||||||
String.format("%.1f",
|
|
||||||
Double.parseDouble(result.getResponse().replaceAll("\n", ""))/1000))
|
|
||||||
+ "°C";
|
|
||||||
} else {
|
|
||||||
log.error("Ошибка при выполнении команды 'CPUtemp'. Искомый сервер (" + serverName + ") не найден");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,37 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.command;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.ServerListButtons;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.TelegramBotKeyboard;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class FirstUseCommand extends CommandTemplate {
|
|
||||||
final TelegramBotKeyboard telegramBotKeyboard;
|
|
||||||
|
|
||||||
public FirstUseCommand(UserService userService,
|
|
||||||
RoleService roleService,
|
|
||||||
SshService sshService,
|
|
||||||
ServerListButtons serverListButtons,
|
|
||||||
TelegramBotKeyboard telegramBotKeyboard) {
|
|
||||||
super(userService, roleService, serverListButtons, sshService);
|
|
||||||
this.telegramBotKeyboard = telegramBotKeyboard;
|
|
||||||
setName("/start");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public SendMessage executeAggregate(User user, SendMessage message) {
|
|
||||||
message.setText("Добро пожаловать " + user.getLogin() + "!");
|
|
||||||
return telegramBotKeyboard.uiForm(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,27 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.command;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.ServerListButtons;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class GetStatusSessions extends CommandTemplate {
|
|
||||||
final SshService sshService;
|
|
||||||
public GetStatusSessions(UserService userService, RoleService roleService, SshService sshService, ServerListButtons serverListButtons) {
|
|
||||||
super(userService, roleService, serverListButtons, sshService);
|
|
||||||
this.sshService = sshService;
|
|
||||||
setName("Статус");
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public SendMessage executeAggregate(User user, SendMessage message) {
|
|
||||||
return sshService.getStatusSessions(message);
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,47 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.command;
|
|
||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import org.telegram.telegrambots.meta.api.objects.Update;
|
|
||||||
import ru.ldeloff.servermonitorbot.controller.TelegramBotController;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.role.RoleService;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.ServerListButtons;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.TelegramBotKeyboard;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Slf4j
|
|
||||||
public class SwitchToMainMenu extends CommandTemplate {
|
|
||||||
final TelegramBotKeyboard telegramBotKeyboard;
|
|
||||||
|
|
||||||
public SwitchToMainMenu(UserService userService,
|
|
||||||
RoleService roleService,
|
|
||||||
SshService sshService,
|
|
||||||
ServerListButtons serverListButtons,
|
|
||||||
TelegramBotKeyboard telegramBotKeyboard) {
|
|
||||||
super(userService, roleService, serverListButtons, sshService);
|
|
||||||
this.telegramBotKeyboard = telegramBotKeyboard;
|
|
||||||
setName("Not found");
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public String executeCommandSpecificHost(String serverName) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
void logSuccess(User user, String message) {
|
|
||||||
log.warn("Получена несуществующая команда '" + message + "' от " + user.getLogin()
|
|
||||||
+ " (" + user.getTelegramId() + "). OK");
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
SendMessage executeAggregate(User user, SendMessage message) {
|
|
||||||
SendMessage answer = new SendMessage();
|
|
||||||
answer.setChatId(user.getTelegramId());
|
|
||||||
answer.setText("Неверная команда. Попробуем сначала.");
|
|
||||||
return telegramBotKeyboard.uiForm(answer);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,9 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.role;
|
|
||||||
|
|
||||||
import ru.ldeloff.servermonitorbot.model.Role;
|
|
||||||
|
|
||||||
public interface RoleService {
|
|
||||||
Role findRoleByName(String name);
|
|
||||||
|
|
||||||
Role findRoleById(Long id);
|
|
||||||
}
|
|
|
@ -1,28 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.role;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.Role;
|
|
||||||
import ru.ldeloff.servermonitorbot.repository.RoleRepository;
|
|
||||||
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class RoleServiceImpl implements RoleService {
|
|
||||||
private final RoleRepository roleRepository;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Role findRoleByName(String name) {
|
|
||||||
Optional<Role> role = roleRepository.findRoleByName(name.toUpperCase(Locale.ROOT));
|
|
||||||
//noinspection OptionalGetWithoutIsPresent
|
|
||||||
return role.orElseGet(() -> roleRepository.findRoleByName("ANONYMOUS").get());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Role findRoleById(Long id) {
|
|
||||||
Optional<Role> role = roleRepository.findRoleById(id);
|
|
||||||
return role.orElseGet(() -> roleRepository.findRoleByName("ANONYMOUS").get());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,74 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.ssh;
|
|
||||||
|
|
||||||
import com.jcraft.jsch.ChannelExec;
|
|
||||||
import com.jcraft.jsch.JSchException;
|
|
||||||
import com.jcraft.jsch.Session;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshCommand;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
|
||||||
import ru.ldeloff.servermonitorbot.repository.SshRepository;
|
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@Slf4j
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class SshServiceImpl implements SshService {
|
|
||||||
final SshRepository sshRepository;
|
|
||||||
@Override
|
|
||||||
public SendMessage getStatusSessions(SendMessage message) {
|
|
||||||
message.setText(sshRepository.getStatusSessions());
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public List<SshServer> getSshServers() {
|
|
||||||
return sshRepository.getSshServers();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public SshCommand execute(SshCommand sshCommand) {
|
|
||||||
List<SshCommand> sshCommands = new ArrayList<>();
|
|
||||||
sshCommands.add(sshCommand);
|
|
||||||
return execute(sshCommands).get(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<SshCommand> execute(List<SshCommand> sshCommands) {
|
|
||||||
Session session = sshCommands.get(0).getSshServer().getSession(); // подразумевается, что в листе с командами сервер один и тот же
|
|
||||||
ChannelExec channel = null;
|
|
||||||
try {
|
|
||||||
channel = (ChannelExec) session.openChannel("exec");
|
|
||||||
ChannelExec finalChannel = channel;
|
|
||||||
|
|
||||||
sshCommands.forEach(command -> {
|
|
||||||
try {
|
|
||||||
finalChannel.setCommand(command.getCommand());
|
|
||||||
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
|
|
||||||
finalChannel.setOutputStream(responseStream);
|
|
||||||
finalChannel.connect();
|
|
||||||
while (finalChannel.isConnected()) {
|
|
||||||
Thread.sleep(command.getTimeout());
|
|
||||||
}
|
|
||||||
String responseString = new String(responseStream.toByteArray());
|
|
||||||
command.setResponse(responseString);
|
|
||||||
} catch (JSchException | InterruptedException e) {
|
|
||||||
log.warn(e.getMessage());
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (JSchException e) {
|
|
||||||
log.warn(e.getMessage());
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
} finally {
|
|
||||||
if (channel != null) {
|
|
||||||
channel.disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return sshCommands;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,13 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.user;
|
|
||||||
|
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public interface UserService {
|
|
||||||
User saveOrUpdateUser(User user);
|
|
||||||
|
|
||||||
User getByTelegramId(Long id);
|
|
||||||
|
|
||||||
List<User> getAllUsers();
|
|
||||||
}
|
|
|
@ -1,34 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.service.user;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.repository.UserRepository;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
@Slf4j
|
|
||||||
public class UserServiceImpl implements UserService {
|
|
||||||
|
|
||||||
final UserRepository userRepository;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public User saveOrUpdateUser(User user) {
|
|
||||||
User existUser = userRepository.getByTelegramId(user.getTelegramId());
|
|
||||||
if (existUser != null) {
|
|
||||||
user.setId(existUser.getId());
|
|
||||||
}
|
|
||||||
return userRepository.save(user);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public User getByTelegramId(Long id) {
|
|
||||||
return userRepository.getByTelegramId(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<User> getAllUsers() {return userRepository.findAll(); }
|
|
||||||
}
|
|
|
@ -0,0 +1,51 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.util;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.Role;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.UserService;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UpdateUtil {
|
||||||
|
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
public User getUser(Update update) {
|
||||||
|
long id = -1L;
|
||||||
|
String login = null;
|
||||||
|
if (update.hasMessage()) {
|
||||||
|
id = update.getMessage().getChat().getId();
|
||||||
|
login = update.getMessage().getChat().getUserName();
|
||||||
|
} else if (update.hasCallbackQuery()) {
|
||||||
|
id = update.getCallbackQuery().getMessage().getChatId();
|
||||||
|
login = update.getCallbackQuery().getFrom().getUserName();
|
||||||
|
}
|
||||||
|
User user = userService.getByTelegramId(id);
|
||||||
|
if (user == null) {
|
||||||
|
user = new User();
|
||||||
|
user.setTelegramId(id);
|
||||||
|
user.setRole(Role.ANONYMOUS);
|
||||||
|
}
|
||||||
|
user.setLogin(login);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage(Update update) {
|
||||||
|
if (update.hasMessage()) {
|
||||||
|
return update.getMessage().getText();
|
||||||
|
} else if (update.hasCallbackQuery()) {
|
||||||
|
return update.getCallbackQuery().getData();
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean roleChecker(Update update, List<Role> expectedRoles) {
|
||||||
|
User user = getUser(update);
|
||||||
|
return expectedRoles.contains(user.getRole());
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,15 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.utils;
|
|
||||||
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.Setter;
|
|
||||||
import lombok.experimental.UtilityClass;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
|
|
||||||
@UtilityClass
|
|
||||||
public class CommandUtil {
|
|
||||||
|
|
||||||
@Setter
|
|
||||||
@Getter
|
|
||||||
private HashMap<String, Long> commands;
|
|
||||||
}
|
|
|
@ -1,19 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.utils;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.Role;
|
|
||||||
import ru.ldeloff.servermonitorbot.model.User;
|
|
||||||
import ru.ldeloff.servermonitorbot.service.user.UserService;
|
|
||||||
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
@Component
|
|
||||||
public class RoleChecker {
|
|
||||||
final UserService userService;
|
|
||||||
public Role getRole(SendMessage sendMessage) {
|
|
||||||
String chatId = sendMessage.getChatId();
|
|
||||||
User user = userService.getByTelegramId(Long.parseLong(chatId));
|
|
||||||
return user.getRole();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
package ru.ldeloff.servermonitorbot.utils;
|
|
||||||
|
|
||||||
import ru.ldeloff.servermonitorbot.model.SshServer;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
public class SshServerUtils {
|
|
||||||
public static List<SshServer> filterGoodServers(List<SshServer> sshServers) {
|
|
||||||
List<SshServer> goodSshServers = sshServers.stream()
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.filter(server -> Objects.nonNull(server.getSession()))
|
|
||||||
.filter(server -> server.getSession().isConnected())
|
|
||||||
.toList();
|
|
||||||
return goodSshServers;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -0,0 +1,33 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.view;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
||||||
|
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class FirstUseCommand extends CommandTemplate {
|
||||||
|
|
||||||
|
private final TelegramBotKeyboard telegramBotKeyboard;
|
||||||
|
|
||||||
|
public FirstUseCommand(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, TelegramBotKeyboard telegramBotKeyboard, MessagingService messagingService) {
|
||||||
|
super(updateUtil, serverListButtons, sshService, messagingService);
|
||||||
|
this.telegramBotKeyboard = telegramBotKeyboard;
|
||||||
|
setName("/start");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage executeAggregate(User user, SendMessage message) {
|
||||||
|
message.setText("Добро пожаловать " + user.getLogin() + "!");
|
||||||
|
return telegramBotKeyboard.uiForm(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String executeCommandSpecificHost(String serverName) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,14 +1,11 @@
|
||||||
package ru.ldeloff.servermonitorbot.utils.ui;
|
package ru.ldeloff.servermonitorbot.view;
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
|
||||||
import ru.ldeloff.servermonitorbot.model.Role;
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
import ru.ldeloff.servermonitorbot.service.ssh.SshService;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.RoleChecker;
|
|
||||||
import ru.ldeloff.servermonitorbot.utils.ui.UiFormer;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
@ -25,7 +22,7 @@ public class ServerListButtons implements UiFormer {
|
||||||
List<List<InlineKeyboardButton>> keyboard = new ArrayList<>();
|
List<List<InlineKeyboardButton>> keyboard = new ArrayList<>();
|
||||||
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
|
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
|
||||||
|
|
||||||
sshService.getSshServers().forEach(sshServer -> {
|
sshService.getAllSshServers().forEach(sshServer -> {
|
||||||
if (Objects.nonNull(sshServer.getSession())) {
|
if (Objects.nonNull(sshServer.getSession())) {
|
||||||
if (sshServer.getSession().isConnected()) {
|
if (sshServer.getSession().isConnected()) {
|
||||||
List<InlineKeyboardButton> keyboardRow = new ArrayList<>();
|
List<InlineKeyboardButton> keyboardRow = new ArrayList<>();
|
|
@ -0,0 +1,37 @@
|
||||||
|
package ru.ldeloff.servermonitorbot.view;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.MessagingService;
|
||||||
|
import ru.ldeloff.servermonitorbot.util.UpdateUtil;
|
||||||
|
import ru.ldeloff.servermonitorbot.model.user.User;
|
||||||
|
import ru.ldeloff.servermonitorbot.service.SshService;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Slf4j
|
||||||
|
public class SwitchToMainMenu extends CommandTemplate {
|
||||||
|
|
||||||
|
private final TelegramBotKeyboard telegramBotKeyboard;
|
||||||
|
|
||||||
|
public SwitchToMainMenu(UpdateUtil updateUtil, ServerListButtons serverListButtons, SshService sshService, TelegramBotKeyboard telegramBotKeyboard, MessagingService messagingService) {
|
||||||
|
super(updateUtil, serverListButtons, sshService, messagingService);
|
||||||
|
this.telegramBotKeyboard = telegramBotKeyboard;
|
||||||
|
setName("Not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String executeCommandSpecificHost(String serverName) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SendMessage executeAggregate(User user, SendMessage message) {
|
||||||
|
SendMessage answer = new SendMessage();
|
||||||
|
answer.setChatId(user.getTelegramId());
|
||||||
|
answer.setText("Неверная команда. Попробуем сначала.");
|
||||||
|
return telegramBotKeyboard.uiForm(answer);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,61 +1,68 @@
|
||||||
package ru.ldeloff.servermonitorbot.utils.ui;
|
package ru.ldeloff.servermonitorbot.view;
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton;
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton;
|
||||||
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
|
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
|
||||||
import ru.ldeloff.servermonitorbot.model.CommandList;
|
import ru.ldeloff.servermonitorbot.model.user.Role;
|
||||||
import ru.ldeloff.servermonitorbot.model.Role;
|
import ru.ldeloff.servermonitorbot.model.user.User;
|
||||||
import ru.ldeloff.servermonitorbot.service.command.CommandTemplate;
|
import ru.ldeloff.servermonitorbot.service.UserService;
|
||||||
import ru.ldeloff.servermonitorbot.utils.CommandUtil;
|
import ru.ldeloff.servermonitorbot.commands.CommandTemplate;
|
||||||
import ru.ldeloff.servermonitorbot.utils.RoleChecker;
|
|
||||||
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static ru.ldeloff.servermonitorbot.model.user.Role.ADMIN;
|
||||||
|
import static ru.ldeloff.servermonitorbot.model.user.Role.USER;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class TelegramBotKeyboard implements UiFormer {
|
public class TelegramBotKeyboard implements UiFormer {
|
||||||
private final RoleChecker roleChecker;
|
|
||||||
|
private final UserService userService;
|
||||||
|
private final ApplicationContext applicationContext;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SendMessage uiForm(SendMessage message) {
|
public SendMessage uiForm(SendMessage message) {
|
||||||
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
|
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
|
||||||
replyKeyboardMarkup.setResizeKeyboard(true);
|
replyKeyboardMarkup.setResizeKeyboard(true);
|
||||||
replyKeyboardMarkup.setOneTimeKeyboard(false);
|
replyKeyboardMarkup.setOneTimeKeyboard(false);
|
||||||
|
|
||||||
ArrayList<KeyboardRow> keyboardRows = formKeyboard(
|
String chatId = message.getChatId();
|
||||||
roleChecker.getRole(message).getId());
|
User user = userService.getByTelegramId(Long.parseLong(chatId));
|
||||||
|
|
||||||
|
ArrayList<KeyboardRow> keyboardRows = formKeyboard(user);
|
||||||
replyKeyboardMarkup.setKeyboard(keyboardRows);
|
replyKeyboardMarkup.setKeyboard(keyboardRows);
|
||||||
message.setReplyMarkup(replyKeyboardMarkup);
|
message.setReplyMarkup(replyKeyboardMarkup);
|
||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ArrayList<KeyboardRow> formKeyboard(long role) {
|
private ArrayList<KeyboardRow> formKeyboard(User user) {
|
||||||
HashMap<String, Long> commands = CommandUtil.getCommands();
|
Role role = user.getRole();
|
||||||
if (role < 3) {
|
Map<String, CommandTemplate> commands = applicationContext.getBeansOfType(CommandTemplate.class);
|
||||||
commands.remove("/start");
|
commands.remove("firstUseCommand");
|
||||||
commands.remove("Not found");
|
commands.remove("switchToMainMenu");
|
||||||
}
|
|
||||||
int buttonOnLine = 3;
|
int buttonOnLine = 3;
|
||||||
|
|
||||||
ArrayList<KeyboardRow> keyboardRows = new ArrayList<>();
|
ArrayList<KeyboardRow> keyboardRows = new ArrayList<>();
|
||||||
KeyboardRow keyboardRow = new KeyboardRow();
|
KeyboardRow keyboardRow = new KeyboardRow();
|
||||||
|
|
||||||
for (Map.Entry<String, Long> entry : commands.entrySet()) {
|
for (Map.Entry<String, CommandTemplate> entry : commands.entrySet()) {
|
||||||
if (role <= entry.getValue()) {
|
if (entry.getValue().getExpectedRole().contains(role)) {
|
||||||
keyboardRow.add(new KeyboardButton(entry.getKey()));
|
keyboardRow.add(new KeyboardButton(entry.getValue().getName()));
|
||||||
}
|
}
|
||||||
if (keyboardRow.size()>=buttonOnLine) {
|
if (keyboardRow.size()>=buttonOnLine) {
|
||||||
keyboardRows.add(keyboardRow);
|
keyboardRows.add(keyboardRow);
|
||||||
keyboardRow = new KeyboardRow();
|
keyboardRow = new KeyboardRow();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (keyboardRow.size() > 0) {
|
if (!keyboardRow.isEmpty()) {
|
||||||
keyboardRows.add(keyboardRow);
|
keyboardRows.add(keyboardRow);
|
||||||
}
|
}
|
||||||
return keyboardRows;
|
return keyboardRows;
|
|
@ -1,4 +1,4 @@
|
||||||
package ru.ldeloff.servermonitorbot.utils.ui;
|
package ru.ldeloff.servermonitorbot.view;
|
||||||
|
|
||||||
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
|
||||||
|
|
|
@ -1,15 +1,6 @@
|
||||||
spring:
|
spring:
|
||||||
application:
|
application:
|
||||||
name: ServerMonitorBot
|
name: ServerMonitorBot
|
||||||
datasource:
|
|
||||||
url: jdbc:postgresql://db:5432/servermonitorbot
|
|
||||||
username: servermonitorbot
|
|
||||||
password: servermonitorbot
|
|
||||||
jpa:
|
|
||||||
hibernate:
|
|
||||||
ddl-auto: none
|
|
||||||
flyway:
|
|
||||||
locations: classpath:db/migration
|
|
||||||
bot:
|
bot:
|
||||||
name: "ServerMonitorBot"
|
name: "ServerMonitorBot"
|
||||||
token: "token"
|
token: "token"
|
||||||
|
@ -17,6 +8,7 @@ bot:
|
||||||
- telegramId: 123456789
|
- telegramId: 123456789
|
||||||
role: admin
|
role: admin
|
||||||
ssh:
|
ssh:
|
||||||
|
checkConnectionDelay: 300000
|
||||||
timeout: 5000
|
timeout: 5000
|
||||||
servers:
|
servers:
|
||||||
-
|
-
|
||||||
|
|
|
@ -1,15 +0,0 @@
|
||||||
--changeset L_DelOff:create_table_users rollbackSplitStatements:true
|
|
||||||
--comment: Создание таблицы пользователей
|
|
||||||
CREATE TABLE users
|
|
||||||
(
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
login VARCHAR(128),
|
|
||||||
id_role integer
|
|
||||||
);
|
|
||||||
|
|
||||||
COMMENT ON TABLE users IS 'Пользователи';
|
|
||||||
COMMENT ON COLUMN users.id IS 'Идентификатор пользователя';
|
|
||||||
COMMENT ON COLUMN users.login IS 'Логин пользователя';
|
|
||||||
COMMENT ON COLUMN users.id_role IS 'Ссылка на роль пользователя';
|
|
||||||
|
|
||||||
--rollback DROP TABLE users;
|
|
|
@ -1,13 +0,0 @@
|
||||||
--changeset L_DelOff:create_table_roles rollbackSplitStatements:true
|
|
||||||
--comment: Создание таблицы ролей
|
|
||||||
CREATE TABLE roles
|
|
||||||
(
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
role VARCHAR(128)
|
|
||||||
);
|
|
||||||
|
|
||||||
COMMENT ON TABLE roles IS 'Пользователи';
|
|
||||||
COMMENT ON COLUMN roles.id IS 'Идентификатор пользователя';
|
|
||||||
COMMENT ON COLUMN roles.role IS 'Логин пользователя';
|
|
||||||
|
|
||||||
--rollback DROP TABLE roles;
|
|
|
@ -1,2 +0,0 @@
|
||||||
ALTER TABLE users
|
|
||||||
ADD COLUMN role_id INT NOT NULL REFERENCES roles(id);
|
|
|
@ -1,2 +0,0 @@
|
||||||
INSERT INTO roles (id, role) VALUES (1, 'ADMIN');
|
|
||||||
INSERT INTO roles (id, role) VALUES (2, 'USER');
|
|
|
@ -1 +0,0 @@
|
||||||
INSERT INTO roles (id, role) VALUES (3, 'ANONYMOUS');
|
|
|
@ -1,9 +0,0 @@
|
||||||
ALTER TABLE users
|
|
||||||
DROP COLUMN login;
|
|
||||||
|
|
||||||
ALTER TABLE users
|
|
||||||
ADD COLUMN telegram_id INTEGER UNIQUE;
|
|
||||||
COMMENT ON COLUMN users.telegram_id IS 'Telegram ID пользователя';
|
|
||||||
|
|
||||||
ALTER TABLE users
|
|
||||||
DROP COLUMN id_role;
|
|
|
@ -1,6 +0,0 @@
|
||||||
ALTER TABLE roles
|
|
||||||
DROP COLUMN role;
|
|
||||||
|
|
||||||
ALTER TABLE roles
|
|
||||||
ADD COLUMN name VARCHAR(128);
|
|
||||||
COMMENT ON COLUMN roles.name IS 'Имя роли';
|
|
|
@ -1,4 +0,0 @@
|
||||||
TRUNCATE TABLE roles CASCADE;
|
|
||||||
INSERT INTO roles (id, name) VALUES (1, 'ADMIN');
|
|
||||||
INSERT INTO roles (id, name) VALUES (2, 'USER');
|
|
||||||
INSERT INTO roles (id, name) VALUES (3, 'ANONYMOUS');
|
|
Loading…
Reference in New Issue