diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..f950263 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# CS0618: Type or member is obsolete +dotnet_diagnostic.CS0618.severity = none diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..8c0b140 --- /dev/null +++ b/Program.cs @@ -0,0 +1,174 @@ +using System.Data.SqlClient; +using System.Net; +using System.Text; +internal class Program +{ + private static void Main(string[] args) + { + while (true) + { + string? gotifyUrl = null; + string? appToken_furnace250_l2 = null; + string? proxyUrl = null; + string? proxyUsername = null; + string? proxyPassword = null; + var config = File.ReadAllLines("config.txt"); + + foreach (var line in config) + { + if (line.StartsWith("gotify_url=")) + gotifyUrl = line.Substring("gotify_url=".Length); + else if (line.StartsWith("app_token_furnace250_l2=")) + appToken_furnace250_l2 = line.Substring("app_token_furnace250_l2=".Length); + else if (line.StartsWith("proxy_url=")) + proxyUrl = line.Substring("proxy_url=".Length); + else if (line.StartsWith("proxy_username=")) + proxyUsername = line.Substring("proxy_username=".Length); + else if (line.StartsWith("proxy_password=")) + proxyPassword = line.Substring("proxy_password=".Length); + } + + if (gotifyUrl == null || appToken_furnace250_l2 == null || proxyUrl == null || proxyUsername == null || proxyPassword == null) + { + Console.WriteLine("Ошибка: не все параметры указаны в config.txt"); + Log("Ошибка: не все параметры указаны в config.txt"); + + } + else + CheckStatusAsync(gotifyUrl, appToken_furnace250_l2, proxyUrl, proxyUsername, proxyPassword); + + Thread.Sleep(10000); + } + } + + private static async void CheckStatusAsync(string url, string token, string proxyUrl, string proxyUsername, string proxyPassword) + { + var result = CheckFurnace250Async().Result; + if (!result.status) + { + var notification = new + { + title = "Статус ПШП ст.250", + message = result.msg, + priority = 5 + }; + await SendNotify(url, token, notification, proxyUrl, proxyUsername, proxyPassword); + } + Thread.Sleep(10000); + + } + + private static async Task<(bool status, string msg)> CheckFurnace250Async() + { + int cntEmptyPOID = 0; + DateTime lastDT = DateTime.Now; + try + { + string sqlConn = @"Password=WonderUser;User ID=WonderUser;Initial Catalog=Furnace_l2;Data Source=10.14.18.38\IZHSTALSQLSRVER;TrustServerCertificate=true;Encrypt=true;"; + using (var conn = new SqlConnection(sqlConn)) + { + await conn.OpenAsync(); + string sqlQuery = @"SELECT COUNT(PO_ID) cnt_empty_poid, (SELECT top(1) + CHARGING_TIME + FROM [Furnace_l2].[dbo].[HIST_PIECES] + where [IS_DISCHARGED] ='N' and + datediff(day,CHARGING_TIME, Getdate()) < 1 AND + RTRIM(LTRIM(PO_ID)) != '' + order by CHARGING_TIME desc) last_dt + FROM [Furnace_l2].[dbo].[HIST_PIECES] + where [IS_DISCHARGED] ='N' and + datediff(day,CHARGING_TIME, Getdate()) < 1 AND + RTRIM(LTRIM(PO_ID)) = '';"; + using (var command = new SqlCommand(sqlQuery, conn)) + using (var dbReader = await command.ExecuteReaderAsync()) + { + while (await dbReader.ReadAsync()) + { + cntEmptyPOID = Convert.ToInt32(dbReader.GetValue(0)); + lastDT = Convert.ToDateTime(dbReader.GetValue(1)); + } + } + } + } + catch + { + return (false, "Ошибка подключения к БД!"); + } + + if (cntEmptyPOID > 15 && DateTime.Now - lastDT > new TimeSpan(0, 5, 0)) + { + return (false, "Проблема с привязкой заготовок в ПШП."); + } + + return (true, "OK"); + } + + private static async Task SendNotify(string url, string token, object notification, string proxyUrl, string proxyUsername, string proxyPassword) + { + var proxy = new WebProxy(new Uri(proxyUrl)) + { + Credentials = new NetworkCredential(proxyUsername, proxyPassword, "MECHEL") + }; + + var handler = new HttpClientHandler() + { + Proxy = proxy, + UseProxy = true, + PreAuthenticate = true, + UseDefaultCredentials = false + }; + + using (var client = new HttpClient(handler)) + { + client.DefaultRequestHeaders.Add("X-Gotify-Key", token); + + string json = Newtonsoft.Json.JsonConvert.SerializeObject(notification); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + try + { + HttpResponseMessage response = await client.PostAsync(url, content); + + if (response.IsSuccessStatusCode) + { + Console.WriteLine($"{DateTime.Now} - Отправлено сообщение."); + Log($"{DateTime.Now} - Отправлено сообщение."); + } + else + { + Console.WriteLine($"Ошибка: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}"); + Log($"Ошибка: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}"); + } + } + catch (HttpRequestException ex) + { + Console.WriteLine($"Ошибка подключения: {ex.Message}"); + Log($"Ошибка подключения: {ex.Message}"); + if (ex.InnerException != null) + { + Console.WriteLine($"Детали: {ex.InnerException.Message}"); + Log($"Детали: {ex.InnerException.Message}"); + } + } + } + } + + private static void Log(string str) + { + string outdir = Environment.CurrentDirectory + @"\logs\"; + if (!Directory.Exists(outdir)) Directory.CreateDirectory(outdir); + string filename = $"{DateTime.Now.Day}_{DateTime.Now.Month}_{DateTime.Now.Year}_SendNotify"; + + foreach (FileInfo file in new DirectoryInfo(outdir).GetFiles()) + { + if (Convert.ToDateTime(file.LastWriteTime) < DateTime.Now.AddDays(-30)) + file.Delete(); + } + + using (FileStream aFile = new FileStream($@"{outdir}\{filename}.log", FileMode.Append, FileAccess.Write)) + using (StreamWriter sw = new StreamWriter(aFile)) + { + sw.WriteLine(DateTime.Now + " - " + str); + } + } +} \ No newline at end of file diff --git a/SendNotify.csproj b/SendNotify.csproj new file mode 100644 index 0000000..bd06f1c --- /dev/null +++ b/SendNotify.csproj @@ -0,0 +1,29 @@ + + + + Exe + net8.0 + enable + enable + + + + embedded + + + + embedded + + + + + + + + + + Always + + + + diff --git a/SendNotify.sln b/SendNotify.sln new file mode 100644 index 0000000..55f9fa7 --- /dev/null +++ b/SendNotify.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.13.35818.85 d17.13 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SendNotify", "SendNotify.csproj", "{2F5A67A3-67F9-4DC4-B502-C2B3EF8C4305}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2F5A67A3-67F9-4DC4-B502-C2B3EF8C4305}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2F5A67A3-67F9-4DC4-B502-C2B3EF8C4305}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2F5A67A3-67F9-4DC4-B502-C2B3EF8C4305}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2F5A67A3-67F9-4DC4-B502-C2B3EF8C4305}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {9452A08A-D5DB-4B32-B452-B5DF2924CB6C} + EndGlobalSection +EndGlobal diff --git a/config.txt b/config.txt new file mode 100644 index 0000000..7e87a76 --- /dev/null +++ b/config.txt @@ -0,0 +1,5 @@ +gotify_url=https://gtf.mysrvhateapple.duckdns.org/message +app_token_furnace250_l2=A6i4cMWOMSikvsR +proxy_url=http://10.14.0.14:3128 +proxy_username=KhasanovAM +proxy_password=Prokatka49! \ No newline at end of file