diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb24f1e --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# Default ignored files +/.idea/shelf/ +/.idea/workspace.xml +/gitCopies/* +Config diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 26d3352..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..1bec35e --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml index a2865fb..d11e6c3 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -6,6 +6,7 @@ + diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 0000000..53cf2b3 --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,16 @@ + + + + + sqlite.xerial + true + org.sqlite.JDBC + jdbc:sqlite:$PROJECT_DIR$/src/main/java/lib/users.db + + + file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.31.1/sqlite-jdbc-3.31.1.jar + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml index 947ef88..dccc6ad 100644 --- a/.idea/jarRepositories.xml +++ b/.idea/jarRepositories.xml @@ -1,6 +1,11 @@ + + \ No newline at end of file diff --git a/.idea/sqldialects.xml b/.idea/sqldialects.xml new file mode 100644 index 0000000..5418333 --- /dev/null +++ b/.idea/sqldialects.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..e96534f --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 35eb1dd..38972df 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,5 +2,7 @@ + + \ No newline at end of file diff --git a/README.md b/README.md index 07c60ff..4aed629 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,12 @@ # telegramPullRequestBot JAVA/Kotlin -Телеграм бот, принимает ссылку на pull request на гитхаб, возвращает ссылку на поднятую виртуальную машину(сайт). под копотом работает с Netangels как хостингом +Телеграм бот, принимает ссылку на pull request на гитхаб, возвращает ссылку на поднятую виртуальную машину(сайт). под капотом работает с Netangels как хостингом + + +# TODO +- [ ] рефакторинг бота +- [x] исправление синтаксических ошибок +- [x] токен в отдельный файл :) +- [x] переместить lib в корень проекта +- [ ] добавить обработку ошибок + diff --git a/TelegramPullRequestBot.iml b/bin/.idea/telegramPullRequestBot2.iml similarity index 100% rename from TelegramPullRequestBot.iml rename to bin/.idea/telegramPullRequestBot2.iml diff --git a/bin/gitCopies/Dimus99_1/.idea/telegramPullRequestBot2.iml b/bin/gitCopies/Dimus99_1/.idea/telegramPullRequestBot2.iml new file mode 100644 index 0000000..78b2cc5 --- /dev/null +++ b/bin/gitCopies/Dimus99_1/.idea/telegramPullRequestBot2.iml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/bin/gitCopies/Dimus99_2/.idea/telegramPullRequestBot2.iml b/bin/gitCopies/Dimus99_2/.idea/telegramPullRequestBot2.iml new file mode 100644 index 0000000..78b2cc5 --- /dev/null +++ b/bin/gitCopies/Dimus99_2/.idea/telegramPullRequestBot2.iml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/bin/gitCopies/Dimus99_3/.idea/telegramPullRequestBot2.iml b/bin/gitCopies/Dimus99_3/.idea/telegramPullRequestBot2.iml new file mode 100644 index 0000000..78b2cc5 --- /dev/null +++ b/bin/gitCopies/Dimus99_3/.idea/telegramPullRequestBot2.iml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/bin/gitCopies/Dimus99_6/.idea/telegramPullRequestBot2.iml b/bin/gitCopies/Dimus99_6/.idea/telegramPullRequestBot2.iml new file mode 100644 index 0000000..78b2cc5 --- /dev/null +++ b/bin/gitCopies/Dimus99_6/.idea/telegramPullRequestBot2.iml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/bin/gitCopies/Dimus99_6/TelegramPullRequestBot.iml b/bin/gitCopies/Dimus99_6/TelegramPullRequestBot.iml new file mode 100644 index 0000000..78b2cc5 --- /dev/null +++ b/bin/gitCopies/Dimus99_6/TelegramPullRequestBot.iml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/bin/src/main/java/database/db.class b/bin/src/main/java/database/db.class new file mode 100644 index 0000000..e773b07 Binary files /dev/null and b/bin/src/main/java/database/db.class differ diff --git a/databases/users.db b/databases/users.db new file mode 100644 index 0000000..6c9ab10 Binary files /dev/null and b/databases/users.db differ diff --git a/gitCopies/1 b/gitCopies/1 new file mode 100644 index 0000000..e69de29 diff --git a/lib/jsch-0.1.55.jar b/lib/jsch-0.1.55.jar new file mode 100644 index 0000000..1a64e71 Binary files /dev/null and b/lib/jsch-0.1.55.jar differ diff --git a/lib/sqlite-jdbc-3.8.10.1.jar b/lib/sqlite-jdbc-3.8.10.1.jar new file mode 100644 index 0000000..971a81f Binary files /dev/null and b/lib/sqlite-jdbc-3.8.10.1.jar differ diff --git a/pom.xml b/pom.xml index c920d1d..897ff5a 100644 --- a/pom.xml +++ b/pom.xml @@ -11,6 +11,7 @@ 15 15 + 1.4.21 @@ -18,12 +19,24 @@ https://jitpack.io + + + + com.github.jkcclemens + khttp + 0.1.0 + io.github.kotlin-telegram-bot.kotlin-telegram-bot telegram 4.5.0 + + com.jcraft + jsch + 0.1.55 + \ No newline at end of file diff --git a/src/main/java/DataBase.java b/src/main/java/DataBase.java new file mode 100644 index 0000000..d95983e --- /dev/null +++ b/src/main/java/DataBase.java @@ -0,0 +1,77 @@ +import java.sql.*; +import java.util.Objects; + +public class DataBase { + static Connection conn; + String databaseName; + + + //Конструктор с подключением к бд + //В переменной path должно находится расположние файла с бд (имя файла и самой таблицы должны сопадать) + public DataBase(String path) { + databaseName = path.split("\\W+")[path.split("\\W+").length - 2]; + + try { + Class.forName("org.sqlite.JDBC"); + path = "jdbc:sqlite:".concat(path); + conn = DriverManager.getConnection(path); + System.out.println("successfully connected to '" + databaseName + "'"); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + + // Добавляем запись в бд + // Этот же метод используется для изменения уже существующих данных + public void addData(String id, String token) throws SQLException { + // Создаем ввод команды SQLite + String query = + "INSERT INTO " + databaseName + " (%s, %s) ".formatted("id", "token") + + "VALUES ('%s', '%s');".formatted(id, token); + // Пробуем создать новую запись + try { + Statement statement = conn.createStatement(); + statement.executeUpdate(query); + } catch (Exception e) + { + System.out.println(e.getMessage()); + } + // Если запись с таки id уже существует, изменяем ее + finally { + query = + "UPDATE " + databaseName + " " + + "SET token = \"%s\"".formatted(token) + + "WHERE id = \"%s\";".formatted(id); + Statement statement = conn.createStatement(); + statement.executeUpdate(query); + } + + System.out.println("data added"); + } + + // По названию и так понятен функционал + public String getTokenById(String id) throws SQLException { + + ResultSet resSet; + String res = null; + + String query = + "SELECT token FROM " + databaseName + " WHERE id = \"" + id + "\";"; + + try + { + Statement statement = conn.createStatement(); + resSet = statement.executeQuery(query); + + } catch (Exception e) { + System.out.println(e.getMessage()); + return ""; + } + + while (Objects.requireNonNull(resSet).next()) { + res = resSet.getString("token"); + } + + return res; + } +} diff --git a/src/main/java/GitHubInteraction.kt b/src/main/java/GitHubInteraction.kt new file mode 100644 index 0000000..4705323 --- /dev/null +++ b/src/main/java/GitHubInteraction.kt @@ -0,0 +1,37 @@ +import java.io.File +import java.io.IOException + + +class GitHubInteraction { + fun downloadPullRequest(urlPullRequest:String): Boolean { + //разделяем ссылку pull request на ссылку на проект и номер пулл реквеста + val urlSplit = urlPullRequest.split("/") + if (urlSplit.count() != 7 || urlSplit[0] != "https:" || urlSplit[2] != "github.com") + return false + val urlProject = urlSplit.take(5).joinToString(separator = "/") + val pullNumber = urlSplit[6] + var directoryForGitProject = "./gitCopies" + val command1 = "git clone $urlProject ${urlSplit[3]}_${urlSplit[6]}" + val command2 = "git pull origin pull/$pullNumber/head" + //далее пишем команды в консоль + // возможно стоит исправить этот костыль с изменением directoryForGitProject + // этот костыль связан с неудобством нормально создать директорию + // надо добавить больше проверок на корректность ссылки + for (command in listOf(command1, command2)) { + try { + println("команда$command") + val proc = Runtime.getRuntime().exec(command,null, File(directoryForGitProject)) + proc.waitFor() + proc.destroy() + } catch (e: IOException) { + e.printStackTrace() + } catch (e: InterruptedException) { + e.printStackTrace() + } + directoryForGitProject += "/${urlSplit[3]}_${urlSplit[6]}" + } + return true + // сделать так, чтобы можно было по ссылке получить проект / готово + // потом этот проект можно будет отправить на виртуальную машину + } +} \ No newline at end of file diff --git a/src/main/java/NetAngelsInteraction.kt b/src/main/java/NetAngelsInteraction.kt new file mode 100644 index 0000000..4d2bee9 --- /dev/null +++ b/src/main/java/NetAngelsInteraction.kt @@ -0,0 +1,102 @@ +import khttp.responses.Response +import org.json.JSONArray +import org.json.JSONObject +// api https://api.netangels.ru/modules/gateway_api.api.cloud.vms/#_1 + + +class NetAngelsInteraction { + + fun getToken(apiKey:String): String { + val response : Response = khttp.post( + url = "https://panel.netangels.ru/api/gateway/token/", + data = mapOf("api_key" to apiKey) + ) + val obj : JSONObject = response.jsonObject + print(obj) + print(response) + if (obj.has("token")){ + return obj["token"].toString() + } + else{ + print("--- Не удалось получить ТОКЕН") + return "" + } + } + + fun getMachines(token: String): MutableMap> { + val response: Response = khttp.get( + url = "https://api-ms.netangels.ru/api/v1/cloud/vms/", + headers = mapOf("Authorization" to "Bearer $token") + ) + val obj: JSONObject = response.jsonObject + print(obj) + val vms : JSONArray = obj["entities"] as JSONArray + val machines : MutableMap> = mutableMapOf() + for (vm in vms){ + val vmObj = vm as JSONObject + print("vm $vm") + val name : String = vmObj["name"] as String + val host : String = vmObj["hostname"] as String + val active : String = vmObj["state"] as String + val ip : String = vmObj["main_ip"] as String + val id : String = vmObj["id"].toString() + machines[ip] = mapOf( + "name" to name, + "active" to active, + "host" to host, + "ip" to ip, + "id" to id + ) + } + return machines + } + + fun startVM(token:String, id:String): Boolean { + val response: Response = khttp.post( + url = "https://api-ms.netangels.ru/api/v1/cloud/vms/$id/start/", + headers = mapOf("Authorization" to "Bearer $token") + ) + val starting = response.jsonObject["state"] + print("$id запуск= $starting") + return response.statusCode==200 + } + + fun stopVM(token:String, id:String): Boolean { + val response: Response = khttp.post( + url = "https://api-ms.netangels.ru/api/v1/cloud/vms/$id/stop/", + headers = mapOf("Authorization" to "Bearer $token") + ) + + print(response.toString()+" "+ response.jsonObject) + + val state = response.jsonObject["state"] as String + print("$id запуск= $state") + return response.statusCode==200 + } + + + private fun changePassword(token:String, id:String, password:String): Response { + val response: Response = khttp.post( + url = "https://api-ms.netangels.ru/api/v1/cloud/vms/$id/change-password/", + headers = mapOf("Authorization" to "Bearer $token"), + json = mapOf("password" to password) + ) + val obj =response.jsonObject + print("$response $obj") + return response + } + + fun getLoginAndPassword(token: String, id: String): Map { + val password = "dfgE3HKJ8c0DFj99d" // may edit + val response = changePassword(token, id, password) + if (response.statusCode == 200) { + return mapOf( + "host" to response.jsonObject["main_ip"].toString(), + "login" to "root", + "password" to password + ) + } + print(response.jsonObject) + throw Exception("НЕ ПОЛУЧИЛОСЬ ПОЛУЧИТЬ ЛОГИН И ПАРОЛЬ") + } +} diff --git a/src/main/java/Program.java b/src/main/java/Program.java new file mode 100644 index 0000000..05d3493 --- /dev/null +++ b/src/main/java/Program.java @@ -0,0 +1,8 @@ +public class Program { + public static void main(String[] args) { + DataBase database = new DataBase("databases/users.db"); + + TelegramBot bot = new TelegramBot(database); + bot.start(); + } +} diff --git a/src/main/java/SshConnection.java b/src/main/java/SshConnection.java new file mode 100644 index 0000000..ef59a4d --- /dev/null +++ b/src/main/java/SshConnection.java @@ -0,0 +1,110 @@ +import com.jcraft.jsch.*; + + +import java.io.*; + +public class SshConnection { + private String user; + private String password; + private String host; + private Integer port; + + + private Session session; + private PrintStream ps; + private InputStream input; + private OutputStream ops; + private Channel channel; + + private static final String STRICT_HOSTKEY_CHECKIN_KEY = "StrictHostKeyChecking"; + private static final String STRICT_HOSTKEY_CHECKIN_VALUE = "no"; + + + private ChannelSftp setupJsch() throws JSchException { + + return (ChannelSftp) session.openChannel("sftp"); + } + + + public SshConnection(String user, String password, String host, Integer port) throws JSchException { + this.user = user; + this.password = password; + this.host = host; + this.port = port; + + final JSch connection = new JSch(); + + session = connection.getSession(user, host, port); + session.setPassword(password); + session.setConfig(STRICT_HOSTKEY_CHECKIN_KEY, + STRICT_HOSTKEY_CHECKIN_VALUE); + + System.out.println("-- Try to connect to the server " + host + ":" + port + + " with user " + user); + session.connect(); + System.out.println("-- Connexion OK"); + + } + + public String executeCommand(String command) + { + StringBuilder outputBuffer = new StringBuilder(); + + try + { + Channel channel = session.openChannel("exec"); + ((ChannelExec)channel).setCommand(command); + InputStream commandOutput = channel.getInputStream(); + channel.connect(); + int readByte = commandOutput.read(); + + while(readByte != 0xffffffff) + { + outputBuffer.append((char)readByte); + readByte = commandOutput.read(); + } + + channel.disconnect(); + } + catch(IOException ioX) + { + System.out.println(ioX.getMessage()); + return null; + } + catch(JSchException jschX) + { + System.out.println(jschX.getMessage()); + return null; + } + + return outputBuffer.toString(); + } + + + + public void sendToServer(File dir, String remoteDir) throws IOException, JSchException, SftpException { + + String command = "tar -cvf "+dir+".tar.gz -C "+dir+" *"; + Process process = Runtime.getRuntime().exec(command); + System.out.println("ZIPPED"); + + ChannelSftp channelSftp = setupJsch(); + channelSftp.connect(); + + + String localFile = dir+".tar.gz"; + executeCommand("mkdir " + remoteDir); + channelSftp.put(localFile, remoteDir); + channelSftp.exit(); + String unzipCommand = "tar -xf " + remoteDir + dir.getName()+".tar.gz" + " -C " + remoteDir; + System.out.println(unzipCommand); + executeCommand(unzipCommand); + executeCommand("cd " + remoteDir + " && rm " + dir.getName()+".tar.gz"); + } + + + + + + +} diff --git a/src/main/java/TelegramBot.kt b/src/main/java/TelegramBot.kt index 3eb9f45..d578ae3 100644 --- a/src/main/java/TelegramBot.kt +++ b/src/main/java/TelegramBot.kt @@ -1,28 +1,276 @@ +import me.ivmg.telegram.Bot import me.ivmg.telegram.bot import me.ivmg.telegram.dispatch -import me.ivmg.telegram.dispatcher.command +import me.ivmg.telegram.dispatcher.callbackQuery import me.ivmg.telegram.dispatcher.text +import me.ivmg.telegram.entities.* +import java.lang.Exception -class TelegramBot - fun main(args: Array) { + +class TelegramBot(private val dataBase:DataBase){ + enum class UserPosition{ + Default, Request, ApiKey, ChoseVDSForRequest, ManageVDS, ManageActionVDS + } + + private val usersPositions = mutableMapOf() + + fun start() { val bot = bot { - token = "1307302342:AAF8z1THWcnkv_ZZ5vtlwROuMsnU8nZz7fU" + token = Config().token + val gitActions = GitHubInteraction() + val startKeyboard = KeyboardReplyMarkup( + KeyboardButton("/request"), + KeyboardButton("/start"), + KeyboardButton("/setApiKey"), + KeyboardButton(("/manageVDS")) + ) dispatch { text { bot, update -> - print(update) + println(update) val text = update.message?.text ?: "Error" val args = text.split(" ") - when (args[0]){ - "/start" -> bot.sendMessage(chatId = update.message!!.chat.id, text = "Приветствую, мой друг") - "!request" -> { - val pull_request = args[1] - bot.sendMessage(chatId = update.message!!.chat.id, text = "https://aaa.com") - } - else -> bot.sendMessage(chatId = update.message!!.chat.id, text = "Не знаю") + if (!usersPositions.containsKey(update.message!!.chat.id.toInt())) + usersPositions[update.message!!.chat.id.toInt()] = UserPosition.Default + if (text[0] == '/') + usersPositions[update.message!!.chat.id.toInt()] = UserPosition.Default + when (usersPositions[update.message!!.chat.id.toInt()]) { + UserPosition.Default -> + when (args[0]) { + "/start" -> bot.sendMessage( + chatId = update.message!!.chat.id, + text = "Приветствую, мой друг", + replyMarkup = startKeyboard + ) + "/request" -> { + usersPositions[update.message!!.chat.id.toInt()] = UserPosition.Request + bot.sendMessage( + chatId = update.message!!.chat.id, + text = "Отправьте следующим сообщением ссылку на pull Request" + ) + } + "/setApiKey" -> { + usersPositions[update.message!!.chat.id.toInt()] = UserPosition.ApiKey + bot.sendMessage( + chatId = update.message!!.chat.id, + text = "Отправьте следующим сообщением ваш Api_key" + ) + } + "/manageVDS" -> { + usersPositions[update.message!!.chat.id.toInt()] = UserPosition.ManageVDS + bot.sendMessage( + chatId = update.message!!.chat.id, + text = "Запустить или выключить?", + replyMarkup = getInlineKeyboard( + listOf("Запустить", "Выключить"), + listOf("запустить", "выключить") + ) + ) + } + else -> bot.sendMessage( + chatId = update.message!!.chat.id, + text = "Не понял ваше сообщение" + ) + } + UserPosition.Request -> addRequest(args, bot, update, gitActions) + UserPosition.ApiKey -> setApiKey(args, bot, update) + UserPosition.ChoseVDSForRequest, UserPosition.ManageActionVDS, UserPosition.ManageVDS -> + bot.sendMessage( + chatId = update.message!!.chat.id, + text = "нажмите на кнопку, или, для выхода нажмите /start" + ) + + else -> throw Exception( + "Лишняя ветвь when, что-то пошло не так," + + usersPositions[update.message!!.chat.id.toInt()] + ) + } + } + callbackQuery { bot, update -> + print(update) + + when (usersPositions[update.callbackQuery!!.message!!.chat.id.toInt()]){ + UserPosition.ChoseVDSForRequest -> uploadRequest(bot, update) + UserPosition.ManageVDS -> manageVDS(bot, update) + UserPosition.ManageActionVDS -> manageActionVDS(bot, update) + else -> {bot.sendMessage(chatId = update.callbackQuery!!.message!!.chat.id, text = "Заново сделайте запрос")} } - bot.sendMessage(chatId = update.message!!.chat.id, text = text) } } } bot.startPolling() - } \ No newline at end of file + } + + private fun manageActionVDS(bot: Bot, update: Update) { + val request = update.callbackQuery!!.data.split(" ") + if (request.count() != 3) + { + bot.sendMessage(chatId = update.callbackQuery!!.message!!.chat.id, text = "заного нажмите /manageVDS") + usersPositions[update.callbackQuery!!.message!!.chat.id.toInt()] = UserPosition.Default + return + } + val token = NetAngelsInteraction().getToken(getApiKey(update.callbackQuery!!.message!!.chat.id.toString())) + if (request[2] == "запустить") + NetAngelsInteraction().startVM(token, request[0]) + else + NetAngelsInteraction().stopVM(token, request[0]) + bot.sendMessage(chatId = update.callbackQuery!!.message!!.chat.id, + text = "выполнил команду \"$request\"") + usersPositions[update.callbackQuery!!.message!!.chat.id.toInt()] = UserPosition.Default + } + + private fun manageVDS(bot: Bot, update: Update) { + val request = update.callbackQuery!!.data + + //val message = if (request == "запустить") "Запускаю" else "Выключаю" + val vms = getMachines(bot, update.callbackQuery!!.message!!.chat.id) + if (vms != null) { + val neededVMS = vms.filter { x -> + x.value["active"] == if (request == "выключить") "Active" else "Stopped" + } + if (neededVMS.count() == 0) { + bot.sendMessage( + chatId = update.callbackQuery!!.message!!.chat.id, text = "Нет подходящих VDS" + ) + return + } + bot.sendMessage( + chatId = update.callbackQuery!!.message!!.chat.id, text = "Выберите вм", + replyMarkup = getKeyboardVDS(neededVMS, request) + ) + usersPositions[update.callbackQuery!!.message!!.chat.id.toInt()] = UserPosition.ManageActionVDS + } + } + + + private fun setApiKey( + args: List, + bot: Bot, + update: Update + ) { + try { + bot.sendMessage(chatId = update.message!!.chat.id, text = "Ожидайте...") + addToDataBase(update.message!!.chat.id.toString(), args[0]) + bot.sendMessage( + chatId = update.message!!.chat.id, + text = "Ваш apiKey из бд\n" + getApiKey(update.message!!.chat.id.toString()) + ).toString() + } catch (e: Exception) { + bot.sendMessage(chatId = update.message!!.chat.id, text = "Ошибка с установкой токена") + e.printStackTrace() + } + usersPositions[update.message!!.chat.id.toInt()] = UserPosition.Default + } + + private fun addRequest( + args: List, + bot: Bot, + update: Update, + gitActions: GitHubInteraction + ) { + bot.sendMessage(chatId = update.message!!.chat.id, text = "Скачиваем ваш pull request, ожидайте...") + val pullRequest = args[0] + try { + if (!gitActions.downloadPullRequest(pullRequest)) { + bot.sendMessage(chatId = update.message!!.chat.id, text = "Ссылка не валидная, отправьте верную, или нажмите /start") + return + } + val machines = getMachines(bot, update.message!!.chat.id) + if (machines != null) { + val keyboard = getKeyboardVDS(machines, "") + bot.sendMessage( + chatId = update.message!!.chat.id, + text = "Выберете сервер для загрузки реквеста \n(я поменяю пароль и отправлю вам данные для подключения)", + replyMarkup = keyboard + ) + usersPositions[update.message!!.chat.id.toInt()] = UserPosition.ChoseVDSForRequest + } + } catch (e: Exception) { + e.printStackTrace() + } + } + + private fun getKeyboardVDS(machines: Map>, arg:String): ReplyMarkup { + + val machinesList: MutableList = mutableListOf() + val ids: MutableList = mutableListOf() + for (vds: Map in machines.values) { + ids.add(vds["id"] + " " + vds["active"] + " " + arg) + machinesList.add( + vds["name"].toString() + "\n" + + vds["ip"].toString() + + " status=" + vds["active"].toString() + + " id=" + vds["id"].toString() + ) + } + return getInlineKeyboard(machinesList, ids) + } + + private fun addToDataBase(id: String, token: String) + { + dataBase.addData(id, token) + } + + private fun getApiKey(id: String): String + { + return dataBase.getTokenById(id) + } + + private fun uploadRequest(bot: Bot, update: Update) { + print(update.callbackQuery.toString() + "\n\n\n") + val vdsId = update.callbackQuery!!.data.split(" ")[0] + val apiKey = getApiKey(update.callbackQuery!!.message!!.chat.id.toString()) + val token = NetAngelsInteraction().getToken(apiKey) + print(update.callbackQuery!!.message!!.replyMarkup!!.inlineKeyboard) + print("\n\n") + val statusVDS = update.callbackQuery!!.data.split(" ")[1] + print(statusVDS) + if (statusVDS != "Active") { + bot.sendMessage( + chatId = update.callbackQuery!!.message!!.chat.id, + text = "сначала включите VM в /manageVDS" + ) + //usersPositions[update.callbackQuery!!.message!!.chat.id.toInt()] = UserPosition.Default + return + } + + val vdsData = NetAngelsInteraction().getLoginAndPassword(token, vdsId) + //вот тут вызов функции, которая загрузит проект + + bot.sendMessage(chatId = update.callbackQuery!!.message!!.chat.id, text = + "Я поменял пароль на этой VDS $vdsId , вот данные для подключения: $vdsData") + usersPositions[update.callbackQuery!!.message!!.chat.id.toInt()] = UserPosition.Default + } + + private fun getMachines(bot:Bot, chatID:Long): MutableMap>? { + + val apiKey = getApiKey(chatID.toString()) + if (apiKey.isEmpty()) + { + bot.sendMessage(chatId = chatID, text = "Ваш apiKey невалидный/вы его не загрузили") + bot.sendMessage(chatId = chatID, text = "Для загрузки воспользуйтесь /setApiKey") + return null + } + else { + val token = NetAngelsInteraction().getToken(apiKey) // may edit + if (token.isEmpty()) { + bot.sendMessage( + chatId = chatID, + text = "У вас не валидный ApiKey, установите валидный ключ от netangels api в /setApiKey" + ) + usersPositions[chatID.toInt()] = UserPosition.Default + return null + } + return NetAngelsInteraction().getMachines(token) + } + } + + private fun getInlineKeyboard(list:List, ids:List): InlineKeyboardMarkup { + val rows : MutableList> = mutableListOf() + for (row in 1..list.count()) + rows.add(mutableListOf()) + for ((numberButton, elem) in list.withIndex()){ + rows[numberButton].add(InlineKeyboardButton(text = elem, callbackData = ids[numberButton])) + } + return InlineKeyboardMarkup(rows) + } +} diff --git a/src/main/java/sshTest.java b/src/main/java/sshTest.java new file mode 100644 index 0000000..d2b6765 --- /dev/null +++ b/src/main/java/sshTest.java @@ -0,0 +1,18 @@ +import com.jcraft.jsch.JSchException; +import java.io.IOException; +import java.util.Scanner; + + +public class sshTest { + public static void main(String[] args) throws JSchException, IOException { + SshConnection ssh = new SshConnection("root", "7nX8uFB1", "vnc.netangels.ru", 10058); + Scanner input = new Scanner(System.in); + String command; + System.out.println(ssh.executeCommand("cd .. && ls")); + while (true) + { + command = input.nextLine(); + System.out.println(ssh.executeCommand(command)); + } + } +} diff --git a/target/classes/META-INF/telegramPullRequestBot2.kotlin_module b/target/classes/META-INF/telegramPullRequestBot2.kotlin_module deleted file mode 100644 index 4bffca6..0000000 Binary files a/target/classes/META-INF/telegramPullRequestBot2.kotlin_module and /dev/null differ diff --git a/target/classes/TelegramBot.class b/target/classes/TelegramBot.class deleted file mode 100644 index a1dbcd9..0000000 Binary files a/target/classes/TelegramBot.class and /dev/null differ diff --git a/target/classes/TelegramBotKt$main$bot$1$1$1.class b/target/classes/TelegramBotKt$main$bot$1$1$1.class deleted file mode 100644 index 483bd32..0000000 Binary files a/target/classes/TelegramBotKt$main$bot$1$1$1.class and /dev/null differ diff --git a/target/classes/TelegramBotKt$main$bot$1$1.class b/target/classes/TelegramBotKt$main$bot$1$1.class deleted file mode 100644 index bbe7948..0000000 Binary files a/target/classes/TelegramBotKt$main$bot$1$1.class and /dev/null differ diff --git a/target/classes/TelegramBotKt$main$bot$1.class b/target/classes/TelegramBotKt$main$bot$1.class deleted file mode 100644 index b7f5896..0000000 Binary files a/target/classes/TelegramBotKt$main$bot$1.class and /dev/null differ diff --git a/target/classes/TelegramBotKt.class b/target/classes/TelegramBotKt.class deleted file mode 100644 index eadf9d8..0000000 Binary files a/target/classes/TelegramBotKt.class and /dev/null differ