From ddf278b87098ad428bdf7018f16f9bd59c6bab53 Mon Sep 17 00:00:00 2001 From: salexdv Date: Tue, 22 Nov 2016 15:42:07 +0300 Subject: [PATCH] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80=D0=B6=D0=BA=D1=83=20OneScr?= =?UTF-8?q?ipt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Settings.cs | 128 ++++++++++++++++++++++++++++++++++++++++---- Structures.cs | 20 ++++++- TelegramWorker.cs | 132 +++++++++++++++++++++++++++++++++++++--------- 3 files changed, 244 insertions(+), 36 deletions(-) diff --git a/Settings.cs b/Settings.cs index 5844e6c..3ed3431 100644 --- a/Settings.cs +++ b/Settings.cs @@ -37,6 +37,7 @@ namespace Telemonitor private bool buttonsHideKeyboard; private bool buttonsUsePic; private int buttonsNumRows; + private string oscriptPath; /// /// Получает настройку из ini файла, преобразуя значение к заданному типу @@ -150,6 +151,8 @@ namespace Telemonitor this.allowUsers = GetWhiteListOfUsers((string)GetAdditionalParamFromINI(iniSettings, "WhiteList", "Users", typeof(string), "")); this.screenOwners = GetWhiteListOfUsers((string)GetAdditionalParamFromINI(iniSettings, "WhiteList", "ScreenOwners", typeof(string), "")); + this.oscriptPath = (string)GetAdditionalParamFromINI(iniSettings, "Environment", "OneScriptPath", typeof(string), ""); + if (!String.IsNullOrEmpty(botToken)) { if (this.interval == 0) this.interval = 1; @@ -181,6 +184,7 @@ namespace Telemonitor iniSettings.IniWriteValue("Buttons", "HideButtonsAfterMessage", "1"); iniSettings.IniWriteValue("Buttons", "NumRowsOfButtons", "2"); iniSettings.IniWriteValue("WhiteList", "Users", ""); + iniSettings.IniWriteValue("OneScriptPath", "Environment", ""); Logger.Write("Создан файл настроек \"settings.ini\""); } @@ -202,7 +206,7 @@ namespace Telemonitor /// private List GetDbCommands(string commandDir) { - List commands = new List(); + List baseCommands = new List(); string fileExtention = ""; string[] cmdFiles = Directory.GetFiles(commandDir, "*.tcm*"); @@ -233,7 +237,7 @@ namespace Telemonitor newCommand.KeyboardCommand = true; else newCommand.KeyboardCommand = false; - commands.Add(newCommand); + baseCommands.Add(newCommand); } else { Logger.Write(cmdFile + ": файл не содержит кода команды", true); @@ -252,7 +256,7 @@ namespace Telemonitor } } - return commands; + return baseCommands; } /// @@ -262,8 +266,7 @@ namespace Telemonitor private bool GetDbSettings(string[] databases) { - this.bases = new List(); - this.commands = new Dictionary(); + this.bases = new List(); foreach (string dir in databases) { @@ -313,22 +316,23 @@ namespace Telemonitor if (baseOK) { - List commands = GetDbCommands(dirName); + List baseCommands = GetDbCommands(dirName); - if (commands.Count > 0) { + if (baseCommands.Count > 0) { DBStruct newBase = new DBStruct(); newBase.Name = dbName; newBase.ConnectionString = conString; newBase.Version = dbVersion; - newBase.Commands = commands; + newBase.Commands = baseCommands; newBase.AllowUsers = GetWhiteListOfUsers(wl_users); this.bases.Add(newBase); - foreach (DBCommand cmd in commands) { + foreach (DBCommand cmd in baseCommands) { string commandID = "/" + dbName + "_" + cmd.Name; Command baseCmd = new Command(); - baseCmd.ID = commandID; + baseCmd.Type = commandTypes.command1C; + baseCmd.ID = commandID; baseCmd.Description = cmd.Description; baseCmd.Code = cmd.Code; baseCmd.Version = newBase.Version; @@ -396,17 +400,108 @@ namespace Telemonitor } + /// + /// Проверяет существование скриптов + /// Путь исполняемого файла + /// + private bool CheckScriptsSettings(string runPath) + { + bool scrOK = true; + + string dirBaseName = runPath + "scripts\\"; + + if (Directory.Exists(dirBaseName)) { + + string[] cmdFiles = Directory.GetFiles(dirBaseName, "*.os*"); + + string iniFileName = dirBaseName + "scripts.ini"; + + iniFile iniSettings = new iniFile(iniFileName); + + string wl_users = (string)GetAdditionalParamFromINI(iniSettings, "WhiteList", "Users", typeof(string), ""); + + foreach (string cmdFile in cmdFiles) { + + string commandName = Path.GetFileNameWithoutExtension(cmdFile); + commandName = commandName.Replace(" ", ""); + + try + { + StreamReader reader = File.OpenText(cmdFile); + string commandDescr = reader.ReadLine(); + commandDescr.Trim(); + if (commandDescr.StartsWith(@"//")) + commandDescr = commandDescr.Substring(3); + + if (commandDescr != null) + { + string commandCode = reader.ReadToEnd(); + reader.Close(); + + if (!String.IsNullOrEmpty(commandCode)) { + + Command scriptCmd = new Command(); + commandName = "/" + commandName; + scriptCmd.Type = commandTypes.commandOScript; + scriptCmd.ID = commandName; + scriptCmd.Description = commandDescr; + scriptCmd.Code = commandCode; + scriptCmd.ConnectionString = cmdFile; + scriptCmd.AllowUsers = GetWhiteListOfUsers(wl_users); + this.commands.Add(commandName.ToLower(), scriptCmd); + } + else { + Logger.Write(cmdFile + ": файл не содержит кода команды", true); + } + + } + else + { + Logger.Write(cmdFile + ": файл не содержит записей", true); + } + + } + catch + { + Logger.Write(cmdFile + ": не удалось прочитать файл", true); + } + + } + + } + else { + + try + { + Directory.CreateDirectory(dirBaseName); + Logger.Write("Создан каталог \"scripts\""); + } + catch + { + Logger.Write("Не удалось создать каталог \"scripts\""); + scrOK = false; + } + + } + + + return scrOK; + + } + /// /// Конструктор класса /// public Settings() { string runPath = Service.CheckPath(System.Windows.Forms.Application.StartupPath); + this.commands = new Dictionary(); bool iniOK = CheckMainINI(runPath); bool dbOK = CheckDbSettings(runPath); + bool scrOK = CheckScriptsSettings(runPath); - this.settingsExists = (iniOK && dbOK); + this.settingsExists = (iniOK && (dbOK || scrOK)); } /// @@ -563,6 +658,17 @@ namespace Telemonitor } } + /// + /// Путь к файлу oscript.exe + /// + public string OScriptPath + { + get + { + return this.oscriptPath; + } + } + /// /// Возвращает команду по имени. Если такой команды нет, возвращается null /// Имя команды diff --git a/Structures.cs b/Structures.cs index 7469d21..901d0ee 100644 --- a/Structures.cs +++ b/Structures.cs @@ -11,12 +11,15 @@ using System.Collections.Generic; namespace Telemonitor { + + public enum commandTypes {command1C, commandOScript}; /// /// Структура для хранения команды /// public struct Command : IEquatable { + commandTypes type; int dbVersion; string dbConString; string commandID; @@ -24,7 +27,22 @@ namespace Telemonitor string commandCode; bool keyboardCommand; Dictionary allowUsers; - + + /// + /// Тип команды + /// + public commandTypes Type + { + get + { + return type; + } + set + { + type = value; + } + } + /// /// Версия 8.x /// diff --git a/TelegramWorker.cs b/TelegramWorker.cs index 1cf8520..0334735 100644 --- a/TelegramWorker.cs +++ b/TelegramWorker.cs @@ -21,6 +21,7 @@ using System.Web; using System.Data.SQLite; using Newtonsoft.Json; using System.Timers; +using System.Diagnostics; namespace Telemonitor { @@ -558,35 +559,118 @@ namespace Telemonitor { TelegramCommand tCommand = (TelegramCommand)e.Argument; - V8Connector connector = new V8Connector(tCommand.Command, tCommand.Parameters, tmSettings.SafeMode1C); - connector.TelegramUserName = tCommand.Message.from.username; - connector.TelegramFirstName = tCommand.Message.from.first_name; - connector.TelegramLastName = tCommand.Message.from.last_name; - - Logger.Debug(tmSettings, "Запуск команды " + tCommand.Command.ID + " на выполнение", false, mutLogger); - // Создание ComConnector и выполнение кода команды - V8Answer result = connector.Execute(mutLogger); - Logger.Debug(tmSettings, "Команда " + tCommand.Command.ID + " выполнена", false, mutLogger); + if (tCommand.Command.Type == commandTypes.command1C) { - if (connector.Success) { + // Запуск команды в базе 1С + V8Connector connector = new V8Connector(tCommand.Command, tCommand.Parameters, tmSettings.SafeMode1C); + connector.TelegramUserName = tCommand.Message.from.username; + connector.TelegramFirstName = tCommand.Message.from.first_name; + connector.TelegramLastName = tCommand.Message.from.last_name; + + Logger.Debug(tmSettings, "Запуск команды " + tCommand.Command.ID + " на выполнение", false, mutLogger); + // Создание ComConnector и выполнение кода команды + V8Answer result = connector.Execute(mutLogger); + Logger.Debug(tmSettings, "Команда " + tCommand.Command.ID + " выполнена", false, mutLogger); - int reply_to_message_id = (result.Dialog) ? tCommand.Message.message_id : 0; + if (connector.Success) { + + int reply_to_message_id = (result.Dialog) ? tCommand.Message.message_id : 0; + + if (!String.IsNullOrEmpty(result.Text)) + SendMessage(tCommand.Message.chat.id, result.Text, "", reply_to_message_id); + + if (!String.IsNullOrEmpty(result.FileName)) + SendDocument(tCommand.Message.chat.id, result.FileName); + + if (String.IsNullOrEmpty(result.Text) && String.IsNullOrEmpty(result.FileName)) + SendMessage(tCommand.Message.chat.id, "Команда выполнена"); + } + else + SendMessage(tCommand.Message.chat.id, "Ошибка при выполнении команды"); - if (!String.IsNullOrEmpty(result.Text)) - SendMessage(tCommand.Message.chat.id, result.Text, "", reply_to_message_id); - - if (!String.IsNullOrEmpty(result.FileName)) - SendDocument(tCommand.Message.chat.id, result.FileName); - - if (String.IsNullOrEmpty(result.Text) && String.IsNullOrEmpty(result.FileName)) - SendMessage(tCommand.Message.chat.id, "Команда выполнена"); + result = null; + connector.Dispose(); } - else - SendMessage(tCommand.Message.chat.id, "Ошибка при выполнении команды"); + else { + + // Запуск команды OneScript + Logger.Debug(tmSettings, "Запуск команды oscript " + tCommand.Command.ID + " на выполнение", false, mutLogger); + + StringBuilder output = new StringBuilder(); + System.Diagnostics.Process oscript = new Process(); + + if (String.IsNullOrEmpty(tmSettings.OScriptPath)) + oscript.StartInfo.FileName = "oscript"; + else { + if (File.Exists(tmSettings.OScriptPath)) + oscript.StartInfo.FileName = tmSettings.OScriptPath; + else { + SendMessage(tCommand.Message.chat.id, "oscript не найден по указанному пути"); + Logger.Debug(tmSettings, "oscript не найден по указанному пути: " + tmSettings.OScriptPath, true, mutLogger); + } + } + + if (!String.IsNullOrEmpty(oscript.StartInfo.FileName)) { + + oscript.StartInfo.Arguments = "\"" + tCommand.Command.ConnectionString + "\""; + + if (!String.IsNullOrEmpty(tCommand.Parameters)) { + string oscParam = tCommand.Parameters.Trim().Replace(' ', '_').Replace(',', ' '); + oscript.StartInfo.Arguments += " " + oscParam; + } + + oscript.StartInfo.UseShellExecute = false; + oscript.StartInfo.RedirectStandardOutput = true; + oscript.StartInfo.StandardOutputEncoding = Encoding.GetEncoding(866); + oscript.StartInfo.CreateNoWindow = true; + + try { + oscript.Start(); + } + catch (Exception ex) { + SendMessage(tCommand.Message.chat.id, "Ошибка при выполнении команды"); + Logger.Debug(tmSettings, "Ошибка при выполнении команды oscript: " + ex.Message, true, mutLogger); + } + + string curString = ""; + bool dialog = false; + string resFile = ""; + + while (!oscript.StandardOutput.EndOfStream) + { + curString = oscript.StandardOutput.ReadLine(); - result = null; - connector.Dispose(); - + if (curString.StartsWith("Результат_Файл") && String.IsNullOrEmpty(resFile)) { + resFile = curString.Substring(15).Trim(); + if (resFile.StartsWith("=")) { + resFile = resFile.Substring(2).Trim(); + continue; + } + else + resFile = ""; + } + + if (curString == "ДиалогСПараметрами") + dialog = true; + else + output.AppendLine(curString); + } + + int reply_to_message_id = (dialog) ? tCommand.Message.message_id : 0; + + if (0 < output.Length || !String.IsNullOrEmpty(resFile)) { + if (0 < output.Length) + SendMessage(tCommand.Message.chat.id, output.ToString(), "", reply_to_message_id); + if (!String.IsNullOrEmpty(resFile)) + SendDocument(tCommand.Message.chat.id, resFile); + } + else + SendMessage(tCommand.Message.chat.id, "Команда выполнена"); + + Logger.Debug(tmSettings, "Команда oscript" + tCommand.Command.ID + " выполнена", false, mutLogger); + } + } + messageOrder.Remove(tCommand.Message.message_id); tCommand = null;