From 6f77ee1937bc55dc024fbbd58c8a51edcb68b2a0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Oct 2024 17:19:24 -0500 Subject: stub ScriptService --- src/slskd/Integrations/Scripts/ScriptService.cs | 50 +++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/slskd/Integrations/Scripts/ScriptService.cs (limited to 'src/slskd/Integrations/Scripts/ScriptService.cs') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs new file mode 100644 index 00000000..a427480b --- /dev/null +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -0,0 +1,50 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Integrations.Scripts; + +using System; +using System.Threading.Tasks; +using Serilog; +using slskd.Events; + +/// +/// Handles the invocation of shell scripts. +/// +public class ScriptService +{ + public ScriptService(EventBus eventBus, IOptionsMonitor optionsMonitor) + { + Events = eventBus; + OptionsMonitor = optionsMonitor; + + Events.Subscribe(nameof(ScriptService), HandleEvent); + + Log.Debug("{Service} initialized", nameof(ScriptService)); + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IOptionsMonitor OptionsMonitor { get; } + private EventBus Events { get; } + + private async Task HandleEvent(Event data) + { + Console.WriteLine($"--------------------{nameof(HandleEvent)}"); + } +} \ No newline at end of file -- cgit v1.2.3 From 4511741facda6c232b4748940ea0f111fa081abe Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Oct 2024 17:55:28 -0500 Subject: All -> Any --- src/slskd/Events/Types/Events.cs | 2 +- src/slskd/Integrations/Scripts/ScriptService.cs | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) (limited to 'src/slskd/Integrations/Scripts/ScriptService.cs') diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index b7e5e5fe..9a3a71ed 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -30,7 +30,7 @@ public abstract record Event public enum EventType { None = 0, - All = 1, + Any = 1, DownloadFileComplete = 2, DownloadDirectoryComplete = 3, } diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index a427480b..9a2a0a0c 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -20,6 +20,7 @@ using Microsoft.Extensions.Options; namespace slskd.Integrations.Scripts; using System; +using System.Linq; using System.Threading.Tasks; using Serilog; using slskd.Events; @@ -45,6 +46,18 @@ public class ScriptService private async Task HandleEvent(Event data) { - Console.WriteLine($"--------------------{nameof(HandleEvent)}"); + Log.Debug("Handling event {Event}", data); + + bool EqualsThisEvent(string type) => type.Equals(data.Type.ToString(), StringComparison.OrdinalIgnoreCase); + bool EqualsLiterallyAnyEvent(string type) => type.Equals(EventType.Any.ToString(), StringComparison.OrdinalIgnoreCase); + + var options = OptionsMonitor.CurrentValue; + var scriptsTriggeredByThisEventType = options.Integration.Scripts + .Where(kvp => kvp.Value.On.Any(EqualsThisEvent) || kvp.Value.On.Any(EqualsLiterallyAnyEvent)); + + foreach (var script in scriptsTriggeredByThisEventType) + { + Console.WriteLine($"--------------------{script.Key}"); + } } } \ No newline at end of file -- cgit v1.2.3 From 18cc1f6712b37dbe49c39619751460e368012f8a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 20 Oct 2024 18:24:09 -0500 Subject: implement script execution --- src/slskd/Integrations/Scripts/ScriptService.cs | 64 ++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) (limited to 'src/slskd/Integrations/Scripts/ScriptService.cs') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 9a2a0a0c..936522c4 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -20,7 +20,9 @@ using Microsoft.Extensions.Options; namespace slskd.Integrations.Scripts; using System; +using System.Diagnostics; using System.Linq; +using System.Text.RegularExpressions; using System.Threading.Tasks; using Serilog; using slskd.Events; @@ -46,6 +48,8 @@ public class ScriptService private async Task HandleEvent(Event data) { + await Task.Yield(); + Log.Debug("Handling event {Event}", data); bool EqualsThisEvent(string type) => type.Equals(data.Type.ToString(), StringComparison.OrdinalIgnoreCase); @@ -57,7 +61,65 @@ public class ScriptService foreach (var script in scriptsTriggeredByThisEventType) { - Console.WriteLine($"--------------------{script.Key}"); + _ = Task.Run(() => + { + Process process = default; + + try + { + var run = script.Value.Run; + var executable = run.Split(" ", 2)[0]; + var args = run.Split(" ", 2)[1].Replace("$DATA", data.ToJson()); + + Log.Debug("Running script '{Script}': {Run}", script.Key, run); + var sw = Stopwatch.StartNew(); + + process = new Process() + { + StartInfo = new ProcessStartInfo(fileName: executable) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = true, + }, + }; + + process.Start(); + process.StandardInput.WriteLine($"{args}"); + process.StandardInput.WriteLine("exit"); + + process.WaitForExit(); + sw.Stop(); + + var error = process.StandardError.ReadToEnd(); + + if (!string.IsNullOrEmpty(error)) + { + throw new Exception($"STDERR: {Regex.Replace(error, @"\r\n?|\n", " ", RegexOptions.Compiled)}"); + } + + var result = process.StandardOutput.ReadToEnd(); + var resultAsLines = result.Split(["\r\n", "\r", "\n"], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); + + Log.Debug("Script '{Script}' ran successfully in {Duration}ms; output: {Output}", script.Key, sw.ElapsedMilliseconds, resultAsLines); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to run script '{Script}': {Message}", script.Key, ex.Message); + } + finally + { + try + { + process?.Close(); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to clean up process started from script '{Script}': {Message}", script.Key, ex.Message); + } + } + }); } } } \ No newline at end of file -- cgit v1.2.3 From f276acf7a74e84dd843bafc7be776fb413ccdb94 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 20 Oct 2024 18:24:39 -0500 Subject: add todo --- src/slskd/Integrations/Scripts/ScriptService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Integrations/Scripts/ScriptService.cs') diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 936522c4..4e086148 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -67,6 +67,7 @@ public class ScriptService try { + // todo: update options validation to ensure run strings have at least 2 words var run = script.Value.Run; var executable = run.Split(" ", 2)[0]; var args = run.Split(" ", 2)[1].Replace("$DATA", data.ToJson()); -- cgit v1.2.3 From 334627cd06476df897cf3f3ec02ca70b51b7fec1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 26 Oct 2024 18:27:34 -0500 Subject: allow one-word scripts --- docs/config.md | 2 +- src/slskd/Integrations/Scripts/ScriptService.cs | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) (limited to 'src/slskd/Integrations/Scripts/ScriptService.cs') diff --git a/docs/config.md b/docs/config.md index 74c29b49..4ff884da 100644 --- a/docs/config.md +++ b/docs/config.md @@ -923,7 +923,7 @@ retention: User-defined scripts can be configured to run when application events are raised. Scripts are given a name (useful for troubleshooting!), a list of triggering events, and a `run` command that's used to execute the script. -The `run` command must be at least two words, with the first word identifying the executable to run and the rest of the string being the command and arguments that will be passed to the executable when the script is run. The executable needs to be on the system's PATH, otherwise it must be the fully qualified path to the file on disk. +The `run` command must be at least one word, with the first word identifying the executable to run and the rest of the string being the command and arguments that will be passed to the executable when the script is run. The executable needs to be on the system's PATH, otherwise it must be the fully qualified path to the file on disk. A reserved placeholder value `$DATA` is replaced with the stringified JSON data associated with the event that caused the script to run. It's the responsibility of the script to parse and handle this JSON. diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 4e086148..48916b2d 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -67,10 +67,18 @@ public class ScriptService try { - // todo: update options validation to ensure run strings have at least 2 words var run = script.Value.Run; - var executable = run.Split(" ", 2)[0]; - var args = run.Split(" ", 2)[1].Replace("$DATA", data.ToJson()); + + // split the string into at most 2 parts, leaving part [0] the executable and part [1] the rest of the string, but possibly null + var parts = run.Split(" ", count: 2, options: StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.RemoveEmptyEntries); + + var executable = parts[0]; + string args = default; + + if (parts.Length > 1) + { + args = parts[1].Replace("$DATA", data.ToJson()); + } Log.Debug("Running script '{Script}': {Run}", script.Key, run); var sw = Stopwatch.StartNew(); @@ -87,7 +95,12 @@ public class ScriptService }; process.Start(); - process.StandardInput.WriteLine($"{args}"); + + if (args is not null) + { + process.StandardInput.WriteLine(args); + } + process.StandardInput.WriteLine("exit"); process.WaitForExit(); -- cgit v1.2.3