rework scripted schedules (#2367)

* start to reorganize scripted playout building

* add openapi

* add all content fns

* add playout instructions

* add control instructions

* add request models

* prevent build loop

* rename

* update changelog

* tweak changelog
This commit is contained in:
Jason Dove
2025-09-03 20:53:14 +00:00
committed by GitHub
parent 7ac93c6aad
commit 03b4419f67
32 changed files with 737 additions and 595 deletions
@@ -1,123 +0,0 @@
using System.Diagnostics.CodeAnalysis;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Scheduling.Engine;
using IronPython.Runtime;
namespace ErsatzTV.Core.Scheduling.ScriptedScheduling.Modules;
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores")]
[SuppressMessage("Usage", "VSTHRD002:Avoid problematic synchronous waits")]
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public class ContentModule(ISchedulingEngine schedulingEngine, CancellationToken cancellationToken)
{
public void add_search(string key, string query, string order)
{
if (!Enum.TryParse(order, ignoreCase: true, out PlaybackOrder playbackOrder))
{
return;
}
schedulingEngine.AddSearch(key, query, playbackOrder, cancellationToken).GetAwaiter().GetResult();
}
public void add_collection(string key, string collection, string order)
{
if (!Enum.TryParse(order, ignoreCase: true, out PlaybackOrder playbackOrder))
{
return;
}
schedulingEngine.AddCollection(key, collection, playbackOrder, cancellationToken).GetAwaiter().GetResult();
}
public void add_marathon(
string key,
string group_by,
string item_order = "shuffle",
PythonDictionary guids = null,
PythonList searches = null,
bool play_all_items = false,
bool shuffle_groups = false)
{
if (!Enum.TryParse(item_order, ignoreCase: true, out PlaybackOrder itemPlaybackOrder))
{
itemPlaybackOrder = PlaybackOrder.Shuffle;
}
var mappedGuids = new Dictionary<string, List<string>>();
if (guids != null)
{
foreach (KeyValuePair<object, object> guid in guids)
{
var guidKey = guid.Key.ToString();
if (guidKey is not null && guid.Value is PythonList guidValues)
{
mappedGuids.Add(guidKey, guidValues.Select(x => x.ToString()).ToList());
}
}
}
var mappedSearches = new List<string>();
if (searches != null)
{
mappedSearches.AddRange(searches.Select(x => x.ToString()));
}
// guids OR searches are required
if (mappedGuids.Count == 0 && mappedSearches.Count == 0)
{
return;
}
schedulingEngine
.AddMarathon(key, mappedGuids, mappedSearches, group_by, shuffle_groups, itemPlaybackOrder, play_all_items)
.GetAwaiter()
.GetResult();
}
public void add_multi_collection(string key, string multi_collection, string order)
{
if (!Enum.TryParse(order, ignoreCase: true, out PlaybackOrder playbackOrder))
{
return;
}
schedulingEngine
.AddMultiCollection(key, multi_collection, playbackOrder, cancellationToken)
.GetAwaiter()
.GetResult();
}
public void add_playlist(string key, string playlist, string playlist_group)
{
schedulingEngine.AddPlaylist(key, playlist, playlist_group, cancellationToken).GetAwaiter().GetResult();
}
public void add_smart_collection(string key, string smart_collection, string order)
{
if (!Enum.TryParse(order, ignoreCase: true, out PlaybackOrder playbackOrder))
{
return;
}
schedulingEngine
.AddSmartCollection(key, smart_collection, playbackOrder, cancellationToken)
.GetAwaiter()
.GetResult();
}
public void add_show(string key, PythonDictionary guids, string order)
{
if (!Enum.TryParse(order, ignoreCase: true, out PlaybackOrder playbackOrder))
{
return;
}
schedulingEngine
.AddShow(key, guids.ToDictionary(k => k.Key.ToString(), k => k.Value.ToString()), playbackOrder)
.GetAwaiter()
.GetResult();
}
}
@@ -1,298 +0,0 @@
using System.Diagnostics.CodeAnalysis;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Scheduling.Engine;
using IronPython.Runtime;
namespace ErsatzTV.Core.Scheduling.ScriptedScheduling.Modules;
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores")]
[SuppressMessage("Usage", "VSTHRD002:Avoid problematic synchronous waits")]
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public class PlayoutModule(ISchedulingEngine schedulingEngine, CancellationToken cancellationToken)
{
public int FailureCount { get; private set; }
// content instructions
public void add_all(
string content,
string filler_kind = null,
string custom_title = null,
bool disable_watermarks = false)
{
Option<FillerKind> maybeFillerKind = Option<FillerKind>.None;
if (Enum.TryParse(filler_kind, ignoreCase: true, out FillerKind fillerKind))
{
maybeFillerKind = fillerKind;
}
bool success = schedulingEngine.AddAll(content, maybeFillerKind, custom_title, disable_watermarks);
if (success)
{
FailureCount = 0;
}
else
{
FailureCount++;
}
}
public void add_count(
string content,
int count,
string filler_kind = null,
string custom_title = null,
bool disable_watermarks = false)
{
Option<FillerKind> maybeFillerKind = Option<FillerKind>.None;
if (Enum.TryParse(filler_kind, ignoreCase: true, out FillerKind fillerKind))
{
maybeFillerKind = fillerKind;
}
bool success = schedulingEngine.AddCount(content, count, maybeFillerKind, custom_title, disable_watermarks);
if (success)
{
FailureCount = 0;
}
else
{
FailureCount++;
}
}
public void add_duration(
string content,
string duration,
string fallback = null,
bool trim = false,
int discard_attempts = 0,
bool stop_before_end = true,
bool offline_tail = false,
string filler_kind = null,
string custom_title = null,
bool disable_watermarks = false)
{
Option<FillerKind> maybeFillerKind = Option<FillerKind>.None;
if (Enum.TryParse(filler_kind, ignoreCase: true, out FillerKind fillerKind))
{
maybeFillerKind = fillerKind;
}
bool success = schedulingEngine.AddDuration(
content,
duration,
fallback,
trim,
discard_attempts,
stop_before_end,
offline_tail,
maybeFillerKind,
custom_title,
disable_watermarks);
if (success)
{
FailureCount = 0;
}
else
{
FailureCount++;
}
}
public void pad_to_next(
string content,
int minutes,
string fallback = null,
bool trim = false,
int discard_attempts = 0,
bool stop_before_end = true,
bool offline_tail = true,
string filler_kind = null,
string custom_title = null,
bool disable_watermarks = false)
{
Option<FillerKind> maybeFillerKind = Option<FillerKind>.None;
if (Enum.TryParse(filler_kind, ignoreCase: true, out FillerKind fillerKind))
{
maybeFillerKind = fillerKind;
}
bool success = schedulingEngine.PadToNext(
content,
minutes,
fallback,
trim,
discard_attempts,
stop_before_end,
offline_tail,
maybeFillerKind,
custom_title,
disable_watermarks);
if (success)
{
FailureCount = 0;
}
else
{
FailureCount++;
}
}
public void pad_until(
string content,
string when,
bool tomorrow = false,
string fallback = null,
bool trim = false,
int discard_attempts = 0,
bool stop_before_end = true,
bool offline_tail = false,
string filler_kind = null,
string custom_title = null,
bool disable_watermarks = false)
{
Option<FillerKind> maybeFillerKind = Option<FillerKind>.None;
if (Enum.TryParse(filler_kind, ignoreCase: true, out FillerKind fillerKind))
{
maybeFillerKind = fillerKind;
}
bool success = schedulingEngine.PadUntil(
content,
when,
tomorrow,
fallback,
trim,
discard_attempts,
stop_before_end,
offline_tail,
maybeFillerKind,
custom_title,
disable_watermarks);
if (success)
{
FailureCount = 0;
}
else
{
FailureCount++;
}
}
// control instructions
public void start_epg_group(bool advance = true)
{
schedulingEngine.LockGuideGroup(advance);
}
public void stop_epg_group()
{
schedulingEngine.UnlockGuideGroup();
}
public void graphics_on(string graphics, PythonDictionary variables = null)
{
var maybeVariables = new Dictionary<string, string>();
if (variables != null)
{
maybeVariables = variables.ToDictionary(v => v.Key.ToString(), v => v.Value.ToString());
}
schedulingEngine
.GraphicsOn([graphics], maybeVariables, cancellationToken)
.GetAwaiter()
.GetResult();
}
public void graphics_on(PythonList graphics, PythonDictionary variables = null)
{
var maybeVariables = new Dictionary<string, string>();
if (variables != null)
{
maybeVariables = variables.ToDictionary(v => v.Key.ToString(), v => v.Value.ToString());
}
schedulingEngine
.GraphicsOn(
graphics.Select(g => g.ToString()).ToList(),
maybeVariables,
cancellationToken)
.GetAwaiter()
.GetResult();
}
public void graphics_off(string graphics = null)
{
if (string.IsNullOrWhiteSpace(graphics))
{
schedulingEngine.GraphicsOff([], cancellationToken).GetAwaiter().GetResult();
}
else
{
schedulingEngine.GraphicsOff([graphics], cancellationToken).GetAwaiter().GetResult();
}
}
public void graphics_off(PythonList graphics)
{
schedulingEngine
.GraphicsOff(graphics.Select(g => g.ToString()).ToList(), cancellationToken)
.GetAwaiter()
.GetResult();
}
public void watermark_on(string watermark)
{
schedulingEngine.WatermarkOn([watermark]).GetAwaiter().GetResult();
}
public void watermark_on(PythonList watermark)
{
schedulingEngine
.WatermarkOn(watermark.Select(g => g.ToString()).ToList())
.GetAwaiter()
.GetResult();
}
public void watermark_off(string watermark = null)
{
if (string.IsNullOrWhiteSpace(watermark))
{
schedulingEngine.WatermarkOff([]).GetAwaiter().GetResult();
}
else
{
schedulingEngine.WatermarkOff([watermark]).GetAwaiter().GetResult();
}
}
public void watermark_off(PythonList watermark)
{
schedulingEngine.WatermarkOff(watermark.Select(g => g.ToString()).ToList()).GetAwaiter().GetResult();
}
public void skip_items(string content, int count)
{
schedulingEngine.SkipItems(content, count);
}
public void skip_to_item(string content, int season, int episode)
{
schedulingEngine.SkipToItem(content, season, episode);
}
public void wait_until(string when, bool tomorrow = false, bool rewind_on_reset = false)
{
if (TimeOnly.TryParse(when, out TimeOnly waitUntil))
{
schedulingEngine.WaitUntil(waitUntil, tomorrow, rewind_on_reset);
}
}
}
@@ -1,20 +1,17 @@
using System.Diagnostics.CodeAnalysis;
using CliWrap;
using CliWrap.Buffered;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Metadata;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Interfaces.Scheduling;
using ErsatzTV.Core.Scheduling.Engine;
using ErsatzTV.Core.Scheduling.ScriptedScheduling.Modules;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using Microsoft.Extensions.Logging;
using Microsoft.Scripting.Hosting;
namespace ErsatzTV.Core.Scheduling.ScriptedScheduling;
public class ScriptedPlayoutBuilder(
IConfigElementRepository configElementRepository,
IScriptedPlayoutBuilderService scriptedPlayoutBuilderService,
ISchedulingEngine schedulingEngine,
ILocalFileSystem localFileSystem,
ILogger<ScriptedPlayoutBuilder> logger)
@@ -29,15 +26,19 @@ public class ScriptedPlayoutBuilder(
{
var result = PlayoutBuildResult.Empty;
Guid buildId = scriptedPlayoutBuilderService.StartSession(schedulingEngine);
try
{
if (!localFileSystem.FileExists(playout.ScheduleFile))
{
logger.LogError("Cannot build scripted playout; schedule file {File} does not exist", playout.ScheduleFile);
logger.LogError(
"Cannot build scripted playout; schedule file {File} does not exist",
playout.ScheduleFile);
return result;
}
logger.LogInformation("Building scripted playout...");
logger.LogInformation("Building scripted playout with id {BuildId} ...", buildId);
int daysToBuild = await GetDaysToBuild(cancellationToken);
DateTimeOffset finish = start.AddDays(daysToBuild);
@@ -48,84 +49,33 @@ public class ScriptedPlayoutBuilder(
schedulingEngine.BuildBetween(start, finish);
schedulingEngine.WithReferenceData(referenceData);
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var token = cts.Token;
TracebackDelegate traceDelegate = null;
traceDelegate = (_, why, _) =>
{
if (why == "line")
{
token.ThrowIfCancellationRequested();
}
return traceDelegate;
};
engine.SetTrace(traceDelegate);
string scriptPath = Path.GetDirectoryName(playout.ScheduleFile);
if (!string.IsNullOrWhiteSpace(scriptPath) && localFileSystem.FolderExists(scriptPath))
{
ICollection<string> paths = engine.GetSearchPaths();
paths.Add(scriptPath);
engine.SetSearchPaths(paths);
}
var contentModule = new ContentModule(schedulingEngine, token);
var playoutModule = new PlayoutModule(schedulingEngine, token);
engine.ExecuteFile(playout.ScheduleFile, scope);
// define_content is required
if (!scope.TryGetVariable("define_content", out PythonFunction defineContentFunc))
{
logger.LogError("Script must contain a 'define_content' function");
return result;
}
if (defineContentFunc.__code__.co_argcount != 2)
{
logger.LogError("Script function 'define_content' must accept 2 parameters: (content, context)");
return result;
}
// reset_playout is NOT required
scope.TryGetVariable("reset_playout", out PythonFunction resetPlayoutFunc);
if (resetPlayoutFunc != null && resetPlayoutFunc.__code__.co_argcount != 2)
{
logger.LogError("Script function 'reset_playout' must accept 2 parameters: (playout, context)");
return result;
}
// build_playout is required
if (!scope.TryGetVariable("build_playout", out PythonFunction buildPlayoutFunc))
{
logger.LogError("Script must contain a 'build_playout' function");
return result;
}
if (buildPlayoutFunc.__code__.co_argcount != 2)
{
logger.LogError("Script function 'build_playout' must accept 2 parameters: (playout, context)");
return result;
}
schedulingEngine.RestoreOrReset(Optional(playout.Anchor));
var context = new PythonPlayoutContext(schedulingEngine.GetState(), playoutModule, engine);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token);
// define content first
engine.Operations.Invoke(defineContentFunc, contentModule, context);
Command command = Cli.Wrap(playout.ScheduleFile)
.WithArguments(
[
$"http://localhost:{Settings.UiPort}",
buildId.ToString(),
mode.ToString().ToLowerInvariant()
])
.WithValidation(CommandResultValidation.None);
// reset if applicable
if (mode is PlayoutBuildMode.Reset && resetPlayoutFunc != null)
var commandResult = await command.ExecuteBufferedAsync(linkedCts.Token);
if (!string.IsNullOrWhiteSpace(commandResult.StandardOutput))
{
engine.Operations.Invoke(resetPlayoutFunc, playoutModule, context);
Console.WriteLine(commandResult.StandardOutput);
}
// build playout
engine.Operations.Invoke(buildPlayoutFunc, playoutModule, context);
if (commandResult.ExitCode != 0)
{
logger.LogWarning(
"Scripted playout process exited with code {Code}: {Error}",
commandResult.ExitCode,
commandResult.StandardError);
}
playout.Anchor = schedulingEngine.GetAnchor();
@@ -141,6 +91,10 @@ public class ScriptedPlayoutBuilder(
logger.LogWarning(ex, "Unexpected exception building scripted playout");
throw;
}
finally
{
scriptedPlayoutBuilderService.EndSession(buildId);
}
return result;
}
@@ -160,96 +114,4 @@ public class ScriptedPlayoutBuilder(
AddedHistory = state.AddedHistory,
HistoryToRemove = state.HistoryToRemove
};
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores")]
public class PythonPlayoutContext
{
private readonly ISchedulingEngineState _state;
private readonly PlayoutModule _playoutModule;
private readonly ScriptEngine _scriptEngine;
private readonly dynamic _datetimeModule;
// track playout build failures
private const int MaxFailures = 10;
// track is_done calls when current_time has not advanced
private DateTimeOffset _lastCheckedTime;
private int _noProgressCounter;
private const int MaxCallsNoProgress = 20;
public PythonPlayoutContext(
ISchedulingEngineState state,
PlayoutModule playoutModule,
ScriptEngine scriptEngine)
{
_state = state;
_playoutModule = playoutModule;
_scriptEngine = scriptEngine;
_datetimeModule = _scriptEngine.ImportModule("datetime");
_lastCheckedTime = _state.CurrentTime;
}
public object current_time => ToPythonDateTime(_state.CurrentTime);
public object start_time => ToPythonDateTime(_state.Start);
public object finish_time => ToPythonDateTime(_state.Finish);
public bool is_done()
{
if (_playoutModule.FailureCount >= MaxFailures)
{
throw new InvalidOperationException(
$"Script execution halted after {MaxFailures} consecutive failures to add content."
);
}
if (_state.CurrentTime == _lastCheckedTime)
{
_noProgressCounter++;
if (_noProgressCounter >= MaxCallsNoProgress)
{
throw new InvalidOperationException(
$"Script execution halted after {MaxCallsNoProgress} consecutive calls to is_done() without time advancing.");
}
}
else
{
_lastCheckedTime = _state.CurrentTime;
_noProgressCounter = 0;
}
return _state.CurrentTime >= _state.Finish;
}
private object ToPythonDateTime(DateTimeOffset dto)
{
dynamic dt_constructor = _datetimeModule.datetime;
dynamic timedelta_constructor = _datetimeModule.timedelta;
dynamic timezone_constructor = _datetimeModule.timezone;
var offset = dto.Offset;
dynamic py_offset = _scriptEngine.Operations.Invoke(
timedelta_constructor,
0,
(int)offset.TotalSeconds
);
dynamic py_tzinfo = _scriptEngine.Operations.Invoke(
timezone_constructor,
py_offset
);
return _scriptEngine.Operations.Invoke(
dt_constructor,
dto.Year,
dto.Month,
dto.Day,
dto.Hour,
dto.Minute,
dto.Second,
dto.Millisecond * 1000,
py_tzinfo
);
}
}
}
@@ -0,0 +1,27 @@
using System.Collections.Concurrent;
using ErsatzTV.Core.Interfaces.Scheduling;
using ErsatzTV.Core.Scheduling.Engine;
namespace ErsatzTV.Core.Scheduling.ScriptedScheduling;
public class ScriptedPlayoutBuilderService : IScriptedPlayoutBuilderService
{
private readonly ConcurrentDictionary<Guid, ISchedulingEngine> _sessions = new();
public bool MockSession(ISchedulingEngine schedulingEngine, Guid buildId) =>
_sessions.TryAdd(buildId, schedulingEngine);
public Guid StartSession(ISchedulingEngine schedulingEngine)
{
var buildId = Guid.NewGuid();
_sessions[buildId] = schedulingEngine;
return buildId;
}
public ISchedulingEngine GetEngine(Guid buildId) => _sessions.GetValueOrDefault(buildId);
public void EndSession(Guid buildId)
{
_sessions.TryRemove(buildId, out _);
}
}