From f31e306c4d4a6abca109b4d619a450b9efb0ad0e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Oct 2024 13:54:17 -0500 Subject: add an EventType enum --- src/slskd/Events/EventsDbContext.cs | 5 +++++ src/slskd/Events/Types/EventRecord.cs | 9 ++------- src/slskd/Events/Types/Events.cs | 11 +++++++++++ 3 files changed, 18 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Events/EventsDbContext.cs b/src/slskd/Events/EventsDbContext.cs index 9acbc9a4..a86f5d1c 100644 --- a/src/slskd/Events/EventsDbContext.cs +++ b/src/slskd/Events/EventsDbContext.cs @@ -32,6 +32,11 @@ public class EventsDbContext : DbContext protected override void OnModelCreating(ModelBuilder modelBuilder) { + modelBuilder + .Entity() + .Property(e => e.Type) + .HasConversion(); + modelBuilder .Entity() .Property(e => e.Timestamp) diff --git a/src/slskd/Events/Types/EventRecord.cs b/src/slskd/Events/Types/EventRecord.cs index 11825c09..4323a42b 100644 --- a/src/slskd/Events/Types/EventRecord.cs +++ b/src/slskd/Events/Types/EventRecord.cs @@ -19,7 +19,6 @@ namespace slskd.Events; using System; using System.ComponentModel.DataAnnotations; -using System.Linq; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; @@ -31,7 +30,7 @@ using Microsoft.EntityFrameworkCore; public record EventRecord { public DateTime Timestamp { get; init; } = DateTime.UtcNow; - public string Type { get; private set; } + public EventType Type { get; private set; } public string Data { get; init; } [Key] public Guid Id { get; private set; } @@ -61,10 +60,6 @@ public record EventRecord public static EventRecord From(Event e) where T : Event { - // this will be 'slskd.NameOfEvent'; we want to chop off 'slskd.' and 'Event' = 'NameOf' - var type = e.GetType().Name.Split('.').TakeLast(1).First(); - type = type.Substring(0, type.Length - "Event".Length); // chop off "Event" suffix - // construct the data for the record by serializing the event and removing redundant properties var json = JsonSerializer.Serialize(e as T, JsonSerializerOptions); var data = JsonNode.Parse(json).AsObject(); @@ -76,7 +71,7 @@ public record EventRecord return new EventRecord { Timestamp = e.Timestamp, - Type = type, + Type = e.Type, Id = e.Id, Data = data.ToJsonString(JsonSerializerOptions), }; diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index 20ec3f9f..b7e5e5fe 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -24,10 +24,20 @@ public abstract record Event { public Guid Id { get; } = Guid.NewGuid(); public DateTime Timestamp { get; init; } = DateTime.UtcNow; + public abstract EventType Type { get; } +} + +public enum EventType +{ + None = 0, + All = 1, + DownloadFileComplete = 2, + DownloadDirectoryComplete = 3, } public sealed record DownloadFileCompleteEvent : Event { + public override EventType Type => EventType.DownloadFileComplete; public string LocalFilename { get; init; } public string RemoteFilename { get; init; } public Transfer Transfer { get; init; } @@ -35,6 +45,7 @@ public sealed record DownloadFileCompleteEvent : Event public sealed record DownloadDirectoryCompleteEvent : Event { + public override EventType Type => EventType.DownloadDirectoryComplete; public string LocalDirectoryName { get; init; } public string RemoteDirectoryName { get; init; } public string Username { get; init; } -- cgit v1.2.3 From a2e2df33837a9439c46311bbc5e96d4d4990a25f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Oct 2024 17:19:13 -0500 Subject: add special case for subscribers to Event --- src/slskd/Events/EventBus.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index e5552d2d..46e55565 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -78,7 +78,7 @@ public class EventBus // save the event to the database before broadcasting to consumers Events.Add(EventRecord.From(data)); - // broadcast the event in a fire-and-forget fashion + // broadcast the event to granular subscribers in a fire-and-forget fashion // we don't need to wait for anything, just need to kick off the tasks // if something throws it will be logged and the consumer can figure it out if (Subscriptions.TryGetValue(typeof(T), out var subscribers)) @@ -94,6 +94,17 @@ public class EventBus { Log.Debug("No subscribers for {Type}", typeof(T)); } + + // broadcast the event to catch-all subscribers of type Event; listening for all types + if (Subscriptions.TryGetValue(typeof(Event), out subscribers)) + { + Log.Debug("{Count} catch-all subscriber(s) for {Type}: {Names}", subscribers.Count, typeof(Event), string.Join(", ", subscribers.Keys)); + + // we don't care about any of these tasks; contractually we are only obligated to invoke them + _ = Task.WhenAll(subscribers.Select(subscriber => + Task.Run(() => (subscriber.Value as Func)(data)) + .ContinueWith(task => Log.Error(task.Exception, "Catch-All Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(Event), task.Exception.Message)))); + } } /// -- cgit v1.2.3 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') 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 8400410fbbc81cea8140da79b3bb991c3bacd87c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Oct 2024 17:27:07 -0500 Subject: add array support to Enum attribute --- src/slskd/Common/Validation/EnumAttribute.cs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/EnumAttribute.cs b/src/slskd/Common/Validation/EnumAttribute.cs index ab28a9f0..ac3e4ce7 100644 --- a/src/slskd/Common/Validation/EnumAttribute.cs +++ b/src/slskd/Common/Validation/EnumAttribute.cs @@ -18,7 +18,9 @@ namespace slskd.Validation { using System; + using System.Collections.Generic; using System.ComponentModel.DataAnnotations; + using System.Linq; /// /// Validates that the value is a valid member of the specified . @@ -36,9 +38,24 @@ namespace slskd.Validation protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null && !Enum.TryParse(TargetType, value.ToString(), IgnoreCase, out _)) + if (value is IList array) { - return new ValidationResult($"The {validationContext.DisplayName} field must be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); + if (array.Any(x => string.IsNullOrEmpty(x))) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more null or empty values"); + } + + if (array.Any(x => !Enum.TryParse(TargetType, x, IgnoreCase, out _))) + { + return new ValidationResult($"The elements in the {validationContext.DisplayName} field must all be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); + } + } + else + { + if (value != null && !Enum.TryParse(TargetType, value.ToString(), IgnoreCase, out _)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); + } } return ValidationResult.Success; -- cgit v1.2.3 From c4450c8592e646de0185fd58710277a2dd0b3ebc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Oct 2024 17:53:20 -0500 Subject: move script config under integration --- config/slskd.example.yml | 22 +++++++++++----------- src/slskd/Core/Options.cs | 26 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 6b7750d5..7dd6450b 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -213,6 +213,16 @@ # username: ~ # password: ~ # integration: +# scripts: +# my_post_download_script: +# on: +# - DownloadFileComplete +# - DownloadDirectoryComplete +# run: data/my_script.sh --json-to-process $EVENT +# my_logging_script: +# on: +# - All +# run: data/log_slskd_events.sh $EVENT # ftp: # enabled: false # address: ~ @@ -232,14 +242,4 @@ # notify_on_private_message: true # notify_on_room_mention: true # retry_attempts: 3 -# cooldown_time: 900000 -# scripts: -# my_post_download_script: -# on: -# - DownloadFileComplete -# - DownloadDirectoryComplete -# run: data/my_script.sh --json-to-process $EVENT -# my_logging_script: -# on: -# - All -# run: data/log_slskd_events.sh $EVENT \ No newline at end of file +# cooldown_time: 900000 \ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 0f86ff62..306f9b87 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -32,6 +32,7 @@ namespace slskd using NetTools; using slskd.Authentication; using slskd.Configuration; + using slskd.Events; using slskd.Relay; using slskd.Shares; using slskd.Validation; @@ -2004,6 +2005,12 @@ namespace slskd /// public class IntegrationOptions { + /// + /// Gets script configuration. + /// + [Validate] + public Dictionary Scripts { get; init; } = []; + /// /// Gets FTP options. /// @@ -2016,6 +2023,25 @@ namespace slskd [Validate] public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions(); + /// + /// Script configuration. + /// + public class ScriptOptions + { + /// + /// Gets the list of Event types that trigger the script. + /// + [Enum(typeof(EventType))] + public string[] On { get; init; } = Array.Empty(); + + /// + /// Gets the shell script to invoke. + /// + [StringLength(int.MaxValue, MinimumLength = 1)] + [NotNullOrWhiteSpace] + public string Run { get; init; } + } + /// /// FTP options. /// -- cgit v1.2.3 From 602002b881ab89145975db10dedfabc69850114d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Oct 2024 17:54:02 -0500 Subject: plumbing for ScriptService --- src/slskd/Program.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6392385f..f18d9c09 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -60,6 +60,7 @@ namespace slskd using slskd.Files; using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; + using slskd.Integrations.Scripts; using slskd.Messaging; using slskd.Relay; using slskd.Search; @@ -484,6 +485,10 @@ namespace slskd var app = builder.Build(); + // hack: services that exist only to subscribe to the event bus are not referenced by anything else + // and are thus never instantiated. force a reference here so they are created. + _ = app.Services.GetService(); + app.ConfigureAspDotNetPipeline(); if (OptionsAtStartup.Flags.NoStart) @@ -553,7 +558,6 @@ namespace slskd services.AddHostedService(p => p.GetRequiredService()); services.AddSingleton(); - services.AddSingleton(); if (OptionsAtStartup.Flags.Volatile) @@ -578,6 +582,8 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); -- 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') 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 88e9ca275941f2a14733de6b427e1f228142d9e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 20 Oct 2024 18:21:20 -0500 Subject: fix logging --- src/slskd/Events/EventBus.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index 46e55565..16b7c9e1 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -83,7 +83,7 @@ public class EventBus // if something throws it will be logged and the consumer can figure it out if (Subscriptions.TryGetValue(typeof(T), out var subscribers)) { - Log.Debug("{Count} subscriber(s) for {Type}: {Names}", subscribers.Count, typeof(T), string.Join(", ", subscribers.Keys)); + Log.Debug("{Count} subscriber(s) for {Type}: {Names}", subscribers.Count, data.Type, string.Join(", ", subscribers.Keys)); // we don't care about any of these tasks; contractually we are only obligated to invoke them _ = Task.WhenAll(subscribers.Select(subscriber => @@ -98,7 +98,7 @@ public class EventBus // broadcast the event to catch-all subscribers of type Event; listening for all types if (Subscriptions.TryGetValue(typeof(Event), out subscribers)) { - Log.Debug("{Count} catch-all subscriber(s) for {Type}: {Names}", subscribers.Count, typeof(Event), string.Join(", ", subscribers.Keys)); + Log.Debug("{Count} catch-all subscriber(s): {Names}", subscribers.Count, string.Join(", ", subscribers.Keys)); // we don't care about any of these tasks; contractually we are only obligated to invoke them _ = Task.WhenAll(subscribers.Select(subscriber => -- 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') 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') 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') 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