소스 검색

Refactoring to use REST API for retrieving and updating cron sections

Lukas Angerer 5 년 전
부모
커밋
4d828098ff

+ 7 - 0
CronAlarm/Config/CronApi.cs

@@ -0,0 +1,7 @@
+namespace CronAlarm.Config
+{
+    public class CronApi
+    {
+        public string BaseUri { get; set; }
+    }
+}

+ 0 - 9
CronAlarm/Config/CronFragment.cs

@@ -1,9 +0,0 @@
-namespace CronAlarm.Config
-{
-    public class CronFragment
-    {
-        public string FilePath { get; set; }
-
-        public string CommandPipe { get; set; }
-    }
-}

+ 0 - 4
CronAlarm/CronAlarm.csproj

@@ -6,10 +6,6 @@
     <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
   </PropertyGroup>
 
-  <ItemGroup>
-    <None Include="wwwroot\data\cron-fragment.txt" />
-  </ItemGroup>
-
   <ItemGroup>
     <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.9" />
     <PackageReference Include="Ninject.Web.AspNetCore" Version="5.1.0-alpha1" />

+ 38 - 0
CronAlarm/CronApiClient.cs

@@ -0,0 +1,38 @@
+using CronAlarm.Config;
+using System;
+using System.IO;
+using System.Net.Http;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace CronAlarm
+{
+    public class CronApiClient
+    {
+        private readonly CronApi _apiConfig;
+        private readonly HttpClient _httpClient;
+
+        public CronApiClient(CronApi apiConfig)
+        {
+            _apiConfig = apiConfig;
+            _httpClient = new HttpClient();
+        }
+
+        public Task<Stream> GetSection(string name)
+        {
+            return _httpClient.GetStreamAsync(SectionEndpoint(name));
+        }
+
+        public Task<Stream> SetSection(string name, string content)
+        {
+            var request = new HttpRequestMessage(HttpMethod.Post, SectionEndpoint(name));
+            request.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(content)));
+            return _httpClient.SendAsync(request).ContinueWith(task => task.Result.Content.ReadAsStream());
+        }
+
+        private Uri SectionEndpoint(string name)
+        {
+            return new Uri($"{_apiConfig.BaseUri}/section/{name}");
+        }
+    }
+}

+ 0 - 51
CronAlarm/CronFragmentHandler.cs

@@ -1,51 +0,0 @@
-using CronAlarm.Config;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-
-namespace CronAlarm
-{
-    public class CronFragmentHandler : ICrontFragmentHandler
-    {
-        private readonly CronFragment _cronFragment;
-
-        public CronFragmentHandler(CronFragment fragment)
-        {
-            _cronFragment = fragment;
-        }
-
-        public IEnumerable<string> GetExpressions()
-        {
-            var lines = File.ReadAllLines(_cronFragment.FilePath);
-            return lines.Select(line => string.Join(" ", line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Take(5)));
-        }
-
-        public void Update(IEnumerable<CronEntry> entries)
-        {
-            using (var writer = File.CreateText(_cronFragment.FilePath))
-            {
-                foreach (var entry in entries)
-                {
-                    writer.WriteLine($"# {entry.Comment}");
-                    writer.Write(entry.Expression);
-                    writer.Write(new String(' ', 25 - entry.Expression.Length));
-                    writer.WriteLine(entry.Command);
-                }
-            }
-
-            NotifyUpdate();
-        }
-
-        private void NotifyUpdate()
-        {
-            if (File.Exists(_cronFragment.CommandPipe))
-            {
-                using (var writer = File.AppendText(_cronFragment.CommandPipe))
-                {
-                    writer.WriteLine("UPDATE");
-                }
-            }
-        }
-    }
-}

+ 52 - 0
CronAlarm/CronSectionHandler.cs

@@ -0,0 +1,52 @@
+using CronAlarm.Config;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+
+namespace CronAlarm
+{
+    public class CronSectionHandler : ICronSectionHandler
+    {
+        public const string AlertsSection = "ALERTS";
+        private readonly CronApiClient _cronApi;
+        private readonly char[] _whitespace = new char[] { ' ', '\t' };
+
+        public CronSectionHandler(CronApiClient cronApi)
+        {
+            _cronApi = cronApi;
+        }
+
+        public IEnumerable<string> GetExpressions()
+        {
+            return ProcessCronText(_cronApi.GetSection(AlertsSection).Result);
+        }
+
+        public IEnumerable<string> Update(IEnumerable<CronEntry> entries)
+        {
+            using (var writer = new StringWriter())
+            {
+                writer.NewLine = "\n";
+                foreach (var entry in entries)
+                {
+                    writer.WriteLine($"# {entry.Comment}");
+                    writer.Write(entry.Expression);
+                    writer.Write(new String(' ', 25 - entry.Expression.Length));
+                    writer.WriteLine(entry.Command);
+                }
+
+                writer.Flush();
+                return ProcessCronText(_cronApi.SetSection(AlertsSection, writer.ToString()).Result);
+            }
+        }
+
+        private IEnumerable<string> ProcessCronText(Stream textStream)
+        {
+            using (var reader = new StreamReader(textStream))
+            {
+                var lines = reader.ReadToEnd().Split('\n');
+                return lines.Select(line => line.Trim()).Where(line => !String.IsNullOrEmpty(line) && !line.StartsWith("#")).Select(line => string.Join(" ", line.Split(_whitespace, StringSplitOptions.RemoveEmptyEntries).Take(5)));
+            }
+        }
+    }
+}

+ 2 - 2
CronAlarm/ICrontFragmentHandler.cs → CronAlarm/ICronSectionHandler.cs

@@ -2,10 +2,10 @@
 
 namespace CronAlarm
 {
-    public interface ICrontFragmentHandler
+    public interface ICronSectionHandler
     {
         IEnumerable<string> GetExpressions();
 
-        void Update(IEnumerable<CronEntry> entries);
+        IEnumerable<string> Update(IEnumerable<CronEntry> entries);
     }
 }

+ 8 - 4
CronAlarm/Pages/AlertSelection.razor.cs

@@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Components;
 using System;
 using System.Collections.Generic;
 using System.Linq;
-using System.Threading.Tasks;
 
 namespace CronAlarm.Pages
 {
@@ -13,7 +12,7 @@ namespace CronAlarm.Pages
         private Alerts Config { get; set; }
 
         [Inject]
-        private ICrontFragmentHandler CronFragmentHandler { get; set; }
+        private ICronSectionHandler CronFragmentHandler { get; set; }
 
         private IDictionary<string, int> SelectedOptions { get; set; } = new Dictionary<string, int>();
 
@@ -59,12 +58,17 @@ namespace CronAlarm.Pages
                 }
             }
 
-            CronFragmentHandler.Update(alerts);
+            ResetGroups(CronFragmentHandler.Update(alerts));
         }
 
         private void Reset()
         {
-            var current = CronFragmentHandler.GetExpressions().ToHashSet();
+            ResetGroups(CronFragmentHandler.GetExpressions());
+        }
+
+        private void ResetGroups(IEnumerable<string> cronLines)
+        {
+            var current = cronLines.ToHashSet();
 
             foreach (var group in Config.Groups)
             {

+ 5 - 4
CronAlarm/Program.cs

@@ -45,7 +45,8 @@ namespace CronAlarm
 
             kernel.Load(typeof(AspNetCoreHostConfiguration).Assembly);
 
-            kernel.Bind<ICrontFragmentHandler>().To<CronFragmentHandler>();
+            kernel.Bind<CronApiClient>().ToSelf();
+            kernel.Bind<ICronSectionHandler>().To<CronSectionHandler>();
 
             kernel.Bind<Alerts>().ToMethod(ctx =>
             {
@@ -55,11 +56,11 @@ namespace CronAlarm
                 return section;
             });
 
-            kernel.Bind<CronFragment>().ToMethod(ctx =>
+            kernel.Bind<CronApi>().ToMethod(ctx =>
             {
                 var config = ctx.Kernel.Get<IConfiguration>();
-                var section = new CronFragment();
-                config.GetSection("CronFragment").Bind(section);
+                var section = new CronApi();
+                config.GetSection("CronApi").Bind(section);
                 return section;
             });
 

+ 2 - 3
CronAlarm/appsettings.json

@@ -7,8 +7,7 @@
     }
   },
   "AllowedHosts": "*",
-  "CronFragment": {
-    "FilePath": "./wwwroot/data/cron-fragment.txt",
-    "CommandPipe": "./wwwroot/data/cmd-pipe"
+  "CronApi": {
+    "BaseUri": "http://192.168.42.44:5000"
   }
 }

+ 0 - 3
CronAlarm/wwwroot/data/cmd-pipe

@@ -1,3 +0,0 @@
-UPDATE
-UPDATE
-UPDATE

+ 0 - 6
CronAlarm/wwwroot/data/cron-fragment.txt

@@ -1,6 +0,0 @@
-# Weekdays / 06:20 - Work
-20 06 * * MON-FRI        /home/pi/mpc-alarm-cron.sh
-# Saturday / 08:20 - Long-Jog
-20 08 * * SAT            /home/pi/mpc-alarm-cron.sh
-# Sunday / 09:00 - Lazy
-00 09 * * SUN            /home/pi/mpc-alarm-cron.sh

+ 0 - 4
data/cron-fragment.txt

@@ -1,4 +0,0 @@
-# Weekdays / 08:30 - Holidays
-30 08 * * MON-FRI        /home/pi/mpc-alarm-cron.sh
-# Sunday / 09:00 - Lazy
-00 09 * * SUN            /home/pi/mpc-alarm-cron.sh