1
0
mirror of https://github.com/salexdv/Telemonitor1C.git synced 2025-02-19 19:00:18 +02:00

добавил поддержку OneScript

This commit is contained in:
salexdv 2016-11-22 15:42:07 +03:00
parent eb68edd293
commit ddf278b870
3 changed files with 244 additions and 36 deletions

View File

@ -37,6 +37,7 @@ namespace Telemonitor
private bool buttonsHideKeyboard;
private bool buttonsUsePic;
private int buttonsNumRows;
private string oscriptPath;
/// <summary>
/// Получает настройку из 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
/// </summary>
private List<DBCommand> GetDbCommands(string commandDir)
{
List<DBCommand> commands = new List<DBCommand>();
List<DBCommand> baseCommands = new List<DBCommand>();
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;
}
/// <summary>
@ -262,8 +266,7 @@ namespace Telemonitor
private bool GetDbSettings(string[] databases)
{
this.bases = new List<DBStruct>();
this.commands = new Dictionary<string, Command>();
this.bases = new List<DBStruct>();
foreach (string dir in databases) {
@ -313,22 +316,23 @@ namespace Telemonitor
if (baseOK) {
List<DBCommand> commands = GetDbCommands(dirName);
List<DBCommand> 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
}
/// <summary>
/// Проверяет существование скриптов
/// <PARAM name="runPath">Путь исполняемого файла</PARAM>
/// </summary>
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;
}
/// <summary>
/// Конструктор класса
/// </summary>
public Settings()
{
string runPath = Service.CheckPath(System.Windows.Forms.Application.StartupPath);
this.commands = new Dictionary<string, Command>();
bool iniOK = CheckMainINI(runPath);
bool dbOK = CheckDbSettings(runPath);
bool scrOK = CheckScriptsSettings(runPath);
this.settingsExists = (iniOK && dbOK);
this.settingsExists = (iniOK && (dbOK || scrOK));
}
/// <summary>
@ -563,6 +658,17 @@ namespace Telemonitor
}
}
/// <summary>
/// Путь к файлу oscript.exe
/// </summary>
public string OScriptPath
{
get
{
return this.oscriptPath;
}
}
/// <summary>
/// Возвращает команду по имени. Если такой команды нет, возвращается null
/// <PARAM name="commandName">Имя команды</PARAM>

View File

@ -11,12 +11,15 @@ using System.Collections.Generic;
namespace Telemonitor
{
public enum commandTypes {command1C, commandOScript};
/// <summary>
/// Структура для хранения команды
/// </summary>
public struct Command : IEquatable<Command>
{
commandTypes type;
int dbVersion;
string dbConString;
string commandID;
@ -24,7 +27,22 @@ namespace Telemonitor
string commandCode;
bool keyboardCommand;
Dictionary<string, bool> allowUsers;
/// <summary>
/// Тип команды
/// </summary>
public commandTypes Type
{
get
{
return type;
}
set
{
type = value;
}
}
/// <summary>
/// Версия 8.x
/// </summary>

View File

@ -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;